Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Saturday, November 26, 2016

Preserving data over different Activities

Preserving data over different Activities


I'm having an issue with preserving the data entered by a user on my android activity classes. I have identified I need to make use of the onSavedInstanceState(Bundle outState) method but the way my program is written makes this difficult.

A user enters a variety of data in DataEntry.java class and the information they submit is displayed on DataSummary.java. This works fine.

But when a user navigates away from DataSummary.java say, to fill in the rest of the information on DataEntry.java the original submitted data is lost if you go back to DS.java to see what you've written already. Below is the code for DataSummary.java.

public class DataSummary extends Activity {    ImageView resultImage;  TextView resultName;   TextView resultDescription;  TextView resultType;  TextView resultProject;    public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);      setContentView(R.layout.activity_data_summary);       //Check if there is anything in the 'bundle' and if not produce message - AVOIDS NULLPOINTEREXCEPTION when navigating to Activity     Bundle bundle = this.getIntent().getExtras();          if (bundle != null){     int image = bundle.getInt("image");     String name = bundle.getString("key");     String description = bundle.getString("key1"); //gets data from DataEntry activity     String type = bundle.getString("key2");     String project = bundle.getString("key3");       resultImage=(ImageView)findViewById(R.id.resultImage);     resultName=(TextView)findViewById(R.id.resultName);  //adds the TextViews to the activity     resultType=(TextView)findViewById(R.id.resultType);     resultDescription=(TextView)findViewById(R.id.resultDesc);     resultProject=(TextView)findViewById(R.id.resultProject);       resultImage.setImageResource(image);     resultName.setText(name); // Fills the textviews with imported data     resultType.setText(type);     resultDescription.setText(description);     resultProject.setText(project);     }           else     {         Toast.makeText(DataSummary.this,"Received no data yet!", Toast.LENGTH_LONG).show();     }    }    /* MANAGES ACTIVITY LIFESTYLE */  public void onSavedInstanceState(Bundle outState){        super.onSaveInstanceState(outState);  }  

How can I expand on the onSavedInstanceState method to get the imported data which is received when the Activity is created and preserved it if a user navigates away from this activity? Hope that's well explained enough?

It is difficult to figure out how to make use of the variables in onCreate as well as I cannot access them from another method (I think if I knew how to do this I could complete the method).

Answer by razielsarafan for Preserving data over different Activities


You can set static variables on your class. When the user enters the data, you just write that data on your variables. When the user comes back to the app, you just write the data stored in your variables into your EditTexts.

EDIT: Example

Let's assume you have 2 EditTexts et1 and et2, and the values they store are username and mail.

public class DataEntryActivity extends Activity{        private static String username;      private static String mail;        @Override      public void onCreate(Bundle b){           super.onCreate(b);           setContentView(R.layout.layout_data_entry);           EditText et1 = (EditText) findViewById(R.id.editTextUsername);           EditText et2 = (EditText) findViewById(R.id.editTextMail);           if (username != null)                et1.setText(username);           if (mail != null)                et2.setText(mail);           Button save = (Button) findViewById(R.id.saveButton);           save.setOnClickListener(new OnClickListener(){                  public void onClick(View v){                       if (et1.getText().toString().length() > 0)                          username = et1.getText().toString();                     if (et2.getText().toString().length() > 0)                          mail = et2.getText().toString();                     Intent intent = new Intent(DataEntryActivity.this, YourOtherActivity.class);                     startActivity(intent);                }             });        }          public static String getUsername(){           return username;      }        public static String getMail(){           return mail;      }    }  

From your other activity you just have to call DataEntryActivity.getUsername() and DataEntryActivity.getMail() to get them back.

Answer by Raphal Titol for Preserving data over different Activities


I would suggest you to have a look at this post, which explains clearly how to use global variables in your whole application.

Android global variable

Answer by Anup Cowkur for Preserving data over different Activities


Here's one logic you can use. When you get the data from the intent, save it into the shared preferences of your app. Every time you enter this activity, check if those keys exist in the shared preferences, if they do, get them and display them, otherwise retrieve them from your saved instance state and write them tot eh shared preferences.

And in the onStop() method of your DataEntry activity, clear these shared preferences.

So, user goes from

DataEntry-->DataSummary ----check shared preferences in DataSummary, if data exists, use it. If some data exists or no data exists, get others from bundle and write it here.  

In this way, every time user goes back and forth, whatever he entered will be still be there in shared preferences. Then,

DataEntry--->Exit app or press back button, clear shared preferences fields so that when this activity is created next time (when user comes here again), he gets a clean slate  

Answer by Rmi for Preserving data over different Activities


If I understand correctly, you have a global state that you wish to share between two activities. You cannot deal with this problem with savedInstanceState, because when you navigate back from DataSummary to DataEntry, and then go forward to DataSummary again, the new DataSummary is a different instance, and does not get the savedInstanceState you saved previously.

In order to make it work, you have to pass the data added by DataSummary via the intent, not the savedInstanceState. In order to get the data that was entered in DataSummary, you can return it from DataSummary to DataEntry, using startActivityForResult: http://developer.android.com/reference/android/app/Activity.html#StartingActivities

Using static global variable does not work, because static global variables are lost if the application is killed in the background.

Using shared preferences, a file or a database might work, but it is not very convenient, and also not very elegant (you share the data with the whole application, whereas communicating via intents limits data access to your two activities).

Answer by DuneCat for Preserving data over different Activities


For starters, you shouldn't use onSavedInstanceState to pass information between Activity instances. There are different ways to share state between activities, one being to extend the Application class and use it as a singleton. You can also just use a regular singleton, but the nice thing about extending Application is that its onCreate method is guaranteed to be called when your application starts.

public class YourApplication extends Application {      private static YourApplication mInstance;      private mDataState;        @Override      public void onCreate() {          super.onCreate();          mInstance = this;          mDataState = new DataState();      }        public static YourApplication getInstance() {          return mInstance;      }        public DataState getDataState() {          return mDataState;      }        public void setDataState(DataState dataState) {          mDataState = dataState;      }  }  

Now you can you setDataState in the DataEntry activity, and getDataState in the DataSummary activity, getting the only instance of YourApplication using its getInstance method. It might be an idea to get the stored values in the onCreate method of DataEntry, so the user can see what was entered before.


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.