Java 传递变量";日期“;通过Android Studio上的Intent连接到另一个类,空对象引用

Java 传递变量";日期“;通过Android Studio上的Intent连接到另一个类,空对象引用,java,android,android-studio,Java,Android,Android Studio,android开发在这里还是个新鲜事物。我一直在修改一个代码,并试图将用户在日历视图上选择的日期传递给另一个类,该类将保存到数据库(一个允许用户为日历上的特定日期创建事件的应用程序)。我的问题是,当我传递它时,应用程序会因空对象引用而崩溃。我似乎找不到导致空对象引用的原因以及需要更改的内容。任何帮助都将不胜感激 CalendarActivity.java package com.example.zaphk.studenthelperapplication3.calendar; import a

android开发在这里还是个新鲜事物。我一直在修改一个代码,并试图将用户在日历视图上选择的日期传递给另一个类,该类将保存到数据库(一个允许用户为日历上的特定日期创建事件的应用程序)。我的问题是,当我传递它时,应用程序会因空对象引用而崩溃。我似乎找不到导致空对象引用的原因以及需要更改的内容。任何帮助都将不胜感激

CalendarActivity.java

package com.example.zaphk.studenthelperapplication3.calendar;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.CalendarView;
import android.widget.Toast;

import com.example.zaphk.studenthelperapplication3.R;

public class CalendarActivity extends AppCompatActivity {
    public String date;
    private  static final String TAG = "CalendarActivity";
    private CalendarView mCalendarView;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calendar_layout);
        mCalendarView = (CalendarView) findViewById(R.id.calendarView);
        mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(CalendarView CalendarView, int year, int month, int dayOfMonth) {
                String date = year + "/" + month + "/"+ dayOfMonth ;
                Log.d(TAG, "onSelectedDayChange: yyyy/mm/dd:" + date);
                Intent intent = new Intent(CalendarActivity.this,CalendarEvent.class);
                intent.putExtra("date",date);
                startActivity(intent);

                Toast.makeText(CalendarActivity.this,date,Toast.LENGTH_SHORT).show();

            }
        });
    }
}
CalendarEvent.java

package com.example.zaphk.studenthelperapplication3.calendar;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

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

import com.example.zaphk.studenthelperapplication3.calendar.database.Calendar;
import com.example.zaphk.studenthelperapplication3.calendar.database.CalendarAdapter;
import com.example.zaphk.studenthelperapplication3.calendar.database.Calendar_DbHelper;
import com.example.zaphk.studenthelperapplication3.utils.MyDividerItemDecoration;
import com.example.zaphk.studenthelperapplication3.utils.RecyclerTouchListener;

import com.example.zaphk.studenthelperapplication3.R;


public class CalendarEvent extends AppCompatActivity {
    private CalendarAdapter mAdapter;
    private List<Calendar> notesList = new ArrayList<>();
    private CoordinatorLayout coordinatorLayout;
    private RecyclerView recyclerView;
    private TextView noNotesView;
    Intent intent = getIntent();
    public String date = intent.getStringExtra("date");


