Activity 无意中启动时的 NULL 指针。 'int java.lang.String.hashCode()' 空对象引用

NULL Pointer when Activity starts without intent. 'int java.lang.String.hashCode()' on a null object reference

关于我正在尝试做的事情的简要说明:

  1. 这是一个简单的消息传递应用程序

  2. 在我的第一个 activity 中,我有一个列表视图和几个按钮。

    • 用户按下任何按钮,有关按下哪个按钮的信息存储在共享首选项中。
    • 当用户按下任何列表项时,将触发一个意图,将他带到新的 activity putExtra() 从意图分析按下的列表项。
  3. 在第二个 activity 中,根据意图附带的值,确定 newString 的字符串值。

问题 当屏幕旋转时,应用程序崩溃并出现此错误 -

Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference

以下是第二个代码 activity -

String newString = "Default_Channel";

public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences;

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

    .
    .
    .

    sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

    String restoredText = sharedpreferences.getString("CurrentUser", null);
    if (restoredText != null) {
        currentUserName = sharedpreferences.getString("CurrentUser", "unknown");//"unknown" is the default value.
        .
        .
        .
    }
    else
    {
        currentUser.setText("not signed in");
    }


    if (savedInstanceState == null)
    {
        Bundle extras = getIntent().getExtras();
        if(extras == null)
        {
            newString= "Default_Channel";
        }
        else
        {
            newString= extras.getString("LIST_ITEM_CLICKED");
        }
    }
    else
    {
        newString= (String) savedInstanceState.getSerializable("LIST_ITEM_CLICKED");
    }
     // *** GETTING ERROR HERE On this line *** // 

    switch (newString)
    {
        case "User_1":
            .
            .
            .
            break;
        case "User_2":
            .
            .
            .
            break;
        case "User_3":
            .
            .
            .
            break;
        case "Default_Channel":
            .
            .
            .
            break;
    }

我在代码中提到的地方出现 NULL 指针异常!它位于 Else 语句和 Switch 之间。

另外,我明白什么是空指针异常,这不是我要问的。当屏幕旋转时,我得到 NULL 指针,即当 activity 无意中重新启动时。

我是 android 编程的新手,无法弄清楚这里出了什么问题。

编辑:这不是与 "What is NULL pointer exception" 重复的问题。

基本上你会得到 NullPointerException.The code you posted is not clear where actually you are getting this. You need to check whether object on which you are performing operation is null or not and proceed based on that. See What is a NullPointerException, and how do I fix it?

我看到你用这个:

newString= (String) savedInstanceState.getSerializable("LIST_ITEM_CLICKED");

那么你会覆盖 onSaveInstanceState 吗?
如果不是,请覆盖它并保存 "LIST_ITEM_CLICKED".

的当前值

我认为你的问题是因为在旋转时,activity 是用 savedInstanceState 重新创建的,但是你没有保存你的值,所以发生了 NPE。