【问题标题】:Android Studio - Passing variable with intent add extra, ends up with nullAndroid Studio - 传递带有意图的变量添加额外,以null结束
【发布时间】:2023-03-30 10:08:01
【问题描述】:

在修复了上一个问题的空指针异常之后,(不确定是否可以为相同的代码发布不同的问题,如果不是,请告诉我)我遇到了一个新问题。当我尝试将日期变量从第一个活动传递给另一个活动时,它始终为空。我也试过设置一个公共吸气剂或变量,它也是空的。但是,使用 toast 在类中检查表明该变量确实包含日期。我正在尝试传递要由应用程序包中的其他类添加到数据库中的日期类。任何帮助将不胜感激。

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 static final String EXTRA_TEXT = "com.example.zaphk.studenthelperapplication3";
    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(Intent.EXTRA_TEXT,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;


    private Calendar_DbHelper db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        intent = getIntent();
        date = intent.getStringExtra(CalendarActivity.EXTRA_TEXT);

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

【问题讨论】:

    标签: java android android-studio android-intent


    【解决方案1】:

    您在活动之间传递数据时使用了错误的键。

    替换下一行,

    intent.putExtra(Intent.EXTRA_TEXT,date);
    

    有了这个,

    intent.putExtra(CalendarActivity.EXTRA_TEXT,date);
    

    【讨论】:

    • 即使按照您的指示更改了我的 CalendarActivity 类中的 putExtra,该变量在下一个类中仍然显示为空。编辑:将整个源代码添加到 github 以供参考是否有帮助?
    【解决方案2】:

    您使用 Intent.EXTRA_TEXT 的键。

    intent.putExtra(Intent.EXTRA_TEXT,date)
    

    但是你使用另一个键来接收。这不是同一个键。

    intent.getStringExtra(CalendarActivity.EXTRA_TEXT);
    

    【讨论】:

      【解决方案3】:

      据我所知(不太确定)

      Intent.EXTRA_TEXT
      

      用于隐式意图。

      对于显式(即活动到活动)

      如下操作

      Intent intent = new Intent(CalendarActivity.this,CalendarEvent.class);
      intent.putExtra("DATE",date);
      startActivity(intent);
      

      接收

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

      其中“DATE”是字符串键。

      【讨论】:

      • 您好,感谢您的宝贵时间。尝试更改您所做的更改后,传递的值仍会导致空变量。
      • @TanZhiJian 只是一个建议。在 CalendarEvent.class 中的 setContentView 下面写下意图代码。检查我编辑的答案。
      • 把它移了下来,遗憾的是它仍然是空的。
      【解决方案4】:

      我会说CalendarActivity.EXTRA_TEXT 可能是空的,因为您还没有将该类导入CalendarEvent.java

      import com.example.zaphk.studenthelperapplication3.calendar.CalendarActivity; in CalendarEvent.java

      正如其他人所说,Intent 上的 put 和 get 需要是相同的 String 值。

      【讨论】:

      • 我会创建一个本地字符串变量来检查您从CalendarActivity.EXTRA_TEXT 获得的字符串是正确的文本,使用调试器检查本地字符串内容是否与您在@987654326 中使用的文本匹配@
      • 我会尝试一下。感谢您抽出宝贵时间提供帮助
      猜你喜欢
      • 2012-02-15
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      • 2016-12-11
      • 2017-12-18
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多