简体   繁体   English

当我将 OnResume function 用于带有数据库的简单待办事项列表应用程序时,OnCreate 函数被删除

[英]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.我正在尝试制作一个简单的待办事项列表 function ,它将任务添加到回收站视图中。

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.我从不同的活动中添加了一个新任务,并尝试使用 OnResume 将其带到我的主要活动中,但是当我使用 OnResume function 时,我的所有任务都消失了,因为我相信 OnResume 以某种方式覆盖了我的 OnCreate。

This is what it looks like without my OnResume: [enter image description here][1] [1]: https://i.stack.imgur.com/ZXCfs.jpg这是没有我的 OnResume 时的样子:[在此处输入图像描述][1] [1]:https://i.stack.imgur.com/ZXCfs.jpg

When I add the OnResume it is just blank and the tasks dont get added either...当我添加 OnResume 时,它只是空白,并且任务也没有被添加......

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 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.不知道为什么它作为 null 出现,因为它之前有代码,也尝试在不清除任务列表的情况下这样做,但它出现了同样的问题。

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.我认为我的数据库处理程序很好,所以我假设我的添加活动或主活动有问题。

Your on resume call the function populateTaskList您的简历调用 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.所以基本上你在调用 function 时所做的就是清除列表,因为它不是空的,而你的 dbHandler.getAllTasks() 可能会给你空列表,所以它是空的。

Try this尝试这个

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

You should not interact with Database in the main thread您不应该在主线程中与数据库交互

暂无
暂无

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

相关问题 我应该在onResume()还是onCreate()中获得类的实例 - Should I get instances of classes in onResume() or onCreate() 我在Android应用程序中以什么方式编程更改textcolor onresume()或oncreate() - Where do I programatically change textcolor onresume() or oncreate() in my Android app 如何在onCreate()和onResume()方法中调用相同的函数? - How can I call the same functions in onCreate() and onResume() methods? 检测外部Android应用何时运行onCreate,onStart,onResume方法 - Detect when an external android app runs onCreate, onStart, onResume methods 当应用程序将用户引导至活动时调用 onCreate 和 onResume - onCreate and onResume were called when app direct user to an activity 如果使用onResume()方法,我的应用程序会崩溃或循环 - I get crash or loop in my app if I use onResume() method 我试图弄清楚为什么我的应用程序从onCreate过渡到onResume时为什么会出现NullPointerException - I'm trying to figue out why I'm getting a NullPointerException when my app transitions from onCreate to onResume 为什么在oncreate中使用if条件时我的应用程序崩溃? - Why my app crashes when I use if condition in my oncreate? 为什么代码在 onCreate() 而不是 onResume() 中工作 - Why do codes work in the onCreate() instead of onResume() 我是否需要在我编写的每个活动中实现 onCreate()、onResume 等方法? - Do I need to implement the onCreate(), onResume, etc methods in every activity I write?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM