繁体   English   中英

显示来自SQLiteDatabase的数据时出现OutOfMemory错误

[英]OutOfMemory Error when displaying data from SQLiteDatabase

我正在尝试使用称为displayData()的方法显示存储在SQLite数据库中的数据。 按钮上有一个onClickListener,只要在该onClickListener内部调用该方法,它就会完美执行。 尽管我希望每当应用启动时就显示数据。 当我直接在onCreate或onStart方法中调用同一方法时,我在重新启动应用程序时遇到OutOfMemory错误。 每当应用启动时,如何在没有此错误的情况下如何调用该方法?

主要活动

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();
    }
}

您需要在while循环的每个迭代中设置适配器,您需要在每次迭代中将数据添加到列表中,并在完成时将其设置为while循环之外的适配器。 检查以下代码

while(data.moveToNext()){
    taskList.add(data.getString(1));

}

listView.setAdapter(cursorAdapter);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM