Brief description about what I am trying to do:
It's a simple messaging app
In my first activity I have a list-view and few buttons.
- User presses any of the button and the information about which button was pressed was stored in shared preferences.
- When user presses any list item, an intent is triggered that takes him to new activity where which list item was pressed is analyzed by putExtra() from intent.
In second activity, depending on which value came with intent, a string value for newString is decided.
Problem When screen rotates, app crashes with this error -
Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
Following is the code in second 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;
}
I am getting NULL pointer exception where I have mentioned it in code ! Its Line between Else statement and Switch.
Also, I understand what is NULL pointer exception and this is not what I am asking. I am getting NULL pointer when screen rotates, i.e. when activity restarts without intent.
I am new to android programming and not able to figure out what's going wrong here.
Edit: This is not duplicate question with "What is NULL pointer exception".