robotium, how to test listview - android

how can I test listview by robotium? I just want to check if oncreate event the items goes into it.
my Activity has a method:
private void initListView() {
Adapter adapter =
new Adapter(this, myRepository.findAll());
listView.setAdapter(adapter);
}
MyRepository returns List. In the ActivityInstrumentationTestCase2 I want to put some items into respository and then test if listView contains elements.
public void testListView_IsNotEmpty() {
Item i = new Item();
i.setSomething("item1");
getActivity().getMyRepository().insert(i);
assertTrue(solo.searchText("item1"));
}
Is it via robotium possible do to that?
best regards

This is clear case for mocking framework. I recomment jMockit as it is most advanced and suitable to use against stubbed out android libraries. As you do not like to test classes provided by android itself ( you implicitely trust that they do right thing ) , you only have to test that:
your repositry was asked for value list
this value list was used to create an adapter
this adapter was passed to list view
Test case would look like this:
#Test
public void testThatListInitializedProperly(#Mocked final ListView listView,
#Mocked final YourRepository repository,
#Mocked(methods = {"initListView"}, inverse=true) final YourActivity activity,
#Mocked final Adapter adapter
) {
new Expectations() {
{
repository.findAll(); returns(someList);
new Adapter(activity, someList); returns(adapter);
listView.setAdapter(adapter);
}
};
activity.initListView(listView);
}
(note that I adjusted interface for easier mockability )

Related

How to handle a custom ArrayAdapter in an Android MVP project?

I have an Android MVP project. I want to keep out any Android references out of the presenter. This way, I can keep UI separated in the Activity/View.
There is a ListView in the Activity which uses a custom ArrayList in the adapter (MyAdapter). This uses MyModel objects to populate the ListView with data.
Now, I'm trying to initialize the adapter and the ListView.
By doing that on the activity I would end up with something like
`MyAdapter adapter = new MyAdapter<MyModel>(this, R.layout.list_item, items);`
The problem with this is that the Activity now have access to the Model and has a reference to an ArrayList of items which I wanted to keep only in the presenter and manage it from there.
I can't move setup the adapter on the Presenter because I would have to share the context from the Activity to the presenter, setup the adapter and pass it back to the Activity. The problem with this is that the presenter now depends on an Android context object (There shouldn't be any Android code in the Presenter part of an MVP Android project).
So the question is what do I do in this case? Where and how do I handle setting up the ArrayAdapter?
You can keep a list of items in the Presenter and then, send it to the Activity when you need to set up the adapter.
I think you can do:
Contract:
public interface ViewContract {
void setupContentList(ArrayList<MyModel> list);
}
public interface PresenterContract {
void onViewCreated();
}
Activity:
public class MainActivity extends Activity implements ViewContract {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
......
mListView = findViewById(R.id.listview);
mPresenter.onViewCreated();
}
public void setupContentList(ArrayList<MyModel> list) {
MyAdapter adapter = new MyAdapter<MyModel>(this, R.layout.list_item, items);
mListView.setAdapter(adapter);
}
}
Presenter:
public class Presenter implements PresenterContract {
public Presenter() {
ArrayList<MyModel> mItems = new ArrayList();
// Add items to the list
}
public void onViewCreated() {
mView.setupContentList(mItems);
}
}
I recommend you to use RecyclerView and not ListView for better performance.
The activity can hold the RecyclerView, you should ask the presenter to fetch the data you want from your model repository, etc.
After the presenter retrieved the data you should notify the Activity about the new data, and set it to the RecyclerAdapter.
Now your activity holds inflates all regarding the view, and the presenter is a hub for data and logic.

Add data in listview using background service

