first activity.
public class MainActivity extends ActionBarActivity {
private Button button;
private SharedPreferences preferences;
private String[] name = {"aa", "bb", "cc"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
preferences=getSharedPreferences("testarray", MODE_PRIVATE);
for(int i=0;i<3;i++)
{
SharedPreferences.Editor editor=preferences.edit();
editor.putString("str"+i, name[i]);
editor.commit();
}
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,Secondact.class));
}
});
}
}
second activity
public class Secondact extends ActionBarActivity {
private Button button;
private SharedPreferences preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
preferences = getSharedPreferences("testarray", MODE_PRIVATE);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
for(int i=0;i<3;i++)
{
Log.d("aa", preferences.getString("str"+i, " "));
}
}
});
}
}
using set of strings
public class MainActivity extends ActionBarActivity {
private Button button;
private SharedPreferences preferences;
private String[] name = {"aa", "bb", "cc"};
Set<String> values = new HashSet<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
preferences=getSharedPreferences("testarray", MODE_PRIVATE);
for(int i=0;i<3;i++)
{
values.add(name[i]);
}
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
for(int i=0;i<3;i++)
{
SharedPreferences.Editor editor=preferences.edit();
editor.putStringSet("str", values);
editor.commit();
}
startActivity(new Intent(MainActivity.this,Secondact.class));
}
});
}
}
public class Secondact extends ActionBarActivity {
private Button button;
private SharedPreferences preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
preferences = getSharedPreferences("testarray", MODE_PRIVATE);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Set<String> values = preferences.getStringSet("str", null);
String[] name = values.toArray(new String[values.size()]);
for (int i = 0; i < values.size(); i++) {
Log.d("aa", name[i]);
}
}
});
}
}
1
solved How to store the array of string in shared preferences? [closed]