Resource not found when changing to landscape mode - android

When I change to landscape mode I want to save informations, I wrote this code, but when I start the program it shows ResourceNotFoundException, why?
public class ActivityB extends AppCompatActivity {
int value = 0;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_b);
text = (TextView) findViewById(R.id.textView);
Button b = (Button) findViewById(R.id.button);
//Toast.makeText(this," svd : "+savedInstanceState,Toast.LENGTH_LONG).show();
if (savedInstanceState != null) {
value = savedInstanceState.getInt("count");
text.setText("" + value); // here is the Error! why ?
}
}
public void Incrementation(View view) {
value++;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("count", value);
}
}
LOG
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.othma.udemy/com.example.othma.udemy.ActivityB}: android.content.res.Resources$NotFoundException: String resource ID #0x6*

First, you need to handle your logic in onCreate properly.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_b);
text = (TextView) findViewById(R.id.textView);
Button b = (Button) findViewById(R.id.button);
//Toast.makeText(this," svd : "+savedInstanceState,Toast.LENGTH_LONG).show();
if (savedInstanceState != null) {
value = savedInstanceState.getInt("count"); // here where we retrieve back the value
} else {
text.setText("" + value); //first time init savedInstanceState will be null
}
}
I think you need to reorder this also.
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("count", value); // used to store data before pausing the activity.
super.onSaveInstanceState(outState);
}
Hope that helps!

Related

Keeping inputs in activity after moving to another activity

I am using Android Studio. I have two activities, MainActivity and Main2Activity. There is an edit text and a button in each one. How do I keep the input in the edit text in any activity when I go to the second activity? I tried many answers but nothing worked.
Here is the code of the activity.
public class MainActivity extends AppCompatActivity {
EditText editText2;
Button button;
String var1 ;
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("var1", var1);
editText2 = (EditText)findViewById(R.id.editText2);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
var1 = savedInstanceState.getString("var1");
var1 = editText2.getText().toString();
editText2.setText(var1);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Click1(View view)
{
Intent i = new Intent(MainActivity.this,Main2Activity.class);
startActivity(i);
}
}
To carry over values from one activity to another, you need to add a line of code before startActivity(i);. This line of code that you need to add is:
i.putExtra("inputValue", String.valueOf(editText2.getText()));
Then in the other activity, in the onCreate() method, add this:
Intent intent = getIntent();
String inputValue = intent.getStringExtra("inputValue");
editText.setText(inputValue);
Obviously I don't know the name of your EditText in the MainActivity2 so replace the editText with its name.
Hope this helps!
You need to check for the existence of savedInstanceState in your onCreate function.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Check for a savedInstanceState
if(savedInstanceState != null){
var1 = savedInstanceState.getString("var1");
editText2.setText(var1); // Making sure that you have assigned editText2 already, of course.
}
}

Android: Save XWalkView - Crosswalk state

I am using XWalkView to show a mobile web site as an application. My problem is when application goes background and comes back it reloads the page it shows. I want to keep it state and continue from that state when it comes from background. Here is my code:
public class MainActivity extends AppCompatActivity {
static final String URL = "https://www.biletdukkani.com.tr";
static final int MY_PERMISSIONS_REQUEST_ACCESS_LOCATION = 55;
static final String SHOULD_ASK_FOR_LOCATION_PERMISSION = "shouldAskForLocationPermission";
static final String TAG = "MainActivity";
static final String COMMAND = "/system/bin/ping -c 1 185.22.184.184";
static XWalkView xWalkWebView;
TextView noInternet;
static Bundle stateBundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
stateBundle = savedInstanceState.getBundle("xwalk");
}
setContentView(R.layout.activity_main);
initNoInternetTextView();
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
stateBundle = savedInstanceState.getBundle("xwalk");
Log.d(TAG, "onRestoreInstanceState");
}
/**
* İnternet yok mesajı gösteren TextVidew'i ayarlar.
*/
private void initNoInternetTextView() {
Log.d(TAG, "initNoInternetTextView");
noInternet = (TextView) findViewById(R.id.no_internet);
if (noInternet != null) {
noInternet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkInternetConnection();
}
});
}
}
/**
* WebView'i ayarlar.
*/
private void initWebView() {
Log.d(TAG, "initWebView");
if (xWalkWebView == null) {
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
xWalkWebView = (XWalkView) findViewById(R.id.webView);
//xWalkWebView.clearCache(true);
xWalkWebView.load(URL, null);
xWalkWebView.setResourceClient(new BDResourceClient(xWalkWebView, progressBar));
}
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
checkLocationPermissions();
checkInternetConnection();
if (xWalkWebView != null && stateBundle != null) {
xWalkWebView.restoreState(stateBundle);
}
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause");
if (xWalkWebView != null) {
stateBundle = new Bundle();
xWalkWebView.saveState(stateBundle);
}
}
public void onSaveInstanceState(Bundle savedInstanceState) {
Log.d(TAG, "onSaveInstanceState");
// Save the user's current game state
savedInstanceState.putBundle("xwalk", stateBundle);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onBackPressed() {
Log.d(TAG, "onBackPressed");
if (xWalkWebView != null && xWalkWebView.getNavigationHistory().canGoBack()) {
xWalkWebView.getNavigationHistory().navigate(XWalkNavigationHistory.Direction.BACKWARD, 1);
} else {
super.onBackPressed();
}
}
}
I have also tried to add following lines to manifest but didn't work.
android:launchMode="singleTask"
android:alwaysRetainTaskState="true"
How can i do that?
Thanks in advcance.
One way would be to initialize the view inside a fragment which is set to retain it's instance.