    private Calendar_DbHelper db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notes);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);




        coordinatorLayout = findViewById(R.id.coordinator_layout);
        recyclerView = findViewById(R.id.recycler_view);
        noNotesView = findViewById(R.id.empty_notes_view);

        db = new Calendar_DbHelper(this);

        notesList.addAll(db.getAllNotes());

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showNoteDialog(false, null, -1);
            }
        });

        mAdapter = new CalendarAdapter(this, notesList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16));
        recyclerView.setAdapter(mAdapter);

        toggleEmptyNotes();



        /**
         * On long press on RecyclerView item, open alert dialog
         * with options to choose
         * Edit and Delete
         * */
        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
                recyclerView, new RecyclerTouchListener.ClickListener() {
            @Override
            public void onClick(View view, final int position) {
            }

            @Override
            public void onLongClick(View view, int position) {
                showActionsDialog(position);
            }
        }));
    }



    /**
     * Inserting new note in db
     * and refreshing the list
     */
    private void createNote(String note) {

        // inserting note in db and getting
        // newly inserted note id
        long id = db.insertNote(note);

        // get the newly inserted note from db
        Calendar n = db.getNote(id);

        if (n != null) {
            // adding new note to array list at 0 position
            notesList.add(0, n);

            // refreshing the list
            mAdapter.notifyDataSetChanged();

            toggleEmptyNotes();
        }
    }

    /**
     * Updating note in db and updating
     * item in the list by its position
     */
    private void updateNote(String note, int position) {
        Calendar n = notesList.get(position);
        // updating note text
        n.setNote(note);

        // updating note in db
        db.updateNote(n);

        // refreshing the list
        notesList.set(position, n);
        mAdapter.notifyItemChanged(position);

        toggleEmptyNotes();
    }

    /**
     * Deleting note from SQLite and removing the
     * item from the list by its position
     */
    private void deleteNote(int position) {
        // deleting the note from db
        db.deleteNote(notesList.get(position));

        // removing the note from the list
        notesList.remove(position);
        mAdapter.notifyItemRemoved(position);

        toggleEmptyNotes();
    }

    /**
     * Opens dialog with Edit - Delete options
     * Edit - 0
     * Delete - 0
     */
    private void showActionsDialog(final int position) {
        CharSequence colors[] = new CharSequence[]{"Edit", "Delete"};

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose option");
        builder.setItems(colors, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    showNoteDialog(true, notesList.get(position), position);
                } else {
                    deleteNote(position);
                }
            }
        });
        builder.show();
    }


    /**
     * Shows alert dialog with EditText options to enter / edit
     * a note.
     * when shouldUpdate=true, it automatically displays old note and changes the
     * button text to UPDATE
     */
    private void showNoteDialog(final boolean shouldUpdate, final Calendar note, final int position) {
        LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
        View view = layoutInflaterAndroid.inflate(R.layout.note_dialog, null);

        AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(CalendarEvent.this);
        alertDialogBuilderUserInput.setView(view);

        final EditText inputNote = view.findViewById(R.id.note);
        TextView dialogTitle = view.findViewById(R.id.dialog_title);
        dialogTitle.setText(!shouldUpdate ? getString(R.string.lbl_new_note_title) : getString(R.string.lbl_edit_note_title));

        if (shouldUpdate && note != null) {
            inputNote.setText(note.getNote());
        }
        alertDialogBuilderUserInput
                .setCancelable(false)
                .setPositiveButton(shouldUpdate ? "update" : "save", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogBox, int id) {

                    }
                })
                .setNegativeButton("cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialogBox, int id) {
                                dialogBox.cancel();
                            }
                        });

        final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
        alertDialog.show();

        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Show toast message when no text is entered
                if (TextUtils.isEmpty(inputNote.getText().toString())) {
                    Toast.makeText(CalendarEvent.this, "Enter note!", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    alertDialog.dismiss();
                }

                // check if user updating note
                if (shouldUpdate && note != null) {
                    // update note by it's id
                    updateNote(inputNote.getText().toString(), position);
                } else {
                    // create new note
                    createNote(inputNote.getText().toString());
                }
            }
        });
    }

    /**
     * Toggling list and empty notes view
     */
    private void toggleEmptyNotes() {
        // you can check notesList.size() > 0

        if (db.getNotesCount() > 0) {
            noNotesView.setVisibility(View.GONE);
        } else {
            noNotesView.setVisibility(View.VISIBLE);
        }
    }

    public String getDate(){
        return date;
    }
}

