我试图使用一种称为displayData()的方法显示存储在SQLite数据库中的数据。按钮上有一个onClickListener,只要在该onClickListener内部调用该方法,它就会完美执行。尽管我希望每当应用启动时就显示数据。当我直接在onCreate或onStart方法中调用同一方法时,我在重新启动应用程序时遇到OutOfMemory错误。每当应用启动时,如何在没有此错误的情况下如何调用该方法?
MainActivity
DatabaseHelper dbHelper;
ListView listView;
EditText taskInput;
Button addButton;
ArrayList<String> taskList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
taskList = new ArrayList<String>();
listView = (ListView) findViewById(R.id.listView);
taskInput = (EditText) findViewById(R.id.taskInput);
addButton = (Button) findViewById(R.id.addButton);
dbHelper = new DatabaseHelper(this);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//put data to Database
String getInput = taskInput.getText().toString();
if (taskInput.length() != 0) {
putData(getInput);
taskInput.setText("");
displayData();
} else {
Toast.makeText(MainActivity.this, "You must put something!", Toast.LENGTH_SHORT).show();
}
}
});
}
public void displayData(){
Cursor data = dbHelper.fetchData();
ToDoAdapter cursorAdapter = new ToDoAdapter(this, data);
if(data.getCount() != 0){
taskList.clear();
while(data.moveToNext()){
taskList.add(data.getString(1));
listView.setAdapter(cursorAdapter);
}
}
else{
Toast.makeText(this, "Error!", Toast.LENGTH_SHORT).show();
}
}
public void putData(String newEntry){
boolean insertData = dbHelper.addData(newEntry);
if(insertData == true){
Toast.makeText(this, "Successfully Added Task", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this, "No Data Added", Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:0)
您要在while循环的每个迭代中设置适配器,您需要在每次迭代中将数据添加到列表中,并在完成后将其设置为while循环之外的适配器。检查以下代码
cat *out
+ HELLO='hello there'
+ echo hello there
hello there