qq_33721362 2016-01-30 23:13 采纳率: 14.3%
浏览 5671

怎么只写一个SharedPreferences让它保存多个数据,而不用像下面代码一样写多个SharedPreferences来保存数据

package com.myedit;

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.view.View.*;
import android.content.*;

public class MainActivity extends Activity
{

private SharedPreferences sp,spa,spb;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final EditText a1=(EditText)findViewById(R.id.a1);
    final EditText a2=(EditText)findViewById(R.id.a2);
    final EditText a3=(EditText)findViewById(R.id.a3);
    Button   a4=(Button)findViewById(R.id.a4);
    final TextView a5=(TextView)findViewById(R.id.a5);
    final TextView a6=(TextView)findViewById(R.id.a6);
    final TextView a7=(TextView)findViewById(R.id.a7);
//保存内容
sp=getSharedPreferences("ba",MODE_PRIVATE);
spa=getSharedPreferences("bb",MODE_PRIVATE);
spb=getSharedPreferences("bc",MODE_PRIVATE);
String str=sp.getString("name","");
String s=spa.getString("name","");
String st=spb.getString("name","");
a5.setText(str);
a6.setText(s);
a7.setText(st);
    a4.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View p1)
            {
                // TODO: Implement this method
                a5.setText(a1.getText().toString());
                a6.setText(a2.getText().toString());
                a7.setText(a3.getText().toString());
                //读取保存内容



                sp.edit().putString("name",a5.getText().toString()).commit();
                spa.edit().putString("name",a6.getText().toString()).commit();
                spb.edit().putString("name",a7.getText().toString()).commit();

            }
        });
}

}
图片图片图片图片

  • 写回答

2条回答

  • threenewbee 2016-01-30 23:24
    关注
     private SharedPreferences sp,spa,spb;
    ->
    private SharedPreferences sp;
    
    sp=getSharedPreferences("ba",MODE_PRIVATE);
    //去掉spa=getSharedPreferences("bb",MODE_PRIVATE);
    //去掉spb=getSharedPreferences("bc",MODE_PRIVATE);
    
    String xx = sp.getString("name","");
    String str=xx.split(",")[0];
    String s=xx.split(",")[1];
    String st=xx.split(",")[2];
    
    sp.edit().putString("name",a5.getText().toString() + "," + a6.getText().toString() + "," + a7.getText().toString()).commit();
    //去掉spa.edit().putString("name",a6.getText().toString()).commit();
    //去掉spb.edit().putString("name",a7.getText().toString()).commit();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