How to populate the EditText data while on resuming the state? - java

Here is the following scenario:
Filling the EditText and other Fields in Activity A
Moving from Activity A to Activity B on Buttonclick
Now Moving from Activity B to Activity A on Button Click
populated EditText is gone now. They are all empty
These fields should be pre-populated (as user has already filled them)
Is there any way to save the current state of Activity A. So that I can populated the EditText back? If not then How can I achieve the above task?

Use SharedPreferences.Editor to save the EditText data onPause, and retrieve the data with SharedPreferences onResume. That's the easiest way.

How are you moving from b back to a? If youre using an intent then your starting a new instance of that 'a' activity. Like some one mentioned above you should be using finish in your b activity which would take you back to a. If you need to populate a with data from b then you should use startActivityForResult - http://developer.android.com/training/basics/intents/result.html

To save the activity state, override OnSaveInstanceState() method.
#Override
protected void onSaveInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("key", somevalue); //save your data in key-value pair
}
and restore the value using,
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
somevalue = savedInstanceState.getString("key");
}
Use this method if you are destroying the activity and creating it again.

Related

onSavedInstanceState doesn't save my Instance

Hope you're all doing fine in these tough times.
I have 2 activities, A and B.
A has a button that enables an intent to go from A to B. B itself has a Dialog window whom's cancel button enables an Intent to go from B to A.
I'd like to save some data from A (2 EditTexts' content) so when I come back to A I don't have to retype those EditTexts.
So after looking up the documentation and a bit of StackOverflow, I decided to go with the onSavedInstance method but I'm wondering whether the intent transition destroys the Activity and hence the savedInstance as well...
Here's my simplified code - Activity A :
public class A extends AppCompatActivity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_match);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
if (savedInstanceState != null) {
EditText firstPlayer = findViewById(R.id.firstPlayerName);
EditText secondPlayer = findViewById(R.id.secondPlayerName);
String firstPlayerName = savedInstanceState.getString("firstPlayerName");
String secondPlayerName = savedInstanceState.getString("secondPlayerName");
firstPlayer.setText(firstPlayerName);
secondPlayer.setText(secondPlayerName);
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
EditText firstPlayer = findViewById(R.id.firstPlayerName);
EditText secondPlayer = findViewById(R.id.secondPlayerName);
String firstPlayerName = String.valueOf(firstPlayer.getText());
String secondPlayerName = String.valueOf(secondPlayer.getText());
savedInstanceState.putString("firstPlayerName", firstPlayerName);
savedInstanceState.putString("secondPlayerName", secondPlayerName);
}
}
When I debugged it, I did notice it passed thru onSavedInstance and it did save the values, but once in onCreate, the savedInstanceState is null.
Any advice?
Thanks in advance & take care people.
Fares.
You note that the "cancel button enables an Intent to go from B to A.". This sounds like you're creating a new instance of Activity A (so your activity stack goes A, B, A), and the instance state is specific to the individual instance.
Instead, you should return to A by simply calling finish() on B. This will return to the original instance of A, which will have your data.

android - listview losing the rows of data when hitting back button

