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

Posted

技术标签:

【中文标题】当我将 OnResume 函数用于带有数据库的简单待办事项列表应用程序时,OnCreate 函数被删除【英文标题】:OnCreate functions get removed when I use an OnResume function for a simple To Do List app with a Database 【发布时间】:2021-08-24 07:27:15 【问题描述】:

我正在尝试制作一个简单的待办事项列表功能,它将任务添加到回收站视图中。

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

这就是没有我的 OnResume 时的样子: [在此处输入图片描述][1] [1]:https://i.stack.imgur.com/ZXCfs.jpg

当我添加 OnResume 时,它​​只是空白,任务也没有被添加...

编辑:当我在我的添加任务活动中,它给出了一个错误: 尝试在空对象引用上调用虚拟方法“java.util.ArrayList com.example.todolist.TaskAdapter.getTaskItemList()”

不知道为什么它像之前的代码一样显示为 null,也尝试在不清除任务列表的情况下执行此操作,但出现了同样的问题。

这是我的 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();
    */

这是我的数据库处理程序:

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


我的添加活动:

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;
    

最后是我的任务项:

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];
        
    ;


我认为我的数据库处理程序很好,所以我假设我的添加活动或主活动有问题。

【问题讨论】:

【参考方案1】:

你的简历调用函数 populateTaskList

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

所以基本上你在调用该函数时所做的就是清除列表,因为它不是空的,而你的 dbHandler.getAllTask​​s() 可能会给你空列表,所以它是空的。

【讨论】:

好吧,如果我没有 OnResume,它适用于第一个实例,它也适用于我的删除功能,所以不确定问题出在哪里:/ 你的 onResume 调用了一个删除你数据的函数,这就是原因。【参考方案2】:

试试这个

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

你不应该在主线程中与数据库交互

【讨论】:

试过了,可惜没用

以上是关于当我将 OnResume 函数用于带有数据库的简单待办事项列表应用程序时,OnCreate 函数被删除的主要内容,如果未能解决你的问题,请参考以下文章

如何刷新片段'onResume?

没有调用 onresume 的弹回堆栈

函数适用于双引号,但不适用于单引号

Android:onResume() 正在跳转到除异常之外的另一个活动

带有 popupTo 和 popUpToInclusive onResume 的 Android 导航组件不起作用

将带有参数的 printf 用于可变参数函数?