【问题标题】:OutOfMemory Error when displaying data from SQLiteDatabase显示来自 SQLiteDatabase 的数据时出现 OutOfMemory 错误
【发布时间】:2019-06-03 02:04:12
【问题描述】:

我正在尝试使用名为 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();
    }
}

【问题讨论】:

    标签: java sqlite android-studio android-sqlite out-of-memory


    【解决方案1】:

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

    while(data.moveToNext()){
        taskList.add(data.getString(1));
    
    }
    
    listView.setAdapter(cursorAdapter);
    

    【讨论】:

    • 非常感谢您的解释!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 2016-08-28
    相关资源
    最近更新 更多