Creating an app in which I am showing feeds in listview and storing feeds record in sqlitedatabase. Now I want that if anyone add new feed, that listview should be automatically update using background service and service will be run in every 1 min and that new value should be inserted in database and generate notification of new added feed.
I don't know how to add service and how to set adapter for listview in service class. I know I have to add intent service for this.
Searched but I did not understood.
What I want: Assume I have two images in feed list view and someone added one more image, so this new added image should be automatically shown in my feed without refreshing the feed listview. For this I have to run background service which will run in every 1 min and that new added image will be shown.
But I don't know how to add service, for this how to call server in service class and add data in listview in service class and add record in sqlitedatabase and generate notification for new feed. This all will be in service class. Extending baseadapter for listview.
Like i said, you need a ListAdapter which controls your changes and asynchronous stuff.
For example something like this:
// Get ListView object from xml
listView = (ListView) findViewById(R.id.list);
// Defined Array values to show in ListView
String[] values = new String[] { "Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View"
};
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
You only need your Service Routine which adds or changes the Array - The adapter will handle your background stuff.
If you use for example the Firebase Database there is a special FirebaseListAdapter which checks deleting, adding, changing the data and will update your list automatically.
For your specific problem with SQLite you should do something like this:
Cursor cursor = dbHelper.fetchAllCountries();
// The desired columns to be bound
String[] columns = new String[] {
CountriesDbAdapter.KEY_CODE,
CountriesDbAdapter.KEY_NAME,
CountriesDbAdapter.KEY_CONTINENT,
CountriesDbAdapter.KEY_REGION
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.country_info,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
You could use a BusEvent solution. When your service detect a change you post a new event with the chages. The activity which contains the ListView, will be listen this event and will update the adapter.
You could use a library like Otto or use a new aproach with RxAndroid and RxJava RxBus.
I think the best option for you is otto because integrate RxAndroid is too much for a simple communication.
A solution with Otto could be:
dependencies {
compile 'com.squareup:otto:1.3.8'
}
BusProvider.java
import com.squareup.otto.Bus;
import com.squareup.otto.ThreadEnforcer;
public final class BusProvider {
private static final Bus BUS = new Bus(ThreadEnforcer.ANY);
private BusProvider() {
// No instances.
}
public static Bus getInstance() {
return BUS;
}
}
ListDataEvent.java
public class ListDataEvent {
List<YourObject> data; ////set your data
}
YourActivity.java
public class YourActivity extends AppCompatActivity {
#Override
public void onResume() {
super.onResume();
BusProvider.getInstance().register(this);
}
#Override
public void onPause() {
super.onPause();
BusProvider.getInstance().unregister(this);
}
#Subscribe
public void onListDataEvent(ListDataEvent event) {
//fill your adapter with event.data and update the listView
}
}
Finally the service:
public class YourService extends IntentService {
#Override
protected void onHandleIntent(Intent workIntent) {
//Gets data and post the event
BusProvider.getInstance().post(new ListDataEvent(data));
}
}

How to add Listview as footer in listview in android?

I have Mainactivity which contain listview with some item and I want to add another listview in that listview as footer.How can I add this
Its not recommended to add a ListView as a footer of another ListView. You might consider making a list of objects containing both list and pass the list to your Adapter.
So if you merge two lists in a common format, you need to be tricky for the layout selection for each item in your list. Let me show you an example of a common class.
public class CommonClass {
// Set null values initially.
private ClassA mFirstListClass = null;
private ClassB mSecondListClass = null;
}
Now take an ArrayList of this object to pass it to your Adapter. In your bindView check if the item is a ClassA object or ClassB object (as you can easily determine them by checking which object is null) and then set proper action.
I think for these kinds of problems RecyclerView is better. Its very simple to implement and you can find the implementation document here.
// Create a List from String Array elements
final List<String> tests = new ArrayList<String>(Arrays.asList(test));
// Create an ArrayAdapter from List
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, tests);
// DataBind ListView with items from ArrayAdapter
lv.setAdapter(arrayAdapter);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Add new Items to List
tests.add("abc");
tests.add("def");
/*
notifyDataSetChanged ()
Notifies the attached observers that the underlying
data has been changed and any View reflecting the
data set should refresh itself.
*/
arrayAdapter.notifyDataSetChanged();
}
});
for more http://android--code.blogspot.in/2015/08/android-listview-add-items.html

How to update a custom listview in android

I have an application developed to get all the third party applications installed and to display them on a list view! this is been done by an extended baseAdapter. In this list I do an uninstallation of a selected application using this code :
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:" + Packname));
startActivity(intent);
Now what I want is to update the list view with the changed data so that the user can get updated application list. how can I achieve this. I found that notifyDatasetchanged method but it can only be used for simple listviews! what are the options that I have and please let me know of any tutorials to achieve my outcome!
thank you.
What do you mean only for simple listviews? How is yours different? You should be able to call notifyDataSetChanged on your custom adapter class after deleting one of your items. You can create a function to do it...
private ArrayList<Object> list;
public void deleteItem(int index){
list.remove(index);
notifyDataSetChanged();
}
you will have an adapter (something that extends BaseAdapter probably) that you set into the ListView using setAdapter(...). add a method to your adapter implementation class that sets the underlying objects that are backing the list. make sure to call notifyDataSetChanged() at the end. something like,
public class MyAdapter extends BaseAdapter<String> {
private List<String> strings;
...
void setModel(List<String> strings) {
this.strings = strings;
this.notifyDataSetChanged();
}
}
simply calling your adapter's setModel(...) will cause the ListView to update.

