灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:2047回复:0

android学习笔记10-----SharedPreferences实现软件参数的保存和获取

楼主#
更多 发布于:2012-09-06 13:44


很多时候我们开发软件需要向用户提供软件参数设置功能,如电子书软件的背景颜色设置,喜好设置等。在Android的应用的使用SharedPreferences类来
保存软件设置参数非常方便。
使用SharedPreferences类保存数据,其实是将这些参数保存在xml文件中,文件存放在/data/data/包名/shared_prefs目录下:




点击保存后,




将test.xml导出,打开




即为我们保存的数据。
点击读取按钮:




读取正确。
代码:

[java]
import Android.app.Activity;
import Android.content.Context;
import Android.content.SharedPreferences;
import Android.content.SharedPreferences.Editor;
import Android.os.Bundle;
import Android.view.View;
import Android.view.View.OnClickListener;
import Android.widget.Button;
import Android.widget.EditText;
import Android.widget.TextView;
import Android.widget.Toast;

public class SharedPreferencesActivity extends Activity
{
    private EditText nameEditText;
    private EditText ageEditText;
    private Button   save;
    private Button   read;
    private Button   exit;
    private TextView resulTextView;
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        nameEditText=(EditText)findViewById(R.id.name);
        ageEditText=(EditText)findViewById(R.id.age);
        save=(Button)findViewById(R.id.save);
        read=(Button)findViewById(R.id.read);
        exit=(Button)findViewById(R.id.exit);
        resulTextView=(TextView)findViewById(R.id.result);
        
        save.setOnClickListener(listener);
        read.setOnClickListener(listener);
        exit.setOnClickListener(listener);
        
    }
    
    private OnClickListener listener=new OnClickListener()
    {        
        @Override
        public void onClick(View v)
        {
            Button button=(Button)v;
            SharedPreferences sharedPreferences=SharedPreferencesActivity.
            this.getSharedPreferences("test", Context.MODE_PRIVATE);
            switch (button.getId())
            {
                case R.id.save:
                    String name=nameEditText.getText().toString();
                    String age=ageEditText.getText().toString();                                        
                    Editor editor=sharedPreferences.edit();
                    editor.putString("name", name);
                    editor.putInt("age", Integer.parseInt(age));
                    editor.commit(); //内容提交  
                    Toast.makeText(SharedPreferencesActivity.this, "保存成功",  
                            Toast.LENGTH_SHORT).show();
                    break;
                    
                case R.id.read:
                    String namevalue= sharedPreferences.getString("name", "");//如果存在name返回name的值,如果不存在该元素,返回“”  
                    int agevalue= sharedPreferences.getInt("age", -1);
                    resulTextView.setText("姓名是:"+namevalue+"n"+"年龄是:"+agevalue);
                    Toast.makeText(SharedPreferencesActivity.this, "读取成功",  
                            Toast.LENGTH_SHORT).show();
                    break;
                    
                case R.id.exit:
                    Android.os.Process.killProcess(Android.os.Process.myPid());
                    break;
    
                default:
                    break;
            }
            
        }
    };
}
import Android.app.Activity;
import Android.content.Context;
import Android.content.SharedPreferences;
import Android.content.SharedPreferences.Editor;
import Android.os.Bundle;
import Android.view.View;
import Android.view.View.OnClickListener;
import Android.widget.Button;
import Android.widget.EditText;
import Android.widget.TextView;
import Android.widget.Toast;
public class SharedPreferencesActivity extends Activity
{
private EditText nameEditText;
private EditText ageEditText;
private Button   save;
private Button   read;
private Button   exit;
private TextView resulTextView;

@Override
public void onCreate(Bundle savedInstanceState)
{
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  nameEditText=(EditText)findViewById(R.id.name);
  ageEditText=(EditText)findViewById(R.id.age);
  save=(Button)findViewById(R.id.save);
  read=(Button)findViewById(R.id.read);
  exit=(Button)findViewById(R.id.exit);
  resulTextView=(TextView)findViewById(R.id.result);
  
  save.setOnClickListener(listener);
  read.setOnClickListener(listener);
  exit.setOnClickListener(listener);
  
}

private OnClickListener listener=new OnClickListener()
{  
  @Override
  public void onClick(View v)
  {
   Button button=(Button)v;
   SharedPreferences sharedPreferences=SharedPreferencesActivity.
   this.getSharedPreferences("test", Context.MODE_PRIVATE);
   switch (button.getId())
   {
    case R.id.save:
     String name=nameEditText.getText().toString();
     String age=ageEditText.getText().toString();          
     Editor editor=sharedPreferences.edit();
     editor.putString("name", name);
     editor.putInt("age", Integer.parseInt(age));
     editor.commit(); //内容提交
     Toast.makeText(SharedPreferencesActivity.this, "保存成功",
       Toast.LENGTH_SHORT).show();
     break;
    
    case R.id.read:
     String namevalue= sharedPreferences.getString("name", "");//如果存在name返回name的值,如果不存在该元素,返回“”
     int agevalue= sharedPreferences.getInt("age", -1);
     resulTextView.setText("姓名是:"+namevalue+"n"+"年龄是:"+agevalue);
     Toast.makeText(SharedPreferencesActivity.this, "读取成功",
       Toast.LENGTH_SHORT).show();
     break;
    
    case R.id.exit:
     Android.os.Process.killProcess(Android.os.Process.myPid());
     break;

    default:
     break;
   }
  
  }
};
}

布局文件:www.atcpu.com

[java]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:orientation="vertical"
    Android:layout_width="fill_parent"
    Android:layout_height="fill_parent"
    >
    <LinearLayout  
                Android:layout_width="match_parent"  
                Android:id="@+id/linearLayout1"  
                Android:layout_height="wrap_content">
        <TextView  
                Android:text="姓名:"  
                Android:textSize="20sp"
                Android:layout_width="wrap_content"  
                Android:layout_height="wrap_content"></TextView>
                
        <EditText  
                Android:id="@+id/name"  
                Android:layout_width="fill_parent"
                Android:layout_height="wrap_content"></EditText>
                
    </LinearLayout>
    <LinearLayout  
                Android:layout_width="match_parent"  
                Android:id="@+id/linearLayout2"  
                Android:layout_height="wrap_content">
                
        <TextView  
                Android:text="年龄:"  
                Android:textSize="20sp"
                Android:layout_width="wrap_content"  
                Android:layout_height="wrap_content"></TextView>
                
        <EditText  
                Android:id="@+id/age"  
                Android:layout_width="fill_parent"
                Android:layout_height="wrap_content"></EditText>
                
    </LinearLayout>
    <LinearLayout  
                Android:layout_width="match_parent"  
                Android:id="@+id/linearLayout3"  
                Android:layout_height="wrap_content">
                
        <Button  
                Android:text="保存数据"  
                Android:id="@+id/save"  
                Android:layout_width="wrap_content"  
                Android:layout_height="wrap_content"></Button>
                
        <Button  
                Android:text="读取数据"  
                Android:id="@+id/read"  
                Android:layout_width="wrap_content"  
                Android:layout_height="wrap_content"></Button>
                
        <Button  
                Android:text="退出"  
                Android:id="@+id/exit"  
                Android:layout_width="wrap_content"  
                Android:layout_height="wrap_content"></Button>
                
    </LinearLayout>
    <TextView  
                Android:text="显示读取值"  
                Android:id="@+id/result"  
                Android:layout_width="wrap_content"  
                Android:layout_height="wrap_content"></TextView>

</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:orientation="vertical"
    Android:layout_width="fill_parent"
    Android:layout_height="fill_parent"
    >
    <LinearLayout
       Android:layout_width="match_parent"
       Android:id="@+id/linearLayout1"
       Android:layout_height="wrap_content">
        <TextView
          Android:text="姓名:"
          Android:textSize="20sp"
          Android:layout_width="wrap_content"
          Android:layout_height="wrap_content"></TextView>
          
        <EditText
          Android:id="@+id/name"
          Android:layout_width="fill_parent"
          Android:layout_height="wrap_content"></EditText>
          
    </LinearLayout>
    <LinearLayout
       Android:layout_width="match_parent"
       Android:id="@+id/linearLayout2"
       Android:layout_height="wrap_content">
      
        <TextView
          Android:text="年龄:"
          Android:textSize="20sp"
          Android:layout_width="wrap_content"
          Android:layout_height="wrap_content"></TextView>
          
        <EditText
          Android:id="@+id/age"
          Android:layout_width="fill_parent"
          Android:layout_height="wrap_content"></EditText>
          
    </LinearLayout>
    <LinearLayout
       Android:layout_width="match_parent"
       Android:id="@+id/linearLayout3"
       Android:layout_height="wrap_content">
      
        <Button
          Android:text="保存数据"
          Android:id="@+id/save"
          Android:layout_width="wrap_content"
          Android:layout_height="wrap_content"></Button>
          
        <Button
          Android:text="读取数据"
          Android:id="@+id/read"
          Android:layout_width="wrap_content"
          Android:layout_height="wrap_content"></Button>
          
        <Button
          Android:text="退出"
          Android:id="@+id/exit"
          Android:layout_width="wrap_content"
          Android:layout_height="wrap_content"></Button>
          
    </LinearLayout>
    <TextView
       Android:text="显示读取值"
       Android:id="@+id/result"
       Android:layout_width="wrap_content"
       Android:layout_height="wrap_content"></TextView>
</LinearLayout>


每次启动程序时,自动读取参数,只要做简单改动:

[java]
import Android.app.Activity;
import Android.content.Context;
import Android.content.SharedPreferences;
import Android.content.SharedPreferences.Editor;
import Android.os.Bundle;
import Android.view.View;
import Android.view.View.OnClickListener;
import Android.widget.Button;
import Android.widget.EditText;
import Android.widget.TextView;
import Android.widget.Toast;

public class SharedPreferencesActivity extends Activity
{
    private EditText nameEditText;
    private EditText ageEditText;
    private Button   save;
    private Button   read;
    private Button   exit;
    private TextView resulTextView;
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        nameEditText=(EditText)findViewById(R.id.name);
        ageEditText=(EditText)findViewById(R.id.age);
        save=(Button)findViewById(R.id.save);
        read=(Button)findViewById(R.id.read);
        exit=(Button)findViewById(R.id.exit);
        resulTextView=(TextView)findViewById(R.id.result);
        
        save.setOnClickListener(listener);
        read.setOnClickListener(listener);
        exit.setOnClickListener(listener);
        
        SharedPreferences sharedPreferences=SharedPreferencesActivity.
        this.getSharedPreferences("test", Context.MODE_PRIVATE);
        String namevalue= sharedPreferences.getString("name", "");
        int agevalue= sharedPreferences.getInt("age", -1);
        nameEditText.setText(namevalue);
        ageEditText.setText(String.valueOf(agevalue));      
    }
    
    private OnClickListener listener=new OnClickListener()
    {        
        @Override
        public void onClick(View v)
        {
            Button button=(Button)v;
            SharedPreferences sharedPreferences=SharedPreferencesActivity.
            this.getSharedPreferences("test", Context.MODE_PRIVATE);
            switch (button.getId())
            {
                case R.id.save:
                    String name=nameEditText.getText().toString();
                    String age=ageEditText.getText().toString();                                        
                    Editor editor=sharedPreferences.edit();
                    editor.putString("name", name);
                    editor.putInt("age", Integer.parseInt(age));
                    editor.commit(); //内容提交  
                    Toast.makeText(SharedPreferencesActivity.this, "保存成功",  
                            Toast.LENGTH_SHORT).show();
                    break;
                    
                case R.id.read:
                    String namevalue= sharedPreferences.getString("name", "");
                    int agevalue= sharedPreferences.getInt("age", -1);
                    resulTextView.setText("姓名是:"+namevalue+"n"+"年龄是:"+agevalue);
                    Toast.makeText(SharedPreferencesActivity.this, "读取成功",  
                            Toast.LENGTH_SHORT).show();
                    break;
                    
                case R.id.exit:
                    Android.os.Process.killProcess(Android.os.Process.myPid());
                    break;
    
                default:
                    break;
            }
            
        }
    };
}




若想保存的xml文件被其他文件访问,应修改:
SharedPreferences sharedPreferences=SharedPreferencesActivity.
this.getSharedPreferences("test", Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);





可以看到其读写权限发生变化

测试的其他Activity

[java]
import Android.app.Activity;
import Android.content.Context;
import Android.content.SharedPreferences;
import Android.content.pm.PackageManager.NameNotFoundException;
import Android.os.Bundle;
import Android.util.Log;

public class LogActivity extends Activity
{
    private static final String TAG="LogActivity";

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //Log.i(TAG, "TAG打印测试");  
        
        try
        {
            Context context=this.createPackageContext("com.luku.SharedPreferences",
                    Context.CONTEXT_IGNORE_SECURITY);
            SharedPreferences sharedPreferences=context.getSharedPreferences
                    ("test", Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
            String namevalue= sharedPreferences.getString("name", "");
            int agevalue= sharedPreferences.getInt("age", -1);
            Log.i(TAG, "名字是:"+namevalue+","+"年龄为:"+agevalue);
        } catch (NameNotFoundException e)
        {
            // TODO Auto-generated catch block  
            e.printStackTrace();
        }
        
        
    }
}
import Android.app.Activity;
import Android.content.Context;
import Android.content.SharedPreferences;
import Android.content.pm.PackageManager.NameNotFoundException;
import Android.os.Bundle;
import Android.util.Log;
public class LogActivity extends Activity
{
private static final String TAG="LogActivity";
@Override
public void onCreate(Bundle savedInstanceState)
{
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  //Log.i(TAG, "TAG打印测试");
  
  try
  {
   Context context=this.createPackageContext("com.luku.SharedPreferences",
     Context.CONTEXT_IGNORE_SECURITY);
   SharedPreferences sharedPreferences=context.getSharedPreferences
     ("test", Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
   String namevalue= sharedPreferences.getString("name", "");
   int agevalue= sharedPreferences.getInt("age", -1);
   Log.i(TAG, "名字是:"+namevalue+","+"年龄为:"+agevalue);
  } catch (NameNotFoundException e)
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  
}
}





由其他程序访问成功!



喜欢0 评分0
游客

返回顶部