Android编程之SharedPreferences文件存储操作实例分析


本文实例讲述了Android编程之SharedPreferences文件存储操作的方法。分享给大家供大家参考。具体分析如下:

SharedPreferences类提供了一种简单的文件存储功能,像程序的配置文件可以通过它来实现。

源代码:

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程序设计有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3