Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

save the data using shared preference in android

i am new developer in android applications.i would like to save the data using shared preference concept.i am saving the data in one activity and get the same data in another activity.here i would like to send the String a[]={"one","two","three"} one activity to another activity.i have written 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 string array values from Main1.java to Main2.java?

like image 492
prasad.gai Avatar asked Dec 05 '25 04:12

prasad.gai


1 Answers

Put it into the starting intent:

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

Get it back in the second activity:

String[] myStringArray = getIntent().getStringArrayExtra("MY_STRING_ARRAY");
like image 100
denis.solonenko Avatar answered Dec 07 '25 19:12

denis.solonenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!