【发布时间】:2018-08-22 18:50:02
【问题描述】:
我有两个活动
第一个活动-
- 用于获取editText中的字符串值
- 将值传递给第二个活动
第二个活动——
- 从第一个活动中获取价值
- 将值放入ArrayList并在listview中显示
- 将值放入集合并存储在共享首选项中。
我希望这些事情发生,但我不知道我的代码存在问题。我的 ListView 不显示任何内容。
这是我的代码:
第一个活动
public class History extends AppCompatActivity {
Button translate;
Button next;
EditText enterText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
enterText = findViewById(R.id.editText);
next = findViewById(R.id.btnNext);
translate = findViewById(R.id.buttonTranslate);
View.OnClickListener addlistener = new View.OnClickListener() {
@Override
public void onClick(View view) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(enterText.getWindowToken(), 0);
if(enterText != null)
{
String input = enterText.getText().toString();
Intent i= new Intent(History.this,MainActivity.class);
i.putExtra("myHistory",input);
enterText.setText("");
}else
{
Toast.makeText(getBaseContext(),"Input Field is empty",Toast.LENGTH_SHORT).show();
}
}
};
translate.setOnClickListener(addlistener);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(History.this,MainActivity.class);
startActivity(intent);
}
});
第二个活动
public class MainActivity extends AppCompatActivity {
private ListView listView;
private ArrayAdapter<String> adapter;
private ArrayList<String> toDelete;
ArrayList<String> itemList = new ArrayList<String>();
SharedPreferences.Editor editor ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, itemList);
toDelete = new ArrayList<>();
listView = findViewById(R.id.listView);
listView.setAdapter(adapter);
final SharedPreferences transHistory = getSharedPreferences("SaveHistory",Context.MODE_PRIVATE);
final Set<String> tHistory = new HashSet<String>();
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("myHistory");
itemList.add(value);
tHistory.addAll(itemList);
}
editor = transHistory.edit();
editor.putStringSet("history",tHistory);
editor.apply();
adapter.notifyDataSetChanged();
}
【问题讨论】:
-
我在您的代码中没有看到对
startActivity(i)的调用,而数据在addlistener中。 -
@Skye 如果不想进行其他活动并想发送数据,那么您为什么要使用 Intent?
-
对不起,我不知道它是为了那个。你能推荐另一种将值传递给第二个活动的方法吗?
-
在任何事件的第一个活动中使用共享偏好保存,然后当您进行第二个活动时从共享偏好中获取数据
标签: android listview sharedpreferences