Alif Meraz Hamid
Alif Meraz Hamid

Reputation: 13

OnCreate functions get removed when I use an OnResume function for a simple To Do List app with a Database

I am trying to make a simple To Do List function which adds tasks to a recycler view.

I add a new task from a different activity and try to bring it to my main activity using OnResume but when I use the OnResume function, all my tasks disappear because I believe that the OnResume is somehow overriding my OnCreate.

This is what it looks like without my OnResume: [enter image description here][1] [1]: https://i.sstatic.net/ZXCfs.jpg

When I add the OnResume it is just blank and the tasks dont get added either...

Edit: When I in my Add Task activity, it gives out an error: Attempt to invoke virtual method 'java.util.ArrayList com.example.todolist.TaskAdapter.getTaskItemList()' on a null object reference

Not sure why its coming out as null as it has code earlier, also tried doing this without clearing the task list but it comes out with the same issue.

This is my MainActivity:

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private TaskAdapter taskAdapter;
    private RecyclerView.LayoutManager layoutManager;
    private DatabaseHandler dbHandler;
    private ArrayList<TaskItem> taskList;
    private FloatingActionButton fAButton;
    private static final String EDIT = "Edit";
    public boolean complete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.recyclerView);
        fAButton = findViewById(R.id.floatingActionButton2);

        dbHandler = new DatabaseHandler(this, null, null, 1);
        populateDB();
        populateTaskList();

        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(getApplicationContext());
        taskAdapter = new TaskAdapter(taskList, this);

        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(taskAdapter);

        taskAdapter.setOnItemClickListener(new TaskAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                TaskItem editTask = taskList.get(position);
                Intent intent = new Intent(MainActivity.this, EditActivity.class);
                intent.putExtra(EDIT, editTask);
                startActivity(intent);
            }
        });

        taskAdapter.setOnItemLongClickListener(new TaskAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(int position) {
                int result = dbHandler.deleteTask(taskList.get(position));
                System.out.println(result);
                populateTaskList();
                taskAdapter.setTaskItemList(taskList);
                taskAdapter.notifyDataSetChanged();
                return true;
            }
        });

        fAButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AddActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.completed, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.complete:
                if (complete = true){
                    item.setTitle("To Do");
                    complete = false;
                    taskAdapter.setCompleted(complete);
                }else{
                    item.setTitle("Complete");
                    complete = true;
                    taskAdapter.setCompleted(complete);
                }
                return true;
        }
        return true;
    }

    private void populateDB(){
        dbHandler.addTask(new TaskItem("Finish Assignment 5", "4/6/2021",
                "Finish task 1 and task 2", "LOW", "NO"));
        dbHandler.addTask(new TaskItem("Finish Assignment 4", "1/6/2021",
                "Finish task 1 and task 2", "LOW", "NO"));
        dbHandler.addTask(new TaskItem("Submit portfolio", "10/6/2021", "Make the LSR then submit it",
                "HIGH", "NO"));
        dbHandler.addTask(new TaskItem("Finish Assignment 3", "24/5/2021",
                "Finish task 1 and task 2", "LOW", "YES"));
        dbHandler.addTask(new TaskItem("Finish Assignment 1", "4/5/2021",
                "Finish task 1 and task 2", "LOW", "YES"));
    }

    private void populateTaskList(){
        if (taskList != null)
            taskList.clear();
        taskList = dbHandler.getAllTasks();
    }

    /*@Override
    protected void onResume() {
        super.onResume();
        populateTaskList();
    }*/
}

This is my Database Handler:

package com.example.todolist;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

public class DatabaseHandler extends SQLiteOpenHelper {
    private static final String DB_NAME = "TaskDB";
    private static final String TABLE_NAME = "Task_Table";

    private static final String KEY_ID = "id";
    private static final String KEY_TITLE = "Title";
    private static final String KEY_DATE = "Date";
    private static final String KEY_DETAILS = "Details";
    private static final String KEY_PRIORITY = "Priority";
    private static final String KEY_COMPLETE = "Complete";

