你好,游客 登录 注册 搜索
背景:
阅读新闻

Android存储——SharedPreference存储(用户偏好存储)

[日期:2012-06-01] 来源:Linux社区  作者:jasonchris [字体:大 中 小]

下面这个程序就是通过其他程序访问上面的程序的SharedPreference.

  1. package cn.jason.io;  
  2.   
  3. import Android.app.Activity;  
  4. import android.content.Context;  
  5. import android.content.SharedPreferences;  
  6. import android.content.pm.PackageManager.NameNotFoundException;  
  7. import android.os.Bundle;  
  8. import android.widget.TextView;  
  9.   
  10. public class ReadOtherPreferenceActivity extends Activity {  
  11.     /** Called when the activity is first created. */  
  12.     @Override  
  13.     public void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.main);  
  16.           
  17.         Context useCount = null;  
  18.           
  19.         try {  
  20.             useCount = createPackageContext("cn.jason.store", Context.CONTEXT_IGNORE_SECURITY);  
  21.         } catch (NameNotFoundException e) {  
  22.             e.printStackTrace();  
  23.         }  
  24.           
  25.         SharedPreferences preferences = useCount.getSharedPreferences("jason", Context.MODE_WORLD_READABLE);  
  26.           
  27.      // 读取数据   
  28.     int num = preferences.getInt("num", 0);  
  29.     TextView show = (TextView) findViewById(R.id.show);  
  30.     // 显示读取的数据内容   
  31.     show.setText("" + num );  
  32.           
  33.     }  
  34. }  

上面的代码关键是先建立报级别的上下文,然后读取到其他包的SharedPreferences。

更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11

linux
相关资讯       Android开发入门 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款