Save data using shared preferences in android

I am a new developer in android applications.i would like to save data using a common concept of preferences. I save the data in one action and get the same data in another activity.here, I would like to send String a [] = {"one", "two", "three"} one kind of activity to another. I wrote the code as follows

Main1.java

public class Main1 extends Activity
 {

  @Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    SharedPreferences shp=getSharedPreferences("TEXT", 0);
    final Editor et=shp.edit();

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

        @Override
        public void onClick(View v) {

            String s1=((EditText)findViewById(R.id.editText1)).getText().toString();
            et.putString("DATA", s1);

            String s2[]={"one","two","three"};

            //here i would like to save the string array

            et.commit();
            Intent it=new Intent(Main1.this,Main2.class);
            startActivity(it);

        }
    });


}

Main2.java

@Override

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main2);
    String kk=getSharedPreferences("TEXT", 0).getString("DATA", null);

    //here i would like to get the string array of Main1.java

    ((EditText)findViewById(R.id.editText1)).setText(kk);
}

can we get the values ​​of a string array from Main1.java to Main2.java?

+3
source share
3 answers

Put it in its original intention:

Intent it = new Intent(Main1.this,Main2.class);
it.putExtra("MY_STRING_ARRAY", s2);

Return it to the second activity:

String[] myStringArray = getIntent().getStringArrayExtra("MY_STRING_ARRAY");
+1
source

, putExtra Intent

Intent i = new Intent(Activity1.this, Activity2.class);
i.putExtra("data1", "some data");
i.putExtra("data2", "another data");
i.putExtra("data3", "more data");
startActivity(i);

Activity2,

Object data1 = getIntent().getExtras().get("data1");

,

0

If you want to save your information through SharedPreference, just do not pass it by type of activity, use the following code:

SharedPreferences settings = getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);
    SharedPreferences.Editor prefEditor = settings.edit();
    prefEditor.putString("string_preference", "some_string");
    prefEditor.putInt("int_preference", 18);
    prefEditor.commit(); 

The commit command is responsible for actually storing data in SharedPreferences.

0
source

All Articles