【发布时间】:2017-12-26 04:10:11
【问题描述】:
我有两个活动。假设“A”和“B”,活动“A”有一个名为“Get”的按钮,每次单击后都会生成一个新字符串,并一次显示一个。活动“A”还有一个“发送”按钮,它将生成的字符串发送到另一个活动“B”。当活动“B”接收到数据时,它必须将数据填充到 ListView 中。
下面是简单的机器步骤:
In Activity "A"
1 - Generate 1 string by pressing the generate button
2 - text will be displayed in textView
3 - "send" button will send the text from textView to another activity "B" ( I'm using sharedPreference)
In Activity "B"
4 - receive the data sent by Activity "A" ( I'm using sharedPreference)
5 - populate string into a listview
6 - go to step 1 again.
我的麻烦是,每当我单击发送按钮时,它都会将字符串发送到活动“B”,但是当我再次执行相同的任务时,它只会填充最后生成的字符串。换句话说,我的代码只填充了一个字符串。
到目前为止,我已经尝试过以下代码,我们将不胜感激。
@Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.generateButton:
generateString();
break;
case R.id.send:
//displayText is a textView
String text = displayText.getText().toString();
// data sharing using sharedPref
SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences("lado", MODE_PRIVATE).edit();
editor.putString("mug",text);
editor.apply();
break;
}
---------
活动 B
ListView textList = (ListView) findViewById(R.id.list);
SharedPreferences prefs = getSharedPreferences("lado", MODE_PRIVATE);
final String text = prefs.getString("mug", "No name defined");
String[] list = new String[]{name};
// Create a List from String Array elements
final List<String> fav_list = new ArrayList<>(Arrays.asList(list));
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,list);
// Assign adapter to ListView
textList.setAdapter(adapter);
【问题讨论】:
-
请给我看你的完整代码并解释你想要什么:)
-
在共享首选项中使用相同的键将覆盖您以前的值,因此请保留一个列表或数组以在共享首选项中存储一组值。
标签: java android sharedpreferences