我正在尝试在升级时永久保存列表项。我有两个活动 - MainActivity.java
和Main2Activity.java
(EditText活动)和一个DatabaseOperations
类。当我编辑示例注释时,它会在MainActivity.java
中更新。但是,在关闭应用程序并再次打开它时,笔记将恢复到以前的状态,并且不会保存。
MainActivity:
public class MainActivity extends AppCompatActivity {
ListView notesListView;
static ArrayList<String> notesArrayList;
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notesListView = (ListView) findViewById(R.id.notesListView);
notesArrayList = new ArrayList<String>();
notesArrayList.add("Akhilesh Chobey");
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, notesArrayList);
notesListView.setAdapter(adapter);
notesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
intent.putExtra("notePosition", i);
startActivity(intent);
}
});
}
}
Main2Activity:
public class Main2Activity extends AppCompatActivity implements TextWatcher {
DatabaseOperations myDB;
EditText editNote;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
editNote = (EditText) findViewById(R.id.noteEditText);
myDb = new DatabaseOperations(Main2Activity.this);
Intent intent = getIntent();
int position = intent.getIntExtra("notePosition", -1);
if(position != -1){
editNote.setText(MainActivity.notesArrayList.get(position));
}
editNote.addTextChangedListener(this);
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (myDb != null){
boolean isInserted = myDB.insertData(editNote.getText().toString());
if(isInserted){
Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
MainActivity.notesArrayList.set(position, String.valueOf(charSequence));
MainActivity.adapter.notifyDataSetChanged();
}
}
答案 0 :(得分:0)
那么你有一个拼写错误,你在数据库中唯一的保存是if (myDB == null)
将其更改为if (myDB != null)
。否则,将其保存到DB的代码将不会被执行。
答案 1 :(得分:0)
在MainActivity中,您始终使用值&#34; Akhilesh Chobey &#34;创建一个新的ArrayList。每次都会将此值传递给您的Main2Activity&amp;设置为EditText。
解决方案 - 在MainActivity中,在添加&#34; Akhilesh Chobey&#34;之前,检查数据库中是否存在任何现有数据。如果存在数据,请将其添加到arraylist中或如果不存在则添加&#34; Akhilesh Chobey&#34;。