Search code examples
javasqliteandroid-studioandroid-sqliteout-of-memory

OutOfMemory Error when displaying data from SQLiteDatabase


I am trying to display the data stored in an SQLite Database using a method called displayData(). There is an onClickListener on a button and whenever the method is called inside that onClickListener it executes perfectly. Although I want the data to be shown whenever the app starts. When I call the same method directly in the onCreate or onStart method, I am getting an OutOfMemory error on the app restart. How can I call the method whenever the app starts without this error?

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

Solution

  • You are setting adapter each iteration of while loop, You need to add data to your list each iteration and when it completes then set it to adapter outside while loop. Check the below code

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