Please give me a hand with an issue I am having with a ListView and its related data in my android development project.
I have an activity called OrderForm that gets started by an Intent from the activity UserProfile as such:
In UserProfile
Intent intent = new Intent(this, OrderForm.class);
startActivity(intent);
Then in OrderForm there is an EditText and an add button to add String items to an ArrayList, and the UI gets populated accordingly.
When I click the back button (back to UserProfile) and go via the Intent to OrderForm again, the UI does not show the list items, why is that?
I realize I can use Room for persistence and even SharedPreferences, but
I wanted to see if there is cleaner, more efficient method, otherwise the less code the better.
Also, maybe I'm not understanding them correctly, but I tried onSaveInstanceState and onRestoreInstanceState and they don't work for me.
Thanks in advance.
Here is part of the code from OrderForm
public class OrderForm extends AppCompatActivity {
ArrayList<String> list;
ListView itemList;
ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_form);
itemList = findViewById(R.id.itemList);
itemText = findViewById(R.id.item);
linearLayout = findViewById(R.id.no_items_container);
orderContainer = findViewById(R.id.orderContainer);
list = new ArrayList<>();
arrayAdapter = new ArrayAdapter<String>(this,
R.layout.list_item,R.id.rowItem, list)
{
#Override
public View getView(int position,
View convertView,
ViewGroup parent) {
// some custom stuff here
}
}
public void addItem(View view)
{
String item = itemText.getText().toString().trim().toLowerCase();
if(!item.isEmpty() && list.indexOf(item) == -1) {
arrayAdapter.add(item);
}
}
You need to understand how Activity lifecycles work.
https://developer.android.com/guide/components/activities/activity-lifecycle.html
Your issue is that when pressing the back button, your OrderForm Activity is destroyed and effectively your arraylist/list view is destroyed. To avoid this problem, you'll have to store the values somewhere for example SharedPreferences, create a text file holding your strings and store it, or return the arraylist back to the UserProfile class where you'll store/handle them (to do that use startActivityForResult() instead of startActivity())
When I click the back button (back to UserProfile) and go via the Intent to OrderForm again, the UI does not show the list items, why is that?
In your onCreate() method, you have this:
list = new ArrayList<>();
arrayAdapter = new ArrayAdapter<String>(..., list)...
Unless you persist your data in some way, list is always going to be empty when your activity starts up.
I realize I can use Room for persistence and even SharedPreferences, but I wanted to see if there is cleaner, more efficient method, otherwise the less code the better.
Exactly what you need to store will help define the best way to store it. For a simple list of strings, probably SharedPreferences is the simplest solution.
Also, maybe I'm not understanding them correctly, but I tried onSaveInstanceState and onRestoreInstanceState and they don't work for me.
These methods are used to store data when an activity is destroyed and then recreated, which commonly happens when the user rotates the device (but can also happen for various other reasons). When you exit your activity (by pressing back to UserProfile), these methods aren't triggered.

Saving/Reloading data in android activities, possibly with an seperate class

I am new to android and am working on a fairly basic android application where users are able to create items that are added to a ListView. On creation of each item I create a instance of the 'clicker' class which keeps track of each items name/tick count/other statistics.
when on of the items in the list are clicked it launches a general activity, used by all of the items. I pass the 'clicker' class object to the activity so that it may construct initialize the textviews.
This is what happens when a list item is clicked (the clicker instances are created in a hashmap named clickers, so I first retrieve the key, then call clickers.get(key))
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// pass along some ID so that the new activity can retrieve info
String clickedName = clickerListItems.get(arg2);
Intent intent = new Intent(MainActivity.this, ClickerActivity.class);
intent.putExtra("clickerName", clickers.get(clickedName));
startActivity(intent);
}
This is how the general activity receives the info
public class ClickerActivity extends Activity {
protected Clicker currentClicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clicker);
Intent i = getIntent();
currentClicker = (Clicker) i.getSerializableExtra("clickerName");
TextView clickerHeader = (TextView) findViewById(R.id.clickerHeader);
clickerHeader.setText(currentClicker.getName());
final TextView countDisplay = (TextView) findViewById(R.id.countText);
countDisplay.setText(Integer.toString(currentClicker.getCount()));
final Button incrementButton = (Button) findViewById(R.id.incrementButton);
final Button resetButton = (Button) findViewById(R.id.resetButton);
(continues)
here's what the general activity looks like to add some perspective. It's fairly plain right now seeing as I am just starting out.
The issue is that say I click on item A of the ListView and increment it's counter (one of the stats) and then press the back button to return to the List Activity. Now if I click on the same listitem to reload the activity none of the data seems to have been saved. Is the clicker class instance not actually being altered? How do I save the info or restore the info? I would do something onRestoreInstanceState but since this is an activity that may be loaded by any item in the list that wouldn't work, right?
If there any clarification is required please let me know, thank you.
You can use shared preferences, to preserve those values.
http://developer.android.com/reference/android/content/SharedPreferences.html
By using this, none of your data will be lost. Just make sure that when you are starting the app again after killing it, you reset the values stored, so that your values are saved for activity relaunch, but not for app relaunch (unless you want it for that too).
EDIT: You can also put all your main code into an Asynctask(), so that processing would be done in the background and it would be kept alive even when you come out of the app.

