Android数据存储汇总

时间:2021-08-06 10:32:38

1.sharedpreference,存储简单的信息,比如用户名,密码

package com.google.datastore.sharep;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.google.datastore.R;

public class SharePreferences extends Activity{

private EditText editUsername = null;
private EditText editPassword = null;

private Button bt = null;
SharedPreferences userInfo = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
       setContentView(R.layout.sharepreferences);
       
       editUsername = (EditText)findViewById(R.id.username);
editPassword = (EditText)findViewById(R.id.password);
bt = (Button)findViewById(R.id.bt);
//String s = Environment.getExternalStorageDirectory().toString();
       initData();
       
        bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = userInfo.edit();
editor.putString("name", editUsername.getText().toString());
editor.putString("password", editPassword.getText().toString());
editor.commit();
}
});
}

//
private void initData() {
userInfo = getSharedPreferences("user_info", Context.MODE_PRIVATE);
String username = userInfo.getString("name", "");
String password = userInfo.getString("password", "");

editUsername.setText(username);
editPassword.setText(password);
}

}

2.网络存储

package com.google.datastore.net;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.util.ByteArrayBuffer;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.datastore.R;

//有问题,思路就是这样,2.3以后不能在主线程中访问网络
public class Net extends Activity{
private TextView tvNet;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.netget);

tvNet = (TextView)findViewById(R.id.textNet);
new Thread(download).start();
}
//
Runnable download = new Runnable() {
@Override
public void run() {
String msg = "";
try {
URL url = new URL("http://linux.chinaitlab.com/command/723482.html");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(6 * 1000);
conn.setConnectTimeout(5 * 1000);

InputStream is = conn.getInputStream();
Log.d("lixp", "is ========" + is);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(100);

int current = 0;
while((current = bis.read()) != -1) {
baf.append((byte)current);
}

msg = new String(baf.toByteArray(), "UTF-8");
Log.d("lixp", "msg ========" + msg);
}
catch(Exception e) {
msg = e.getMessage();
Log.e("lixp", "e ===" + e);
}
//tvNet.setText(msg);
}
};
}

3.文件存储

package com.google.datastore.filestore;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.datastore.R;

public class FileActivity extends Activity{
private EditText name;
private EditText age;
private FileService fileService;
private Button saveButton;
private Button readButton;
private Button saveToSd;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.file);

name = (EditText)findViewById(R.id.filename);
                age = (EditText)findViewById(R.id.content);
                saveButton = (Button)findViewById(R.id.save);
                readButton = (Button)findViewById(R.id.read);
               saveToSd = (Button)findViewById(R.id.saveToSdCard);
        
               fileService = new FileService(FileActivity.this);
        
               saveButton.setOnClickListener(listener);
               saveToSd.setOnClickListener(listener);
              readButton.setOnClickListener(listener);
}

private View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Button btn = (Button)v;
String filename = name.getText().toString();
String content = age.getText().toString();
switch (btn.getId()) {
case R.id.save:

try {
fileService.save(filename, content);
Toast.makeText(FileActivity.this, R.string.fileSaveSuccess,
Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(FileActivity.this, R.string.fileSaveException,
Toast.LENGTH_LONG).show();
}
break;

case R.id.saveToSdCard:           
            if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
try {
fileService.saveToSd(filename, content);
Toast.makeText(FileActivity.this,
R.string.fileSaveSuccess, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(FileActivity.this, R.string.fileSaveException,
Toast.LENGTH_LONG).show();
}
} else {
Log.e("lixp", "Environment.getExternalStorageState() is not equals ..");
}

break;

case R.id.read:
            //有错误5-16
            FileService fileService = new FileService(getApplicationContext());
        Intent intent = getIntent();
        String fileName = intent.getStringExtra("fileName");
       
        Log.d("lixp", "fileService.read(fileName) = " + fileService.read(fileName));
        /*try {
        content.setText(fileService.read(fileName));
        }
        catch(Exception e) {
        e.printStackTrace();
        }*/
            break;            
default:
break;
}
}
};
}

package com.google.datastore.filestore;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class FileService {
private Context context;
public FileService(Context context) {
super();
this.context = context; 
}

/**
* 保存文件
*/
public void save(String fileName, String content) {

try {
//以私有方式读写数据,创建出来的文件只能被该应用访问
FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_WORLD_READABLE);
fileOutputStream.write(content.getBytes());
fileOutputStream.close();

}
catch(Exception e) {
Log.e("lixp", "save() e ============" + e);
}
}

/**
* 保存文件到sdcard
*/
public void saveToSd(String fileName, String content){

try {
//File file = new File(new File("/mnt/sdcard"), fileName);
//考虑不同版本的sdCard目录不同,采用系统提供的API获取SD卡的目录
//命名要避免冲突,和本包的冲突了
File file = new File(Environment.getExternalStorageDirectory(), fileName);
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(content.getBytes());
fileOutputStream.close();

}
catch(Exception e) {
Log.e("lixp", "saveToSd() e =============" + e);
}
}

/**
* 读取文件内容
*/
public String read(String fileName) {
byte[] data = null;
try {
FileInputStream fileInputStream = context.openFileInput(fileName);
////把每次读取的内容写入到内存中,然后从内存中获取
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;

//只要没读完,不断的读取
while((len = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
//得到内存中的数据 以二进制存放的
data = outputStream.toByteArray();

}
catch(Exception e) {
Log.e("lixp", "read() e ===========" + e);
}
//根据二进制数据转换成所对应的字符串
return new String(data);
}

}

4.SQLITE数据库存储
package com.google.datastore.sqllite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

/*SQLiteOpenHelper:是一个辅助类,这个类主要用于生产一个数据库,并对数据库的版本进行管理。此类为一抽象类,使用是需要继承此类并实现该类的方法 
onCreate(SQLiteDatabase):在数据库第一次生产的时候会调用这个方法,一般我们在这个方法里边生产数据库表。 
onUpgrade(SQLiteDatabase,int,int):当数据库需要升级的时候,Android系统会主动的调用这个方法。一般我们在这个方法里边删除数据库表,并建立新的数据库表,当然是否还需要做其他的操作,完全取决于应用程序的需求。 
onOpen(SQLiteDatabase):这是当打开数据库时的回调函数,一般也不会用到。 
   调用程序方法返回SQLiteDatabase对象。 
当在程序当中调用这个类的方法getWritableDatabase()或者getReadableDatabase()方法的时候,如果当时没有数据,那么Android系统就会自动生产一个数据库。数据库使用完后记得调用close()方法关闭数据库。 
*/
public class DbOpenHelper extends SQLiteOpenHelper{
    public static final String TABLE_NAME = "fb";
public static final String ID = "_id";
public static final String COUNTRY = "country";
       public static final String CODE = "code";
    
//构造方法
public DbOpenHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS"
+ TABLE_NAME + "("
+ ID + "INTEGER PRIMARY KEY,"
+ COUNTRY + "VARCHAR,"
+ CODE + "INTEGER)"
);
}

//升级数据库
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}

package com.google.datastore.sqllite;

import android.app.Activity;
import android.os.Bundle;
import com.google.datastore.R;

public class DbActivity extends Activity{
DbOpenHelper helper = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);    
   /**
    * 得到SQLiteDatabase的实例
    */
  /* helper = new DbOpenHelper(this, FB, null, version);
   //如果没有数据库,自动创建
   SQLiteDatabase db = helper.getWritableDatabase();*/
}

/**
* 插入数据
*/
/*ContentValues values = new ContentValues();
values.put(DBHelper.COUNTRY, "中国");  
    values.put(DBHelper.CODE, 86);  
    db.insert(DBHelper.TB_NAME,DBHelper.ID, values);

*//**
* 改动数据
*//*
db.insert(DBHelper.TB_NAME,DBHelper.ID,null);
    values.clear();
    values.put(DBHelper.COUNTRY, "意大利");
    values.put(DBHelper.CODE, 39);
    db.update(DBHelper.TB_NAME, values,DBHelper.ID + " = 2",null);
    
    *//**
     * execSQL 执行SQL语言
     *//*
    db.execSQL("INSERT INTO "
            + DBHelper.TB_NAME + "("
            + DBHelper.COUNTRY + ","
            + DBHelper.CODE + ") VALUES "
            + "('洪都拉斯',504)");

*//**
     * 查询数据
     *//*
    Cursor c = db.query(DBHelper.TB_NAME,null,null,null,null,null,
    DBHelper.CODE+" DESC");
    //删除数据
    db.delete(DBHelper.TB_NAME,null,null);
    */
}