How to refresh Android listview?

How to refresh an Android ListView after adding/deleting dynamic data?
Call notifyDataSetChanged() on your Adapter object once you've modified the data in that adapter.
Some additional specifics on how/when to call notifyDataSetChanged() can be viewed in this Google I/O video.
Also you can use this:
myListView.invalidateViews();
Please ignore all the invalidate(), invalidateViews(), requestLayout(), ... answers to this question.
The right thing to do (and luckily also marked as right answer) is to call notifyDataSetChanged() on your Adapter.
Troubleshooting
If calling notifyDataSetChanged() doesn't work all the layout methods won't help either. Believe me the ListView was properly updated. If you fail to find the difference you need to check where the data in your adapter comes from.
If this is just a collection you're keeping in memory check that you actually deleted from or added the item(s) to the collection before calling the notifyDataSetChanged().
If you're working with a database or service backend you'll have to call the method to retrieve the information again (or manipulate the in memory data) before calling the notifyDataSetChanged().
The thing is this notifyDataSetChanged only works if the dataset has changed. So that is the place to look if you don't find changes coming through. Debug if needed.
ArrayAdapter vs BaseAdapter
I did find that working with an adapter that lets you manage the collection, like a BaseAdapter works better. Some adapters like the ArrayAdapter already manage their own collection making it harder to get to the proper collection for updates. It's really just an needless extra layer of difficulty in most cases.
UI Thread
It is true that this has to be called from the UI thread. Other answers have examples on how to achieve this. However this is only required if you're working on this information from outside the UI thread. That is from a service or a non UI thread. In simple cases you'll be updating your data from a button click or another activity/fragment. So still within the UI thread. No need to always pop that runOnUiTrhead in.
Quick Example Project
Can be found at https://github.com/hanscappelle/so-2250770.git. Just clone and open the project in Android Studio (gradle). This project has a MainAcitivity building a ListView with all random data. This list can be refreshed using the action menu.
The adapter implementation I created for this example ModelObject exposes the data collection
public class MyListAdapter extends BaseAdapter {
/**
* this is our own collection of data, can be anything we
* want it to be as long as we get the abstract methods
* implemented using this data and work on this data
* (see getter) you should be fine
*/
private List<ModelObject> mData;
/**
* our ctor for this adapter, we'll accept all the things
* we need here
*
* #param mData
*/
public MyListAdapter(final Context context, final List<ModelObject> mData) {
this.mData = mData;
this.mContext = context;
}
public List<ModelObject> getData() {
return mData;
}
// implement all abstract methods here
}
Code from the MainActivity
public class MainActivity extends Activity {
private MyListAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = (ListView) findViewById(R.id.list);
// create some dummy data here
List<ModelObject> objects = getRandomData();
// and put it into an adapter for the list
mAdapter = new MyListAdapter(this, objects);
list.setAdapter(mAdapter);
// mAdapter is available in the helper methods below and the
// data will be updated based on action menu interactions
// you could also keep the reference to the android ListView
// object instead and use the {#link ListView#getAdapter()}
// method instead. However you would have to cast that adapter
// to your own instance every time
}
/**
* helper to show what happens when all data is new
*/
private void reloadAllData(){
// get new modified random data
List<ModelObject> objects = getRandomData();
// update data in our adapter
mAdapter.getData().clear();
mAdapter.getData().addAll(objects);
// fire the event
mAdapter.notifyDataSetChanged();
}
/**
* helper to show how only changing properties of data
* elements also works
*/
private void scrambleChecked(){
Random random = new Random();
// update data in our adapter, iterate all objects and
// resetting the checked option
for( ModelObject mo : mAdapter.getData()) {
mo.setChecked(random.nextBoolean());
}
// fire the event
mAdapter.notifyDataSetChanged();
}
}
More Information
Another nice post about the power of listViews is found here: http://www.vogella.com/articles/AndroidListView/article.html
Call runnable whenever you want:
runOnUiThread(run);
OnCreate(), you set your runnable thread:
run = new Runnable() {
public void run() {
//reload content
arraylist.clear();
arraylist.addAll(db.readAll());
adapter.notifyDataSetChanged();
listview.invalidateViews();
listview.refreshDrawableState();
}
};
i got some problems with dynamic refresh of my listview.
Call notifyDataSetChanged() on your Adapter.
Some additional specifics on how/when to call notifyDataSetChanged() can be viewed in this Google I/O video.
notifyDataSetChanged() did not work properly in my case[ I called the notifyDataSetChanged from another class]. Just in the case i edited the ListView in the running Activity (Thread). That video thanks to Christopher gave the final hint.
In my second class i used
Runnable run = new Runnable(){
public void run(){
contactsActivity.update();
}
};
contactsActivity.runOnUiThread(run);
to acces the update() from my Activity. This update includes
myAdapter.notifyDataSetChanged();
to tell the Adapter to refresh the view.
Worked fine as far as I can say.
If you are using SimpleCursorAdapter try calling requery() on the Cursor object.
if you are not still satisfied with ListView Refreshment, you can look at this snippet,this is for loading the listView from DB, Actually what you have to do is simply reload the ListView,after you perform any CRUD Operation
Its not a best way to code, but it will refresh the ListView as you wish..
It works for Me....if u find better solution,please Share...
.......
......
do your CRUD Operations..
......
.....
DBAdapter.open();
DBAdapter.insert_into_SingleList();
// Bring that DB_results and add it to list as its contents....
ls2.setAdapter(new ArrayAdapter(DynTABSample.this,
android.R.layout.simple_list_item_1, DBAdapter.DB_ListView));
DBAdapter.close();
The solutions proposed by people in this post works or not mainly depending on the Android version of your device. For Example to use the AddAll method you have to put android:minSdkVersion="10" in your android device.
To solve this questions for all devices I have created my on own method in my adapter and use inside the add and remove method inherits from ArrayAdapter that update you data without problems.
My Code: Using my own data class RaceResult, you use your own data model.
ResultGpRowAdapter.java
public class ResultGpRowAdapter extends ArrayAdapter<RaceResult> {
Context context;
int resource;
List<RaceResult> data=null;
public ResultGpRowAdapter(Context context, int resource, List<RaceResult> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.data = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
........
}
//my own method to populate data
public void myAddAll(List<RaceResult> items) {
for (RaceResult item:items){
super.add(item);
}
}
ResultsGp.java
public class ResultsGp extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
...........
...........
ListView list = (ListView)findViewById(R.id.resultsGpList);
ResultGpRowAdapter adapter = new ResultGpRowAdapter(this, R.layout.activity_result_gp_row, new ArrayList<RaceResult>()); //Empty data
list.setAdapter(adapter);
....
....
....
//LOAD a ArrayList<RaceResult> with data
ArrayList<RaceResult> data = new ArrayList<RaceResult>();
data.add(new RaceResult(....));
data.add(new RaceResult(....));
.......
adapter.myAddAll(data); //Your list will be udpdated!!!
For me after changing information in sql database nothing could refresh list view( to be specific expandable list view) so if notifyDataSetChanged() doesn't help, you can try to clear your list first and add it again after that call notifyDataSetChanged(). For example
private List<List<SomeNewArray>> arrayList;
List<SomeNewArray> array1= getArrayList(...);
List<SomeNewArray> array2= getArrayList(...);
arrayList.clear();
arrayList.add(array1);
arrayList.add(array2);
notifyDataSetChanged();
Hope it makes sense for you.
If you want to maintain your scroll position when you refresh, and you can do this:
if (mEventListView.getAdapter() == null) {
EventLogAdapter eventLogAdapter = new EventLogAdapter(mContext, events);
mEventListView.setAdapter(eventLogAdapter);
} else {
((EventLogAdapter)mEventListView.getAdapter()).refill(events);
}
public void refill(List<EventLog> events) {
mEvents.clear();
mEvents.addAll(events);
notifyDataSetChanged();
}
For the detail information, please see Android ListView: Maintain your scroll position when you refresh.
Just use myArrayList.remove(position); inside a listener:
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> parent, android.view.View view, int position, long id) {
myArrayList.remove(position);
myArrayAdapter.notifyDataSetChanged();
}
});
You need to use a single object of that list whoose data you are inflating on ListView. If reference is change then notifyDataSetChanged() does't work .Whenever You are deleting elements from list view also delete them from the list you are using whether it is a ArrayList<> or Something else then Call
notifyDataSetChanged() on object of Your adapter class.
So here see how i managed it in my adapter see below
public class CountryCodeListAdapter extends BaseAdapter implements OnItemClickListener{
private Context context;
private ArrayList<CountryDataObject> dObj;
private ViewHolder holder;
private Typeface itemFont;
private int selectedPosition=-1;
private ArrayList<CountryDataObject> completeList;
public CountryCodeListAdapter(Context context, ArrayList<CountryDataObject> dObj) {
this.context = context;
this.dObj=dObj;
completeList=new ArrayList<CountryDataObject>();
completeList.addAll(dObj);
itemFont=Typeface.createFromAsset(context.getAssets(), "CaviarDreams.ttf");
}
#Override
public int getCount() {
return dObj.size();
}
#Override
public Object getItem(int position) {
return dObj.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if(view==null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.states_inflator_layout, null);
holder.textView = ((TextView)view.findViewById(R.id.stateNameInflator));
holder.checkImg=(ImageView)view.findViewById(R.id.checkBoxState);
view.setTag(holder);
}else{
holder = (ViewHolder) view.getTag();
}
holder.textView.setText(dObj.get(position).getCountryName());
holder.textView.setTypeface(itemFont);
if(position==selectedPosition)
{
holder.checkImg.setImageResource(R.drawable.check);
}
else
{
holder.checkImg.setImageResource(R.drawable.uncheck);
}
return view;
}
private class ViewHolder{
private TextView textView;
private ImageView checkImg;
}
public void getFilter(String name) {
dObj.clear();
if(!name.equals("")){
for (CountryDataObject item : completeList) {
if(item.getCountryName().toLowerCase().startsWith(name.toLowerCase(),0)){
dObj.add(item);
}
}
}
else {
dObj.addAll(completeList);
}
selectedPosition=-1;
notifyDataSetChanged();
notifyDataSetInvalidated();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Registration reg=(Registration)context;
selectedPosition=position;
reg.setSelectedCountryCode("+"+dObj.get(position).getCountryCode());
notifyDataSetChanged();
}
}
Consider you have passed a list to your adapter.
Use:
list.getAdapter().notifyDataSetChanged()
to update your list.
After deleting data from list view, you have to call refreshDrawableState().
Here is the example:
final DatabaseHelper db = new DatabaseHelper (ActivityName.this);
db.open();
db.deleteContact(arg3);
mListView.refreshDrawableState();
db.close();
and deleteContact method in DatabaseHelper class will be somewhat looks like
public boolean deleteContact(long rowId) {
return db.delete(TABLE_NAME, BaseColumns._ID + "=" + rowId, null) > 0;
}
I was not able to get notifyDataSetChanged() to work on updating my SimpleAdapter, so instead I tried first removing all views that were attached to the parent layout using removeAllViews(), then adding the ListView, and that worked, allowing me to update the UI:
LinearLayout results = (LinearLayout)findViewById(R.id.results);
ListView lv = new ListView(this);
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
SimpleAdapter adapter = new SimpleAdapter( this, list, R.layout.directory_row,
new String[] { "name", "dept" }, new int[] { R.id.name, R.id.dept } );
for (...) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", name);
map.put("dept", dept);
list.add(map);
}
lv.setAdapter(adapter);
results.removeAllViews();
results.addView(lv);
while using SimpleCursorAdapter can call changeCursor(newCursor) on the adapter.
I was the same when, in a fragment, I wanted to populate a ListView (in a single TextView) with the mac address of BLE devices scanned over some time.
What I did was this:
public class Fragment01 extends android.support.v4.app.Fragment implements ...
{
private ListView listView;
private ArrayAdapter<String> arrayAdapter_string;
...
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
...
this.listView= (ListView) super.getActivity().findViewById(R.id.fragment01_listView);
...
this.arrayAdapter_string= new ArrayAdapter<String>(super.getActivity(), R.layout.dispositivo_ble_item, R.id.fragment01_item_textView_titulo);
this.listView.setAdapter(this.arrayAdapter_string);
}
#Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord)
{
...
super.getActivity().runOnUiThread(new RefreshListView(device));
}
private class RefreshListView implements Runnable
{
private BluetoothDevice bluetoothDevice;
public RefreshListView(BluetoothDevice bluetoothDevice)
{
this.bluetoothDevice= bluetoothDevice;
}
#Override
public void run()
{
Fragment01.this.arrayAdapter_string.add(new String(bluetoothDevice.toString()));
Fragment01.this.arrayAdapter_string.notifyDataSetChanged();
}
}
Then the ListView began to dynamically populate with the mac address of the devices found.
I think it depends on what you mean by refresh. Do you mean that the GUI display should be refreshed, or do you mean that the child views should be refreshed such that you can programatically call getChildAt(int) and get the view corresponding to what is in the Adapter.
If you want the GUI display refreshed, then call notifyDataSetChanged() on the adapter. The GUI will be refreshed when next redrawn.
If you want to be able to call getChildAt(int) and get a view that reflects what is what is in the adapter, then call to layoutChildren(). This will cause the child view to be reconstructed from the adapter data.
I had an ArrayList which I wanted to display in a listview. ArrayList contained elements from mysql.
I overrided onRefresh method and in that method I used tablelayout.removeAllViews(); and then repeated the process for getting data again from the database.
But before that make sure to clear your ArrayList or whatever data structre or else new data will get appended to the old one..
If you want to update the UI listview from a service, then make the adapter static in your Main activity and do this:
#Override
public void onDestroy() {
if (MainActivity.isInFront == true) {
if (MainActivity.adapter != null) {
MainActivity.adapter.notifyDataSetChanged();
}
MainActivity.listView.setAdapter(MainActivity.adapter);
}
}
If you are going by android guide lines and you are using the ContentProviders to get data from Database and you are displaying it in the ListView using the CursorLoader and CursorAdapters ,then you all changes to the related data will automatically be reflected in the ListView.
Your getContext().getContentResolver().notifyChange(uri, null); on the cursor in the ContentProvider will be enough to reflect the changes .No need for the extra work around.
But when you are not using these all then you need to tell the adapter when the dataset is changing. Also you need to re-populate / reload your dataset (say list) and then you need to call notifyDataSetChanged() on the adapter.
notifyDataSetChanged()wont work if there is no the changes in the datset.
Here is the comment above the method in docs-
/**
* Notifies the attached observers that the underlying data has been changed
* and any View reflecting the data set should refresh itself.
*/
I was only able to get notifyDataSetChanged only by getting new adapter data, then resetting the adapter for the list view, then making the call like so:
expandableAdapter = baseFragmentParent.setupEXLVAdapter();
baseFragmentParent.setAdapter(expandableAdapter);
expandableAdapter.notifyDataSetChanged();
on other option is onWindowFocusChanged method, but sure its sensitive and needs some extra coding for whom is interested
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
// some controls needed
programList = usersDBHelper.readProgram(model.title!!)
notesAdapter = DailyAdapter(this, programList)
notesAdapter.notifyDataSetChanged()
listview_act_daily.adapter = notesAdapter
}
If I talked about my scenario here, non of above answers will not worked because I had activity that show list of db values along with a delete button and when a delete button is pressed, I wanted to delete that item from the list.
The cool thing was, I did not used recycler view but a simple list view and that list view initialized in the adapter class. So, calling the notifyDataSetChanged() will not do anything inside the adapter class and even in the activity class where adapter object is initialized because delete method was in the adapter class.
So, the solution was to remove the object from the adapter in the adapter class getView method(to only delete that specific object but if you want to delete all, call clear()).
To you to get some idea, what was my code look like,
public class WordAdapter extends ArrayAdapter<Word> {
Context context;
public WordAdapter(Activity context, ArrayList<Word> words) {}
//.......
#NonNull
#Override
public View getView(final int position, View convertView, ViewGroup group) {
//.......
ImageButton deleteBt = listItemView.findViewById(R.id.word_delete_bt);
deleteBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (vocabDb.deleteWord(currentWord.id)) {
//.....
} else{
//.....
}
remove(getItem(position)); // <---- here is the trick ---<
//clear() // if you want to clear everything
}
});
//....
Note: here remove() and getItem() methods are inherit from the Adapter class.
remove() - to remove the specific item that is clicked
getItem(position) - is to get the item(here, thats my Word object
that I have added to the list) from the clicked position.
This is how I set the adapter to the listview in the activity class,
ArrayList<Word> wordList = new ArrayList();
WordAdapter adapter = new WordAdapter(this, wordList);
ListView list_view = (ListView) findViewById(R.id.activity_view_words);
list_view.setAdapter(adapter);
After adding/deleting dynamic data in your "dataArray" do:
if you use an ArrayAdapter
adapter.notifyDataSetChanged();
if you use a customAdapter that extends ArrayAdapter
adapter.clear();
adapter.addAll(dataArray);
adapter.notifyDataSetChanged();
if you use a customAdapter that extends BaseAdapter
adapter.clear();
adapter.getData().addAll(dataArray);
adapter.getData().notifyDataSetChanged();
The easiest is to just make a new Adaper and drop the old one:
myListView.setAdapter(new MyListAdapter(...));

Categories

Resources