本文实例讲述了Android编程之SharedPreferences文件存储操作的方法。分享给大家供大家参考。具体分析如下:
SharedPreferences类提供了一种简单的文件存储功能,像程序的配置文件可以通过它来实现。
源代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package com.test.sharedpreferences;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
public class test_sharedpreferences extends Activity
{
SharedPreferences file;
SharedPreferences.Editor editor;
TextView text;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.main);
//获得配置文件
file = getSharedPreferences( "test_config" , 0 );
editor = file.edit();
//写入配置:Id:10000 Name:Jdh
editor.putInt( "Id" , 10000 );
editor.putString( "Name" , "Jdh" );
editor.commit();
//读取配置
int id = 0 ;
id = file.getInt( "Id" , 0 );
String str;
str = file.getString( "Name" , null );
text = (TextView)findViewById(R.id.textView1);
text.setText( "Id:" + id + " Name:" + str);
}
}
|
效果图如下:
希望本文所述对大家的Android程序设计有所帮助。