我试图创建一个应用程序,您可以使用EditText和ListView将项目添加到列表中。它必须记住你添加到列表中的内容,因为有多个活动,所以我使用SharedPreferences。活动第一次打开它崩溃了,因为它查找了一个SharedPreferences文件,但它没有,所以我添加了
if (newquestion == null) {
return;
}
但现在它从未在列表中添加任何内容。
此活动的完整代码:
package com.example.dogwise;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView;
import android.content.SharedPreferences;
public class Questions extends AppCompatActivity {
ListView listview;
String[] ListElements = new String[]{
"How much food should I feed my dog?",
"How do I teach my dog to sit?"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
listview = (ListView) findViewById(R.id.QuestionsList);
final List<String> ListElementsArrayList = new ArrayList<String>(Arrays.asList(ListElements));
final ArrayAdapter<String> adapter = new ArrayAdapter<String>
(Questions.this, android.R.layout.simple_list_item_1, ListElementsArrayList);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
String newquestion=pref.getString("key_question", null);
if (newquestion == null) {
return;
}
ListElementsArrayList.add(newquestion);
adapter.notifyDataSetChanged();
Bundle newQuestion = getIntent().getExtras();
if (newQuestion == null) {
return;
}
final String QuestionName = newQuestion.getString("QuestionName");
ListElementsArrayList.add(QuestionName);
adapter.notifyDataSetChanged();
SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
editor.putString("key_question", QuestionName);
editor.apply();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {
Intent myIntent = new Intent(view.getContext(), Question_1.class);
startActivityForResult(myIntent, 0);
}
if (position == 1) {
Intent myIntent = new Intent(view.getContext(), Question_2.class);
startActivityForResult(myIntent, 0 );
}
if (position == 2) {
Intent myIntent = new Intent(view.getContext(), Question_Asked.class);
myIntent.putExtra("QuestionTitle", QuestionName);
startActivityForResult(myIntent, 0);
}
}
});
}
;
public void backHomeOnClick(View view) {
Intent b = new Intent(this, HomeScreen.class);
startActivity(b);
}
public void askAQuestionOnClick(View view) {
Intent i = new Intent(this, AskAQuestion.class);
startActivity(i);
}
;
}
答案 0 :(得分:0)
您使用key =“QuestionTitle”将数据发布到intent中,但尝试使用key =“QuestionName”检索该数据。