How to recover data after closing another application

I'm developing an Android application and I need to open pdf files and return to same activity when back button is pressed.
Problem
I correctly open pdf file (from ActivityOne) using an intent and starting activity, but when I press back button, all data that I had in the ActivityOne (and previous activities) have been lost.
Here is my code of starting activity for showing pdf:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+"/"+ myApplication.getUsuarioActual().getFacturaActual().getPdf());
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
intent.setType("application/pdf");
startActivity(intent);
What do I have to do to solve that? Same occurs when I open another application and close it: when return to my app, it shows an error saying that all data is null.
EDIT
After reading that question, as #TheCharliemops recommended me, I know it is what I need, but I have another question related to that.
I have a class myApplicationthat extends Application to maintain global application state where I save all data that I read/write in different Activities.
My question is if I have to save all data I have in myApplication in every activity using onSaveInstanceState or there is some easiest manner to do it.
Firts of all, welcome to SO!!
Here, #reto-meier explains how to save the activity state in Android. I think that could fix your problem. I put his code here for future people with similar problem.
He says that you must override onSaveInstanceState(Bundle savedInstanceState) and onRestoreInstanceState(Bundle savedInstanceState) as following code shows:
Reto Meier said:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
// etc.
}
The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will get passed in to onCreate and also onRestoreInstanceState where you'd extract the values like this:
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
I hope this helps you.
Regards!

Retaining the data in the view during activity switch?

In my android app the user can enter the text in the EditView and the click on a button which takes him to an other activity where he can select a contact ... and then press a button which
brings him back to the first activity...
now the problem is I need to pass the selected contact to the first activity and display it (which i have done it using a bundle) but i am unable to retain already entered text in the EditView... which i should do (but the text should be retained with out passing it through the the bundle and getting it back)
thanks :)
The text in a view component is automagically saved by the OS, even after a soft kill (user changed phone orientation), but not after a hard kill, the user hit the back button while the parent activity was in focus. So, unless you are doing something non-standard, such as calling onSaveInstanceState without calling super.onSaveInstanceState, the data in the view state should persist.
One solution would be to save the text in the view component as a non view instance property before you launch the child activity, and just read this value back when the focus returns to the parent activity in the method onActivityResult.
JAL
EDIT: The Android Docs Activity page has been extensively updated. View state will not be saved if the widget does not have an ID.
EDIT: What I am saying is that the view state should be persisted by the OS. You should not need to save the view state manually. On a hard kill, you would need to save the state of your activity IF that is the expected behavior of the activity. So here is some code that saves the activity state. Given an instance variable:
String password;
Here we save state on a soft kill:
protected void onSaveInstanceState(Bundle outState){
password= editTextPassword.getText().toString();
outState.putString("password", password);
super.onSaveInstanceState(outState); // save view state
}
Here we save state on a hard kill
#Override
protected void onStop(){
super.onStop();
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("password",password);
editor.commit();
Here we restore state in onCreate(Bundle savedInstanceState):
if( savedInstanceState!= null){ // get saved state from soft kill after first pass
try {
password= savedInstanceState.getString("password");
Log.d(TAG,"RestoredState!");
}
catch(Exception e){
Log.d(TAG,"FailedToRestoreState",e);
}
}
else { // get saved state from preferences on first pass
SharedPreferences prefs = getPreferences(MODE_PRIVATE); // singleton
if (prefs != null){
this.password= prefs.getString("password","");
Log.d(TAG,"gettingPrefs");
}
}
Log.d(TAG,"onCreate");
Also given the fact that IF onSaveInstanceState is called it will be called before onStop, it is possible to use the flags isSavedInstanceState and isSavedPreferences to write to prefs ONLY on a hard kill if you reset the flags in onResume as:
protected void onResume() {
super.onResume();
Log.d(TAG,"onResume");
isSavedInstanceState= false;
isSavedPrefs= false;
}
Setting the flags in onCreate will not result in the desired outcome.

Categories