package com.example.zaphk.studentHelperApplication 3.calendar;
导入android.content.DialogInterface;
导入android.content.Intent;
导入android.os.Bundle;
导入android.support.design.widget.CoordinatorLayout;
导入android.support.design.widget.FloatingActionButton;
导入android.support.v7.app.AlertDialog;
导入android.support.v7.app.AppActivity;
导入android.support.v7.widget.DefaultItemAnimator;
导入android.support.v7.widget.LinearLayoutManager;
导入android.support.v7.widget.RecyclerView;
导入android.support.v7.widget.Toolbar;
导入android.text.TextUtils;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.widget.EditText;
导入android.widget.TextView;
导入android.widget.Toast;
导入java.util.ArrayList;
导入java.util.List;
导入com.example.zaphk.studenthelperapplication3.calendar.database.calendar;
导入com.example.zaphk.studenthelperapplication3.calendar.database.CalendarAdapter;
导入com.example.zaphk.studenthelperapplication3.calendar.database.calendar\u DbHelper;
导入com.example.zaphk.studenthelperapplication3.utils.MyDividerItemDecoration;
导入com.example.zaphk.studenthelperapplication3.utils.RecyclerTouchListener;
导入com.example.zaphk.studenthelperapplication3.R;
公共类CalendarEvent扩展了AppCompatActivity{
私人日历适配器mAdapter;
private List notesList=new ArrayList();
私人协调人布局协调人布局;
私人回收站;
私有文本视图非OTESVIEW;
Intent=getIntent();
公共字符串日期=intent.getStringExtra(“日期”);
私人日历(dbdb),;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_注释);
Toolbar Toolbar=(Toolbar)findViewById(R.id.Toolbar);
设置支持操作栏(工具栏);
coordinatorLayout=findViewById(R.id.coordinator\U布局);
recyclerView=findViewById(R.id.recycler\u视图);
noNotesView=findViewById(R.id.empty\u notes\u view);
db=新日历\u DbHelper(此);
addAll(db.getAllNotes());
FloatingActionButton fab=(FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
showNoteDialog(false,null,-1);
}
});
mAdapter=新日历适配器(此为notesList);
RecyclerView.LayoutManager mLayoutManager=新的LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
setItemAnimator(新的DefaultItemAnimator());
recyclerView.addItemDecoration(新的MyDividerItemDecoration(这是LinearLayoutManager.VERTICAL,16));
recyclerView.setAdapter(mAdapter);
toggleEmptyNotes();
/**
*长按RecyclerView项时,打开警报对话框
*有选项可供选择
*编辑和删除
* */
recyclerView.addOnItemTouchListener(新的RecyclerTouchListener(此,
recyclerView,新建RecyclerTouchListener.ClickListener(){
@凌驾
公共void onClick(视图,最终int位置){
}
@凌驾
仅长按公共无效(视图,int位置){
显示操作对话框(位置);
}
}));
}
/**
*在db中插入新注释
*并刷新列表
*/
私有void createNote(字符串注释){
//在数据库中插入注释并获取
//新插入的注释id
长id=db.insertNote(注释);
//从db获取新插入的注释
日历n=db.getNote(id);
如果(n!=null){
//将新注释添加到0位置的数组列表
注释列表添加(0,n);
//刷新列表
mAdapter.notifyDataSetChanged();
toggleEmptyNotes();
}
}
/**
*更新数据库中的注释并更新
*按其位置列出列表中的项
*/
私有void updateNote(字符串注释,int位置){
日历n=notesList.get(位置);
//更新注释文本
n、 setNote(注);
//更新数据库中的注释
db.updateNote(n);
//刷新列表
注释列表集合(位置,n);
mAdapter.notifyItemChanged(位置);
toggleEmptyNotes();
}
/**
*从SQLite中删除注释并删除
*按其位置从列表中删除项
*/
私有无效删除注释(内部位置){
//从db中删除注释
db.deleteNote(notesList.get(position));
//从列表中删除注释
注释列表。移除(位置);
mAdapter.notifyItemRemoved(位置);
toggleEmptyNotes();
}
/**
*打开带有编辑-删除选项的对话框
*编辑-0
*删除-0
*/
私有无效显示操作对话框(最终整数位置){
字符序列颜色[]=新字符序列[]{“编辑”、“删除”};
AlertDialog.Builder=新建AlertDialog.Builder(此);
builder.setTitle(“选择选项”);
setItems(颜色,新的DialogInterface.OnClickListener(){
@凌驾
2019-10-06 21:49:33.346 26474-26474/com.example.zaphk.studenthelperapplication3 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.zaphk.studenthelperapplication3, PID: 26474
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.zaphk.studenthelperapplication3/com.example.zaphk.studenthelperapplication3.calendar.CalendarEvent}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2762)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2943)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1630)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6626)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
        at com.example.zaphk.studenthelperapplication3.calendar.CalendarEvent.<init>(CalendarEvent.java:41)
        at java.lang.Class.newInstance(Native Method)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1196)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2752)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2943) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1630) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6626) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811) 
public String date = getIntent().getStringExtra("date");
public String date ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notes);
        date =  getIntent().getStringExtra("date")
    }