您的位置:首页 > 移动开发 > Android开发

Android数据存储方式及存储位置

2014-04-24 12:14 337 查看

Android数据存储方式及存储位置

Android数据存储是很重要的一个环节,有以下几种方式:

一、Shared Preference

使用:

SharedPreferences sp =
MainHello.this.getSharedPreferences("hello", 0);

int age = sp.getInt(“Age”, 0);		// read

SharedPreferences.Editor ed = sp.edit();	// write
ed.putString("Name", "mike");
ed.putInt("Age", 33);
ed.putFloat("Salary", 1080.55f);

ed.commit();


存储位置:

Data is stored in xml format, located at

/data/data/<package name>/shared_prefs/hello.xml

XML file Content:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="Name">mike</string>
<float name="Salary" value="1080.55" />
<int name="Age" value="33" />
</map>


二、Internal Storage

使用:

try {
String str = "Hello World";
FileOutputStream fos =
MainHello.this.openFileOutput("hello.txt", MODE_PRIVATE);
fos.write(str.getBytes());
fos.close();
}
catch (Exception e) {
e.printStackTrace();
}


存储位置:

/data/data/<package name>/files/hello.txt

三、External Storage

使用:

String str = "Hello World";
File file = new File(getExternalFilesDir(null), "hello.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(str.getBytes());
fos.close();


存储位置:

/mnt/sdcard/Android/data/<package name>/files/hello.txt

四、SQL Lite

使用:

public class MyDB extends SQLiteOpenHelper {

public MyDB(Context context) {
super(context, "TestDB", null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE stu (" +
"sid INTEGER," +
"sname TEXT)";
db.execSQL(sql);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Used when 模式更新
}
}
MyDB d = new MyDB(MainHello.this);
SQLiteDatabase db = d.getWritableDatabase();
db.execSQL("INSERT INTO stu(sid, sname) VALUES(3, 'Jason')");


存储位置:

/data/data/com.hezongjian/databases/

五、Content Provider

使用:

ContentResolver cr = getContentResolver();
Cursor cur = cr.query(android.provider.CallLog.Calls.CONTENT_URI, null, null, null, null);

cur.moveToFirst();

int num = cur.getColumnIndex(CallLog.Calls.NUMBER);

do
{
Log.e("CALLLOG", cur.getString(num));
}while(cur.moveToNext());

cur.close();

// android.permission.READ_CONTACTS permission
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: