how to save data using shared preferences?

廉价感情. 提交于 2019-12-08 09:06:45

问题


i am new developer in android application.i have used shared preference concept to share the data from one activity to another activity.i have implemented code as follows

Main.java

public class Main extends Activity 
{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TableLayout table=(TableLayout)findViewById(R.id.tableLayout1);
         table.removeAllViews();
        String sName = null;
        for(int i=0;i<10;i++)
        {
            TableRow row=new TableRow(Main.this);
            row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
            TextView  name=new TextView(Main.this);

            name.setText(" HAI PRASAD"+i);

          sName=name.getText().toString();

            Log.v("sName 1111111","-->"+sName);

             getSharedPreferences("Values", 0).edit().putString("NAMES",sName).commit();


            name.setGravity(Gravity.LEFT);
            name.setTypeface(Typeface.MONOSPACE);

              row.addView(name);

              table.addView(row);  
        }

        ((Button)findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent it=new Intent(Main.this,Main2.class);
                startActivity(it);
            }
        });


}

here i am printing a name ten times and saving with shared preference as

TextView  name=new TextView(Main.this);

            name.setText(" HAI PRASAD"+i);

          sName=name.getText().toString();

            Log.v("sName 1111111","-->"+sName);

             getSharedPreferences("Values", 0).edit().putString("NAMES",sName).commit();

here i would like to get the same data in Main2.class.the main2.java as follows

public class Main2 extends Activity 
{


@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

    setContentView(R.layout.main2);

    String name=getSharedPreferences("Values", 0).getString("NAMES", "");

    ((TextView)findViewById(R.id.textView1)).setText(name);
}

but here i am getting only one name that as HAI PRASAD9

how can i get one by one

HAI PRASAD0 HAI PRASAD1 HAI PRASAD2 HAI PRASAD3 HAI PRASAD4 ......so on?

please any one can help

thanks in advance


回答1:


You need to have multiple keys for storing multiple items. Something like that:

for (int i = 0; i < 10; i++) {
        getSharedPreferences("Values" + i, 0).edit().putString("Key" + i, "STring" + i);
    }
    for (int i = 0; i < 10; i++) {
        getSharedPreferences("Values" + i, 0).getString("Key" + i, "");
    }

Hope this helps.



来源:https://stackoverflow.com/questions/6015197/how-to-save-data-using-shared-preferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!