将模型从活动传递到另一个时出错

时间:2018-05-31 01:42:09

标签: java android android-intent android-activity

所以我在Firestore上使用Mitch的tutorial跟踪Coding,我正在改变它以满足我的个人需求。我正在构建一个待办事项应用程序(这是我的第一个应用程序/项目)现在,我正在尝试进行第二项活动,以便查看,更新和删除所选任务(此活动是ViewTaskActivity)。我试图将当前任务从MainActivity传递给ViewTaskActivity时遇到困难。当我尝试在任务变量上调用方法时,它会给我一个错误。 这是代码:

任务模型:

package dev.raphdl.firebasepractice.models;

imports ...

@IgnoreExtraProperties
public class Task implements Parcelable {

    private String title;
    private String content;
    private @ServerTimestamp Date timestamp;
    private String note_id;

    public Task(String title, String content, Date timestamp, String note_id) {
        this.title = title;
        this.content = content;
        this.timestamp = timestamp;
        this.note_id = note_id;
    }

    public Task(){

    }

    private Task(Parcel in) {
        title = in.readString();
        content = in.readString();
        note_id = in.readString();
    }

    public static final Creator<Task> CREATOR = new Creator<Task>() {
        @Override
        public Task createFromParcel(Parcel in) {
            return new Task(in);
        }

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


    public String getTitle() {
        return title;
    }

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

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }

    public String getNote_id() {
        return note_id;
    }

    public void setNote_id(String note_id) {
        this.note_id = note_id;
    }

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

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(title);
        parcel.writeString(content);
        parcel.writeString(note_id);
    }
}

MainActivity

package dev.raphdl.firebasepractice;

imports ...

public class MainActivity extends AppCompatActivity implements
        View.OnClickListener,
        IMainActivity {




    @Override
    public void updateTask(final Task mTask) {

        DocumentReference docRef = db
                .collection("users")
                .document(mAuth.getCurrentUser().getUid())
                .collection("tasks")
                .document(mTask.getNote_id());

        docRef.update("title", mTask.getTitle(),"content", mTask.getContent()).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull com.google.android.gms.tasks.Task<Void> task) {
                if(task.isSuccessful()){
                    makeSnackBarMessage("Updated Task");
                    mAdapter.updateTask(mTask);
                } else {
                    makeSnackBarMessage("Update Failed, Check logs");
                }
            }
        });


    }


    @Override
    public void deleteTask(final Task mTask){

        DocumentReference docRef = db
                .collection("users")
                .document(mAuth.getCurrentUser().getUid())
                .collection("tasks")
                .document(mTask.getNote_id());

        docRef.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull com.google.android.gms.tasks.Task<Void> task) {
                if (task.isSuccessful()){
                    makeSnackBarMessage("Task Deleted");
                    mAdapter.deleteTask(mTask);
                } else {
                    makeSnackBarMessage("Failed to Delete, Check Logs");
                }
            }
        });
    }



    @Override
    public void onTaskSelected(Task mTask) {
        viewTaskActivity(mTask);
    }

    private void viewTaskActivity(Task task) {
        Intent intent = new Intent(this, ViewTaskActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("Task", task);
        intent.putExtras(bundle);
        startActivity(intent);
    }

}

MainActivityInterface

package dev.raphdl.firebasepractice;


import dev.raphdl.firebasepractice.models.Task;

public interface IMainActivity {

    void createNewTask(String title, String content);

    void onTaskSelected(Task mTask);

    void updateTask (Task mTask);

    void deleteTask(Task mTask);

}

ViewTaskActivity

package dev.raphdl.firebasepractice;

imports ...

public class ViewTaskActivity extends AppCompatActivity implements View.OnClickListener {

    private IMainActivity mIMainActivity;

    private Task mTask;

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

        Bundle bundle = getIntent().getExtras();
        mTask = bundle.getParcelable("Task");

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.save_text_view: {

                String title = titleEditText.getText().toString();
                String content = contentEditText.getText().toString();
                if (mTask != null) {
                    Toast.makeText(this, "mTask Not NULL", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "onClick: mTask Not NULL");

                    mTask.setTitle(title);
                    mTask.setContent(content);
//THIS IS THE LINE THAT TRIGGERS THE ERROR
                    mIMainActivity.updateTask(mTask);

                    mainActivity();
                }else {
                    Log.d(TAG, "onClick: mTask NULL");
                    Toast.makeText(this, "mTask NULL", Toast.LENGTH_SHORT).show();
                }
                break;
            }
            case R.id.delete_text_view: {

                mIMainActivity.deleteTask(mTask);
                mainActivity();
                break;
            }

        }

    }

    private void mainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        Toast.makeText(this, "MainActivity", Toast.LENGTH_SHORT).show();
        startActivity(intent);
    }
}

最后,错误:

6072-6072/dev.raphdl.firebasepractice E/AndroidRuntime: FATAL EXCEPTION: main
Process: dev.raphdl.firebasepractice, PID: 6072
java.lang.NullPointerException: Attempt to invoke interface method 'void dev.raphdl.firebasepractice.IMainActivity.updateTask(dev.raphdl.firebasepractice.models.Task)' on a null object reference
    at dev.raphdl.firebasepractice.ViewTaskActivity.onClick(ViewTaskActivity.java:68)
    at android.view.View.performClick(View.java:6256)
    at android.view.View$PerformClick.run(View.java:24697)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6541)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

对于大块代码感到抱歉。

仅供参考:应用程序在尝试删除任务时给出了同样的错误

我还是个初学者,所以这可能是我忘了什么。

感谢您阅读本文

1 个答案:

答案 0 :(得分:0)

首先要了解JAVA的基本概念。您必须创建实现该接口的类的对象。在您的情况下,MainActivity正在实现接口IMainActivity。因此,您需要使用MainActivity对象初始化mIMainActivity,例如:

console.log('hello from b.js')