Keep spinner position when screen orientation is changed

I want to keep the spinner position when the screen is rotated
I've looked at a few answers on here and so far have the following
Aim - Store the position of the spinner
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
flav1Spinner = (Spinner)findViewById(R.id.Combo_InvChoice1);
Integer flav1 = flav1Spinner.getSelectedItemPosition();
savedInstanceState.putInt("cho1", flav1);
}
Aim - Restore position
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculation);
Locale.setDefault(Locale.US);
if (savedInstanceState != null){
flav1Spinner = (Spinner)findViewById(R.id.Combo_InvChoice1);
Integer flav1 = savedInstanceState.getInt("cho1");
flav1Spinner.setSelection(flav1);
}
However while debugging I can see that the Integer Flav1 is getting a value assigned to it and the digit is being retrieved, however the spinner isn't changing it's position. Any suggestions?
You can do it by onSaveInstanceState(), As below
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("yourSpinner", yourSpinner.getSelectedItemPosition());
// do this for each of your Spinner
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
yourSpinner.setSelection(savedInstanceState.getInt("yourSpinner", 0));
// do this for every text views
}
}
Check Saving Activity state, it will help you to get more details.

how to set listview's position after configuration change

I'm struggling to recover my position in a listview on screen rotation configuration change.
Amongst the many things I've tried I came to this:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState == null) {
...
mVisibleItem = -1;
} else {
if (savedInstanceState.containsKey(LV_VISIBLE_ITEM)) {
mVisibleItem = savedInstanceState.getInt(LV_VISIBLE_ITEM);
}
}
setRetainInstance(true);
}
and here I'm trying to set the position in the listview
#Override
public void onResume() {
super.onResume();
if (mVisibleItem > 0) {
mlvDictionaryIndex.setSelectionFromTop(mVisibleItem, 0);
}
}
However, much to my surprise, after rotating the screen and watching mVisibleItem gets set with the correct value, in onResume I see that mVisibleItem equals -1. How come?
use onSavedInstanceState to write in the bundle the returned value of ListView.onSaveInstanceState(), and restored it onActivityCreated
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mListView != null) {
outState.putParcelable(LISTVIEW_INTERNAL_STATE_KEY, mListView.onSaveInstanceState());
}
}
after the data are reload then you can call
mListView.onRestoreInstanceState(savedInstanceState.getParcelable(LISTVIEW_INTERNAL_STATE_KEY));
Override onSaveInstanceState such as below"
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("pos", pos);
}
Then in your onCreate method have read the savedInstanceState to check if this is an orientation change or a new activity.
private int pos = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
//This is a new activity
}else{
pos = savedInstanceState.getInt("");
}
Now you have the position in the list, and you can scroll to this in configuration change.
Maybe after the data in the listview is reloaded,the code below will work.
mlvDictionaryIndex.setSelectionFromTop(mVisibleItem, 0);
So you can use post() method, just like below:
post(new Runnable() {
public void run() {
mlvDictionaryIndex.setSelectionFromTop(mVisibleItem, 0);
}
});

Android count number of times user changes orientation

I am trying to create a basic application that just counts how many times the user changes the orientation to landscape from portrait and displays the count on screen. I have:
public class MainActivity extends Activity {
int count = 0;
private static boolean inLandscape = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.count);
tv.setText(getResources().getString(R.string.count) + ' ' + count);
if (!inLandscape && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
inLandscape = true;
count++;
Log.e("Debug","In Landscape " + count);
}
else if (inLandscape && getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
inLandscape = false;
}
The problem is, in my debug statement count is always 1, and the text never changes on the screen. Doing some research, I think this is because the activity gets trashed and recreated every time the orientation changes. How do I maintain the variable value throughout orientation change?
I tried using the savedInstanceState with
if (savedInstanceState.containsKey("count"))
count = savedInstanceState.getInt("count");
savedInstanceState.putInt("count", count);
but this gives a NullPointerException at the containsKey line.
Override onSaveInstanceState to store your orientation change counter.
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("count", count)
}
and override onRestoreInstanceState to read it back after a change.
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
count = savedInstanceState.getInt("count");
}
Obviously, you can still keep your code in the same place in 'onCreate', for conditionally adding to the counter depending on the orientation each time onCreate is called.
It's giving you a NullPointerException because saveInstanceState is null. You also need to put the savedInstanceState.putInt("count", count) inside your onRestoreInstanceState method. So your code would look like...
int mCount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.count);
mCount = 0;
tv.setText(getResources().getString(R.string.count) + ' ' + mCount);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mCount++;
tv.setText(getResources().getString(R.string.count) + ' ' + count);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
mCount = savedInstanceState.getInt("count");
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("count", mCount);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
Please see http://developer.android.com/training/basics/activity-lifecycle/recreating.html and http://developer.android.com/guide/topics/resources/runtime-changes.html for more information.

Categories

Resources