Cleaning a Listview for data - android

I've got a ListView, an ArrayList. From activity1, I pass some data, e.g a price and a name of a company. This data will be stored in an ArrayList of Hashmaps. When I first passes some data to the second activity which holds the ListView the data will be found in this list, but when I go back to the first activity and pass some information again, the old data will still be in the list. Is there any possible way I can prevent this to happend? For instance, when I return from activity2 to activity1, the ListView will be wiped.
Thanks!

what you need to do:
on the activity which holds the listView - override the onResume() method:
#Override
protected void onResume() {
super.onResume();
mArrayList.clear();
mAdapter.notifyDataSetChanged();
}
if it's not good for you to clear the array list, so you can do the following:
#Override
protected void onResume() {
super.onResume();
mListView.removeAllViews();
}

Related

How to notifydatasetchanged between two activities

I have two activities that each contain fragments. Activity A has a fragment with a ListView. Rows of the ListView are obtained from a SQLiteDatabase.
Activity B contains a fragment that enables entries of the database to be edited. When a user edits a database entry, saves the data, then returns to Activity A via the backbutton or:
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
How do I notify the ListView in Activity A that there has been a change to the database? I understand how to communicate between an Activity and it's fragments, but how do I implement a notifydatasetchanged when the fragments are in two different activities?
I suspect that going back to Activity A via the back button is simply recalling the view from the stack, but that view has changed when there is a database change.
You could simply call the notifyDataSetChanged in onResume in your Activity A. So when you close or go back from Activity B to A, it will update the data. Don't forget to check if the adapter is different than null, otherwise it could crash the first time you open the App.
You could also make a public function in your Activity A which updates the list and call it from your Activity B.
class ActivityA
public static void updateList() {
if(adapter != null){
adapter.notifyDataSetChanged;
}
}
class ActivityB
ActivityA.updateList();
Hope it helps :)
you could start activity with startActivityForResult(start activityB) and override method onActivityResult in activityA and notifyDataSetChanged when needed.
You will need to read the updated dataset from your SQLite database and pass it adapter again. After you need to notify adapter. For example, like in the code below:
In your Activity A
#Override
protected void onResume() {
super.onResume();
// method to read new dataset
Database ourDB = new Database(this);
ourDB.openDB();
data = ourDB.getData();
ourDB.closeDB();
if(adapter == null) {
// initializes adapter when first launched
adapter = new RecyclerViewAdapter(data, this);
yourListView.setAdapter(adapter);
}
else {
// in subsequent returns to activity we are replacing
// old data with new and reusing existing adapter
adapter.updateData(data);
}
}
In your adapter class include similar method:
public void updateData(ArrayList<String> newData) {
data = newData;
this.notifyDataSetChanged();
}

Using onSaveInstanceState to prevent network call a second time

In my OnCreate method I am making a network call and populating a listview with the results. I am saving the result in an ArrayList and using the ArrayList to populate the listview. If the user presses the back button and reenters the activity I would like to store the ArrayLists in a SavedInstanceState Bundle and populate the ListView with the stored ArrayLists instead of making the network call a second time. The following is my OnCreate code:
if (savedInstanceState != null) {
largeImage = savedInstanceState.getParcelableArrayList("Image");
flowercode = savedInstanceState.getStringArrayList("Code");
flowerprice = savedInstanceState.getStringArrayList("Price");
flowerdimensions = savedInstanceState.getStringArrayList("Dimension");
largeImageText = savedInstanceState.getStringArrayList("Imagetext");
ListView listView = (ListView) findViewById(R.id.LowRomance);
FlowerShopAdapter listAdapter = new FlowerShopAdapter(this, flowercode, flowerName, flowerprice, largeImage, flowerdimensions);
listView.setAdapter(listAdapter);
} else if(savedInstanceState == null) {
makesoapcall();
}
}
This is my OnSaveInstanceState code
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putParcelableArrayList("Image", largeImage);
savedInstanceState.putStringArrayList("Code", flowercode);
savedInstanceState.putStringArrayList("Price", flowerprice);
savedInstanceState.putStringArrayList("Dimension", flowerdimensions);
super.onSaveInstanceState(savedInstanceState);
}
Currently my App is making the network call every single time. Is their something else I need to implement in order to get this to work or is their an error in the current way I am trying to implement this? The ArrayList's are definitely not null when I put them into savedInstanceState.
onSaveInstanceState() is not supposed to be called when the back button is pressed on an Activity. It's called when Android decides to destroy the Activity.
e.g. When orientation changes.
What you need here is SharedPreferences. Store the ArrayLists using SharedPreferences in onStop(). And get it in onStart(). Here is how to store ArrayList in SharedPreferences.

How to call ListView adapter from another activity for refresh - notifyDataSetChanged()

I want to call a listview adapter from another activies after insert record to sqllite db.
I cant call the adapter.notifyDataSetChanged() method. What is the best way to do it.
public void onClick(View v) {
TextView item_name;
item_name=(TextView) findViewById(R.id.eItemName);
Log.d("Insert: ", "Inserting ..");
db.add_item(new Item(item_name.getText().toString()), getApplicationContext());
// I want to call the method HERE!!!!
finish();
}
Just
After finish() Current Activity, Call adapter.notifyDataSetChanged() from onActivityResult()in previous Activity (As I assumes your Listview in this previous Activity).
Also start your Current Activity from Previous Activity using startActivityForResult();
Or if you have reference of List Adapter in this Activity, then using that reference call adapter.notifyDataSetChanged(). (But I think its not a good practice)
The better option would be re-loading your ListView with new data inside onResume() of your Activity where you have ListView. There is no need to call notifyDataSetChanged() from another class as you don't have your List visible in your another Activity.
#Override
protected void onResume() {
super.onResume();
//fill your Collection with new data
// setAdapter or notify your adapter
}

android - pass data from one activity to a list in a second activity

new to droid programming. im having a small problem that im sure is simply fixed but ive done some searching and a bunch of tutorials but cant seem to find just what i need so i figured id ask. My app has 2 activites, the first activity is just a simple form where a user enters course information(class title, professor..etc.)
the first activity passes the data which is supposed to be stored in a list in the second activity. problem is that only the first course gets stored in the list, after the first time nothing new gets added to the second activity. Can someone point me in the right direction please? thanks in advance
First Activity
public class CourseDetail extends Activity {
//Course c = new Course();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button save=(Button)findViewById(R.id.save);
save.setOnClickListener(onSave);
}
private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {
EditText course=(EditText)findViewById(R.id.course);
EditText professor=(EditText)findViewById(R.id.professor);
EditText location=(EditText)findViewById(R.id.location);
EditText officehrs=(EditText)findViewById(R.id.officehrs);
Intent i=new Intent(CourseDetail.this, CourseList.class);
i.putExtra("myCourse", course.getText().toString());
i.putExtra("myProfessor", professor.getText().toString());
i.putExtra("myLocation", location.getText().toString());
i.putExtra("myOfficehrs", officehrs.getText().toString());
startActivity(i);
}
};
}
Second Activity
public class CourseList extends Activity {
Button btnCourse;
List<Course> model = new ArrayList<Course>();
CourseAdapter adapter=null;
private String dCourse="";
private String dProfessor="";
private String dLocation="";
private String dOfficehrs="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clist);
ListView list =(ListView)findViewById(R.id.courses);
adapter=new CourseAdapter();
list.setAdapter(adapter);
Course c = new Course();
Bundle extras = getIntent().getExtras();
dCourse = extras !=null ? extras.getString("myCourse") :"no value entered";
dProfessor = extras !=null ? extras.getString("myProfessor") :"no value entered";
dLocation = extras !=null ? extras.getString("myLocation") :"no value entered";
dOfficehrs = extras !=null ? extras.getString("myOfficehrs") :"no value entered";
c.setCourse(dCourse);
c.setProfessor(dProfessor);
c.setLocation(dLocation);
c.setOfficeHrs(dOfficehrs);
btnCourse =(Button)findViewById(R.id.btnCourse);
btnCourse.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
You are just getting the user entered value in CourseDetail activity and displaying the received value inside the CourseList activity, that means you are not storing these values permanently.
Go through this Android - Data Storage document.
When you move to 2nd activity i.e. CourseList activity, at that time fetch the data from the SQLite table and display the same. whenever you get new values from previous activity, at that time just update the list by adding the new data in ArrayList and make a call on adapter.notifyDataSetChanged()
Some suggestions:
Have your CourseList extend ListActivity instead of just Activity - check out some tutorials on that which should help you set things up correctly.
There seems to be a bit of confusion with how you're handling your lists - you have your model variable but don't seem to be doing anything with it. Again, have a look at a ListView tutorial (just google "android listview tutorial").
You seem to have figured out that you can use "intents" to pass information from one activity to another, but since you're only doing this in the onCreate() method, it's only happening once. Try doing this in your ListActivity's adapter once for each item.
Don't give up on Android, keep trying :-)
Some suggestion:
You have to add your object to the adapter: adapter.add(c); after you get the data.
Call adapter.notifyDataSetChanged() to notify the system that your data for the listView has been changed. Call list.invalidate() to refresh it.
I noticed that you set the button with the finish() method. Hmm, if you do so, the next time you get to CourseList Activity from CourseDetail, the adapter will be null again. No previously received data will be available. Is this what you really want?
The problem is you are not adding the newly added items to the List.So before setting adapter you have to add all your objects like
list.add(c);

Refresh ListView when returned to activity on android

I am currently developing an android app. The app has 2 activities. Activity 1 is a ListActivity. ListActivity calls a standard Activity. When the 2nd activity is finished, I use the finish() method to close the activitity which returns to the ListActivity. I need the ListActivity to now refresh with the new dat
You should just call notifyDataSetChanged() on your adapter when you return back to your activity.
The API states:
void notifyDataSetChanged()
Notifies the attached View that the
underlying data has been changed and
it should refresh itself.
Have you packaged the data into and intent? For that matter did you startActivityForResult()? If so the you would take the data out of the intent by overriding the onActivityResult(...) method and add the data to what ever you need to do. Then like sahhhm said notifyDataSetChanged().
~Aedon
You need reload the info in the ListView...
#Override
protected void onResume() {
super.onResume();
mAdapter= new mYCustomAdapter(mActivity.this, valuesReloaded);
mList.setAdapter(mAdapter);
mAdapter.myMethodThatNotifyChange();
}
where:
valuesReloaded is the new Array with the new Values.
mAdapter is a Custom Adapter
myMethodThatNotifyChange is a method in the Class MyCustomAdapter where you must call notifyDataSetChanged() , ( in a custom adapter can only call from the class adapter)
class myCustomAdapter extends BaseAdapter{
...
...
myMethodThatNotifyChange{
notifyDataSetChanged();
}
...
...
}
Or finish the actual activity, and reload with a new intent
#Override
protected void onResume() {
super.onResume();
Intent mIntet = new Intent(mlistViewPersons.this , mlistViewPersons.class)
startActivity(mIntent);
finish();
}

Categories

Resources