import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences
sharedPreferences=this.getSharedPreferences("com.example.sharedpre",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", "VJ").apply();
String user=savedInstanceState.getString("username","");
Log.i("username",user);
}
}
Asked
Active
Viewed 954 times
0

Phantômaxx
- 37,901
- 21
- 84
- 115

Vardhman Jain
- 49
- 4
-
3You have to check if `savedInstanceState` is not null before trying to call get string, as it is null when this error occurs – Tyler Jan 21 '20 at 17:35
-
help me i am getting this exception in many app – Vardhman Jain Jan 21 '20 at 17:35
2 Answers
0
You need to wrap your line which causes the error like this:
String user;
if (savedInstanceState != null) {
user = savedInstanceState.getString("username", "");
} else {
user = "";
}

Valentina Konyukhova
- 4,464
- 2
- 24
- 33
0
before saving in shared preference check your editText
is not or not then check your savedInstanceState
if (savedInstanceState != null)

Farhan Fahim
- 137
- 2
- 7