I have seen a few examples on how to achieve this but still I can't get it working.
I followed this example, but the TextView
is empty in OnCreate
and when I rotate the screen. Here is how I implemented it:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_image_viewer);
displayFileName = (TextView) findViewById(R.id.displayFileName);
//Getting the fileName
Bundle extras = getIntent().getExtras();
uri = extras.getString("uriAsString");
Uri myUri = Uri.parse(uri);
filename = uri.substring(uri.lastIndexOf("/") + 1);
nameWitoutExtention = filename.substring(0, filename.lastIndexOf('.'));
//Checking if Text was stored
if (savedInstanceState != null) {
CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
displayFileName.setText(savedText);
}
}
@Override
protected void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putCharSequence(KEY_TEXT_VALUE, displayFileName.getText());
}
What I'm trying to achieve is to set nameWitoutExtention
to displayFileName
and when the device is rotated to let the text remain.
I got a null pointer on the text and that is why I'm trying this, any help on what I'm doing wrong?
EDIT:
This is how my implementation looks like at the moment:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_image_viewer);
displayFileName = (TextView) findViewById(R.id.displayFileName);
if(savedInstanceState != null){
CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
//When displaying this toast the correct filename gets displayed
//Toast.makeText(getApplicationContext(), savedText, Toast.LENGTH_LONG).show();
displayFileName.setText(savedText+"");
}
else{
//Getting the fileName
Bundle extrsas = getIntent().getExtras();
uri = extrsas.getString("selectedStudentVid");
Uri mUri = Uri.parse(uri);
filename = uri.substring(uri.lastIndexOf("/") + 1);
nameWitoutExtention = filename.substring(0, filename.lastIndexOf('.'));
displayFileName.setText(nameWitoutExtention);
}
@Override
protected void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putCharSequence(KEY_TEXT_VALUE, displayFileName.getText());
}
I have also tried onRestoreInstanceState()
as suggested by @PorasBhardwaj
The exception I'm getting is:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference