Updating a list after a child process has finished - android

The main activity of the application is to display a list. The user clicks on something on the list which opens a edit screen. Upon fisnish, the edit screen is closed - and I want the original list to be updated with whatever hapenned on the edit screen. I save the data to a file - and I can just read it again to update the list. However I don't know where to insert the re-read code.
In the ListActivity - what method is called whe the list gets focus again?
This is my main List activity code:
Creating the view:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate our UI from its XML layout description.
setContentView(R.layout.my_activity);
list=new Data_List(this); // my data reading class
list.read_data(); // reads from a file
load_dynamic_list();
}
Loading the data:
private void load_dynamic_list(){
ladapter=new
list_adapter(this,android.R.layout.simple_list_item_1,list); // the type is actually ignored // getview function in list_adapter handles everything
setListAdapter(ladapter);
this.getListView().invalidate();
}
Something was selected:
protected void onListItemClick (ListView l, View v, int position, long id){
int a;
intent = new Intent(this,Editing.class);
intent.putExtra("New_entry",0);
intent.putExtra("Entry",position);
//start the second Activity
this.startActivity(intent);
}
In the Editing function I end off like this:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.button_save){
do_save(); // saves to a file
// I want something like: caller.getListView().invalidate();
finish();
}
if(v.getId() == R.id.button_cancel){
finish();
}
}
What method can I override or call that will execute when the editing is done? At that point I want to read_data() and then load_dynamic_list() again.

You have to use AsyncTask.
Prefer URL :
http://steveliles.github.com/android_s_asynctask.html
http://www.vogella.com/articles/AndroidPerformance/article.html
With example :
http://labs.makemachine.net/2010/05/android-asynctask-example/

#Override
protected void onResume() {
super.onResume();
list=new Data_List(this);
list.read_data();
load_dynamic_list(); // becuase whatever was edited needs to be reread.
}

Related

delete item from Activity after receive it in Fragment / Lifecycle issue

I need some help. I've got activity where I create item. Next I want to send it to the fragment in second activity so I need to firstly send it to that Activity (am I correct ?). This is how I create item :
public void savePart() {
Part part = new Part(name,quantity,"","",tag,"","2");
Intent intent = new Intent(this,InvActivity.class);
intent.putExtra("Part", (Serializable) part);
setResult(2,intent);
finish();
}
This is how I receive it in second activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 2) {
part = (Part) data.getSerializableExtra("Part");
}
}
I've got method to return the part in fragment :
public Part getMyData() {
return part;
}
In Fragment's onResume() I receive the Part object, check if object with similar code exists and add it to the ListView if not:
#Override
public void onResume() {
super.onResume();
List<Part>subList = new ArrayList<>();
if (mActivity.getMyData() != null) {
Part part = mActivity.getMyData();
for(Part parts : mParts) {
if (parts.getCode().contains(part.getCode())) {
subList.add(parts);
}
}
if (subList.size() == 0) {
mParts.add(part);
adapter = new PartAdapter(getContext(), R.layout.part_item, mParts, mActivity, new AdapterCallback() {
#Override
public void onMethodCallback() {
}
});
mPartsLV.setAdapter(adapter);
} else {
Toast.makeText(getContext(), R.string.equipment_exists, Toast.LENGTH_SHORT).show();
}
}
}
So far everything works well. items are added correctly and shown in ListVIew in fragment.Here is where the problem begins :) In listView row I've got imageView which deletes item from ListView.
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mParts.remove(part);
notifyDataSetChanged();
}
});
That works great to but ... when fragment comes back to onResume() deleted item shows again is ListView. That is because each time I receive Part and check if exists in List. I think I should somehow clear intent after receiving Part from Activity where Part was created but I don't know how ? Maybe any other solution,please ?
Declare your subList as public and populate it once. So you need to modify your onResume function a bit. Check if the list is populated already. If not, populate the list from the extras and vice versa.
ListsubList = new ArrayList<>();
your list is created every time when onResume() called that's why delete entries could not managed. So either take a copy of this list or every time check which elements got deleted,and then set data to listview.

Going back and forth between intents without losing user entered data

I have a form. Here, the user fills in details like event name, description, location etc. To select the location, I have set a button. This is my button code:
btnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent map = new Intent(getApplicationContext(), Map2.class);
startActivity(map);
}
});
I select the location from there, and the data is passed back to my main intent correctly. But the thing is, the data in the other fields like event, description etc. that users filled in are lost.
I tried startActivityForResult(map,1); too. Doesn't work. Is there a way to keep the data, without sending them in a bundle to the other intent and getting them back? like the select image button does? It goes to the gallery and comes back without resetting the other fields
contactImageImgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), 1);
}
});
You need to save your activity state.
Override the method onSaveInstanceState and persist all your data in the bundle
In onCreate, if savedInstanceState is not null, restore all your data and set all the fields.
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("MY_FIELD", 43);
// ... other fields
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
if (savedInstanceState != null) {
int value = savedInstanceState.getInt("MY_FIELD");
// ... update your views
} else {
// no previous state, start fresh
}
}
Details here
Note: you have mentioned that rotation is blocked. This is generally bad for the user unless it's part of the feature of the app.
Explanation:
A screen rotation is a configuration change that causes the activity to restart with the appropriate resources. There are many more configuration changes such as screen unlock,device docked etc. Not all of them trigger an activity restart but some do. When your activity restarts due to a configuration change, onSaveInstanceState gets called and savedInstanceState will be not-null when onCreate is called.
When you start a new activity Android may destroy the previous one to recover some of the resources it was consuming. In that case, when you return to that previous activity, it is actually a new instance of the Activity subclass and the internal state has been lost. It's up to you to save and restore any state necessary within the onSaveInstanceState and onCreate callback methods, respectively.
Have a look at this page for more information and examples: Recreating an Activity | Android Developers
public class FormActivity extends Activity {
private static final String NAME = "NAME";
private EditText nameEdit;
// Declare other view references here...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
nameEdit = (EditText) findViewById(R.id.name_edit);
// Find other views...
if (savedInstanceState != null) {
final String nameValue = savedInstanceState.getString(NAME, "");
nameEdit.setText(nameValue);
// Restore other saved values...
} else {
// No saved values to restore
}
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
final String nameValue = nameEdit.getText().toString()
outState.putString(NAME, nameValue);
// Put (save) other values into the outState bundle...
super.onSaveInstanceState(outState, outPersistentState);
}
// Other FormActivity code...
}

Shared Preference not saving value [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am just learning to build some applications in Android. Out of curiosity, I have a small and weird problem using Shared Preferences. If someone can help me addressing this issue , I would be most thankful to them. Anyways,here goes the problem. I have 2 Activities. 1. Activity 1 : Consists of just one button that will get you to the next activity. 2. Activity 2 : Consists of a listview with checkbox (simple_list_item_checked or simple_list_multi_choice_item).
My question is: I open my application, hit the button on my first activity screen, this moves me to the second activity. I check an item in the listview. I hit the back button on my phone, go to the first activity, again press the button on my activity 1 screen, this takes me to the list again. Now I just leave my list item checked(I don't change anything that is already checked previously). Now again, I hit back button on my phone, get back to activity one. Now again when I press the button on my activity one screen. It takes me back to the listview but SURPRISINGLY nothing is checked. To note a point here, I had also set and retrieved my shared preference.
MY QUESTION IN A SINGLE LINE IS : If I don't change a value in the check list while I'm in that Activity and then go back to the Main Activity, and get back to the same check list activity, my shared preference does not load what has been saved earlier. Is this the normal behavior of Shared Preference or is it a problem in the coding.
I would just like to know how preference values are saved and retrieved and how long does a preference save a value ? I mean the lifecycle of the saved value in preference.
MY SECOND QUESTION : Also, I would like to know one more thing in activity life cycle. When I am in the second activity as explained in the above example. Now I press the home button , now I go to the background tasks and clear all the tasks(Apps) that are running . Now, my question is which state of activity life cycle is followed or what will be the final activity lifecycle before i clear all my apps from the background ? Please someone help me out on this. Thanks to all those creative developers out there in advance. Hope someone can solve my issue.
public class Secondact extends ListActivity {
ListView list;
SharedPreferences pref;
int pos,itemposition,positionvalue;
boolean boolval,checkvalue;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.secondact);
Toast.makeText(getApplicationContext(), "ONCREATE", 50).show();
list=getListView();
String[] family_array=this.getResources().getStringArray(R.array.family);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,family_array);
list.setAdapter(adapter);
list.setChoiceMode(1);
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
pos=pref.getInt("itempos", pos);
boolval=pref.getBoolean("boolvalue", true);
list.setItemChecked(pos, boolval);
Toast.makeText(getApplicationContext(), "DATA LOADED ITEM NO:"+pos, 50).show();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
pos=position;
list.setItemChecked(pos, true);
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor=pref.edit();
editor.putInt("itempos", pos);
editor.putBoolean("boolvalue", list.isItemChecked(pos));
editor.commit();
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor=pref.edit();
editor.putInt("itempos", pos);
editor.putBoolean("boolvalue", list.isItemChecked(pos));
editor.commit();
// Toast.makeText(getApplicationContext(), "PAUSE", 50).show();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
pos=pref.getInt("itempos", pos);
boolval=pref.getBoolean("boolvalue", true);
list.setItemChecked(pos, boolval);
//Toast.makeText(getApplicationContext(), "RESUME", 50).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor=pref.edit();
editor.putInt("itempos", pos);
editor.putBoolean("boolvalue", list.isItemChecked(pos));
editor.commit();
Toast.makeText(getApplicationContext(), "DESTROY", 50).show();
Toast.makeText(getApplicationContext(), "DATA SAVED ITEM NO:"+pos, 50).show();
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
pos=pref.getInt("itempos", pos);
boolval=pref.getBoolean("boolvalue", true);
list.setItemChecked(pos, boolval);
//Toast.makeText(getApplicationContext(), "RESTART", 50).show();
}
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
savedInstanceState.putInt("itempositionno", positionvalue);
savedInstanceState.putBoolean("checkvalue", true);
Toast.makeText(getApplicationContext(), "ONSAVEINSTANCE", 50).show();
list.setItemChecked(pos, checkvalue);
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
pos=savedInstanceState.getInt("itempositionno", pos);
checkvalue=savedInstanceState.getBoolean("checkvalue", true);
list.setItemChecked(pos, checkvalue);
Toast.makeText(getApplicationContext(), "ONRESTOREINSTANCE", 50).show();
super.onRestoreInstanceState(savedInstanceState);
}
}
I would just like to know how preference values are saved and
retrieved and how long does a preference save a value ? I mean the
lifecycle of the saved value in preference.
A single line reply to your single line question -
It is saved throughout the life-cycle of the application unless you yourself clear it.
To obtain shared preferences:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To read preferences:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
To edit and save preferences
In order to edit(clear) -
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.commit();
In order to save -
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).commit();
Read - how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values.
Which state of activity life cycle is followed or what will be the
final activity life-cycle before I clear all my apps from the
background ?
Depends on your requirement. No need to follow final activity life-cycle to do this. For example - When the user logs out from the application, preferences related to the user are of no use and can be cleared independent of the life-cycle just after the log out button press.
Alright, for those who are suffering from the same problem of the shared preference not maintaining the value on activity switch. This piece of logic does the trick:
Set your default value of your row in the listview like this
sp.getInt("CheckedValue",
pass the position of the ealier checked row as the default one
viz.Listitem.getCheckedItemPosition());
This will save the checked value throughout your application's life cycle and/or activity life cycle.
NOTE:
Make sure to clear your sharedpreference before commit() so as to avoid the hectic memory usage of your app.

onResume causing problems on start up

I have an activity that allows the user to start a second activity. The second activity has a list of items which I add to an array list. When I return to the previous activity I want to display the size of the array list.
However I am having a problem with onResume(). It is called when my first activity is created and as a result generates an error as the array list does not exist when it is first launched!
onResume():
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
getIntentData();
calcSubTotal(orderData);
}
getIntentData():
public void getIntentData(){
b = new Bundle();
b = getIntent().getExtras();
orderData = b.getParcelable("order");
Toast.makeText(this.getApplicationContext(), orderData.size(), Toast.LENGTH_LONG).show();
}
onCreate() of second activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starters);
createTestData();
b = new Bundle();
orderData = new MenuItemList();
adapter = new MenuItemArrayAdapter(this, starters);
this.setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(this.getApplicationContext(), l.getItemAtPosition(position).toString() + " clicked", Toast.LENGTH_LONG).show();
//add clicked item to orderData....
MenuItem m = (MenuItem)l.getItemAtPosition(position);
//create new item
orderData.add(m);
}
Any idea how I might be able to control this?
ERROR:
java.lang.RuntimeException: Unable to resume activity {com.example.waitronproto3/com.example.waitronproto3.SectionsActivity}: java.lang.NullPointerException
I think you may want to have a look at startActivityForResult instead, when you're starting your second Activity. It'll allow your second activity to return a result back to your first activity. You can read up on it at the Activity documentation, specifically the "Starting Activities and Getting Results" section of the document.
Edit: By the looks of your code - nothing you're doing is either storing a bundle from the second activity and sending it back to the first. So you'll never get the proper Bundle data in your first activity. As suggested, look into startActivityForResult to launch your second activity with. This will allow you to return data back into your first activity with ease.
However I am having a problem with onResume(). It is called when my first activity is created and as a result generates an error as the array list does not exist when it is first launched!
I recommend changing getIntentData() to check if the appropriate data exists first:
public void getIntentData(){
Intent intent = getIntent();
if(intent != null && intent.hasExtra("order")) {
orderData = b.getParcelable("order");
Toast.makeText(this.getApplicationContext(), orderData.size(), Toast.LENGTH_LONG).show();
calculateSubTotal(order);
}
}
And update onResume():
#Override
protected void onResume() {
super.onResume();
getIntentData();
}
(Though you could simply put getIntentData() in onResume() now.)
Your onResume() will be called after onCreate() according to the Android Lifecycle so you will want to check that the data is not null before trying to use it.
`if(intentData != null)
//do something`

Use onBackPressed to save a file

I want to allow users to save a list of favourite items from a list, so I display the full list using a Listview with checkboxes, and the user will check or uncheck items in the list.
When the user presses the back button, I want to be able to save the checked items out to a separate file on the SD card.
I'm using the following method in my Activity:
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
}
However, the list that I create within my OnCreate method is not available within the onBackPressed method - ie it's out of scope.
If I try and pass the list into the onBackPressed method as follows:
#Override
public void onBackPressed(ArrayList<HashMap<String, Object>> checked_list) {
// TODO Auto-generated method stub
}
Then I get the error:
"The method onBackPressed(ArrayList>) of type SetFavourites must override or implement a supertype method" and Eclipse prompts to remove the #Override.
But when I do this, then the onBackPressed method never gets called.
How can I pass variables into the onBackPressed method so that I can perform actions on data within my Activity before exiting?
Thanks
You can define a variable in the class' scope, ie outside onCreate().
class Example {
int mVisible = 0;
void onCreate() {
int notVisible = mVisible;
}
void onBackPressed() {
mVisible = 10;
}
}
You can't use #Override to override a non-existent method. In other words onBackPressed(ArrayList<...> foo) is not an existing method of the Activity class.
To access your list declare it as an instance member of your Activity...
public class MyActivity extends Activity {
ArrayList<HashMap<String, Object>> checked_list;
// onCreate(...) here
// onBackPressed() here
}

Categories

Resources