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.j开发者_StackOverflow中文版ava 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
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.
精彩评论