    public DatabaseHandler(@Nullable Context context, @Nullable String name,
                           @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String create_table = "CREATE TABLE " + TABLE_NAME + "(" + KEY_ID + " INTEGER PRIMARY KEY,"
                + KEY_TITLE + " TEXT, " + KEY_DATE + " TEXT, " + KEY_DETAILS + " TEXT, " + KEY_PRIORITY +
                " TEXT, " + KEY_COMPLETE + " TEXT)";
        db.execSQL(create_table);
        System.out.println("Table created");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        //onCreate(db);
        //System.out.println("Table dropped");
    }

    public long addTask(TaskItem task){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_TITLE, task.getTitle());
        contentValues.put(KEY_DATE, task.getDate());
        contentValues.put(KEY_DETAILS, task.getDetails());
        contentValues.put(KEY_PRIORITY, task.getPriority());
        contentValues.put(KEY_COMPLETE, task.getComplete());

        return db.insert(TABLE_NAME, null, contentValues);
    }

    public TaskItem getTask(int taskID){
        TaskItem taskItem = null;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME, new String[]{KEY_ID, KEY_TITLE, KEY_DATE, KEY_DETAILS,
                KEY_PRIORITY, KEY_COMPLETE}, KEY_ID + "=?", new String[]{String.valueOf(taskID)},
                null, null, null, null);

        if(cursor != null){
            cursor.moveToFirst();
            taskItem = new TaskItem(cursor.getInt(0), cursor.getString(1),
                    cursor.getString(2), cursor.getString(3), cursor.getString(4),
                    cursor.getString(5));
        }

        return taskItem;
    }

    public ArrayList<TaskItem> getAllTasks(){
        ArrayList<TaskItem> taskList = new ArrayList<TaskItem>();
        String selectQuery = "SELECT * FROM " + TABLE_NAME;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if(cursor.moveToFirst()){
            do{
                TaskItem taskItem = new TaskItem();
                taskItem.setId(Integer.parseInt(cursor.getString(0)));
                taskItem.setTitle(cursor.getString(1));
                taskItem.setDate(cursor.getString(2));
                taskItem.setDetails(cursor.getString(3));
                taskItem.setPriority(cursor.getString(4));
                taskItem.setComplete(cursor.getString(5));
                taskList.add(taskItem);
            }while (cursor.moveToNext());
        }
        return taskList;
    }

    public int deleteTask(TaskItem taskItem){
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete(TABLE_NAME, KEY_ID + "=?", new String[]{String.valueOf(taskItem.getId())});
    }

    public int updateTask(int taskID){
        TaskItem task = new TaskItem();
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_ID, task.getTitle());
        contentValues.put(KEY_TITLE, task.getTitle());
        contentValues.put(KEY_DATE, task.getDate());
        contentValues.put(KEY_DETAILS, task.getDetails());
        contentValues.put(KEY_PRIORITY, task.getPriority());
        contentValues.put(KEY_COMPLETE, task.getComplete());
        return db.update(TABLE_NAME, contentValues, KEY_ID + "= ?", new String[]{String.valueOf(taskID)});
    }
}

My AddActivity:

public class AddActivity extends AppCompatActivity {
    public EditText addTitle, addDate, addDetail;
    public CheckBox priorityBox;
    DatePickerDialog picker;
    DatabaseHandler dbHandler;
    TaskAdapter taskAdapter;
    private ArrayList<TaskItem> taskList = new ArrayList<TaskItem>();
    public String title, date, detail, priority;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);

        addTitle = findViewById(R.id.addTitle);
        addDate = findViewById(R.id.addDate);
        addDetail = findViewById(R.id.addDetails);
        priorityBox = findViewById(R.id.addPriority);

        final Calendar cldr = Calendar.getInstance();
        int day = cldr.get(Calendar.DAY_OF_MONTH);
        int month = cldr.get(Calendar.MONTH);
        int year = cldr.get(Calendar.YEAR);
        addDate.setText(day + "/" + (month + 1) + "/" + year);

        addDate.setInputType(InputType.TYPE_NULL);
        addDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // date picker dialog
                picker = new DatePickerDialog(AddActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                addDate.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
                            }
                        }, year, month, day);
                picker.getDatePicker().setMinDate(System.currentTimeMillis());
                picker.show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.tick, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
                title = addTitle.getText().toString();
                date = addDate.getText().toString();
                detail = addDetail.getText().toString();
                priority = "LOW";

                priorityBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked)
                            priority = "HIGH";
                        else
                            priority = "LOW";
                    }
                });

                //taskList = taskAdapter.getTaskItemList();
                dbHandler = new DatabaseHandler(this, null, null, 1);
                dbHandler.addTask(new TaskItem(title, date, detail, priority, "NO"));
                //taskList.add(new TaskItem(title, date, detail, priority, "NO"));
                taskList = taskAdapter.getTaskItemList();
                taskList.add(new TaskItem("title", "date", "detail", "priority", "NO"));
                taskAdapter.setTaskItemList(taskList);
                taskAdapter.notifyDataSetChanged();
                finish();
                //Intent intent = new Intent(AddActivity.this, MainActivity.class);
                //startActivity(intent);

        return true;
    }
}

Finally my TaskItem:

public class TaskItem implements Parcelable {
    private int id;
    private String title;
    private String date;
    private String details;
    private String priority;
    private String complete;

    public TaskItem(String title, String date, String details, String priority, String complete) {
        this.title = title;
        this.date = date;
        this.details = details;
        this.priority = priority;
        this.complete = complete;
    }

    public TaskItem() {

    }

    public TaskItem(int id, String title, String date, String details, String priority, String complete) {
        this.id = id;
        this.title = title;
        this.date = date;
        this.details = details;
        this.priority = priority;
        this.complete = complete;
    }

    public int getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String getDate() {
        return date;
    }

    public String getDetails() {
        return details;
    }

    public String getPriority() {
        return priority;
    }

    public String getComplete() {
        return complete;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public void setDetails(String details) {
        this.details = details;
    }

    public void setPriority(String priority) {
        this.priority = priority;
    }

    public void setComplete(String complete) {
        this.complete = complete;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(title);
        dest.writeString(date);
        dest.writeString(details);
        dest.writeString(priority);
        dest.writeString(complete);
    }

    public TaskItem(Parcel parcel){
        id = parcel.readInt();
        title = parcel.readString();
        date = parcel.readString();
        details = parcel.readString();
        priority = parcel.readString();
        complete = parcel.readString();
    }

    public static final Parcelable.Creator<TaskItem> CREATOR = new Parcelable.Creator<TaskItem>() {

        @Override
        public TaskItem createFromParcel(Parcel parcel) {
            return new TaskItem(parcel);
        }

        @Override
        public TaskItem[] newArray(int size) {
            return new TaskItem[0];
        }
    };
}

I think my Database Handler is fine so I'm assuming it is something wrong with my Add Activity or Main Activity.

Upvotes: 0

Views: 120

Answers (2)

Piyush Mamidwar
Piyush Mamidwar

Reputation: 85

Try this

protected void onResume() {
    super.onResume();
    populateTaskList();
    taskAdapter.notifyDataSetChanged();
}

You should not interact with Database in the main thread

Upvotes: 0

Yakir Malka
Yakir Malka

Reputation: 308

Your on resume call the function populateTaskList

    private void populateTaskList(){
    if (taskList != null)
        taskList.clear();
    taskList = dbHandler.getAllTasks();
}

so basically what you doing when you calling that function is to clear the list because its not empty and your dbHandler.getAllTasks() gives you probably empty list back so its empty.

Upvotes: 0

Related Questions