android ArrayAdapter items update - android

I have ArrayAdapter with this items structure:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout ... >
<TextView
android:id="#+id/itemTextView"
... />
</RelativeLayout>
And add this adapter so:
mAdapter = new ArrayAdapter<String>(this, R.layout.item,
R.id.itemTextView, itemsText);
All is fine but I want to update text in adapter's items. I found a solution
mAdapter.notifyDataSetChanged();
but do not understand how to use it. Help please.
upd
My code:
String[] itemsText = {"123", "345", "567"};
ArrayAdapter<String> mAdapter;
onCreate
mAdapter = new ArrayAdapter<String>(this, R.layout.roomitem,
R.id.itemTextView, itemsText);
setListAdapter(mAdapter);
itemsText = {"789", "910", "1011"};
onClick
mAdapter.notifyDataSetChanged();
//it's dont work

I think something like this
public void updatedData(List itemsArrayList) {
mAdapter.clear();
if (itemsArrayList != null){
for (Object object : itemsArrayList) {
mAdapter.insert(object, mAdapter.getCount());
}
}
mAdapter.notifyDataSetChanged();
}

Your problem is a typical Java error with pointers.
In a first step you are creating an array and passing this array to the adapter.
In the second step you are creating a new array (so new pointer is created) with new information but the adapter is still pointing to the original array.
// init itemsText var and pass to the adapter
String[] itemsText = {"123", "345", "567"};
mAdapter = new ArrayAdapter<String>(..., itemsText);
//ERROR HERE: itemsText variable will point to a new array instance
itemsText = {"789", "910", "1011"};
So, you can do two things, one, update the array contents instead of creating a new one:
//This will work for your example
items[0]="123";
items[1]="345";
items[2]="567";
... or what I would do, use a List, something like:
List<String> items= new ArrayList<String>(3);
boundedDevices.add("123");
boundedDevices.add("456");
boundedDevices.add("789");
And in the update:
boundedDevices.set("789");
boundedDevices.set("910");
boundedDevices.set("1011");
To add more information, in a real application normally you update the contents of the list adapter with information from a service or content provider, so normally to update the items you would do something like:
//clear the actual results
items.clear()
//add the results coming from a service
items.addAll(serviceResults);
With this you will clear the old results and load the new ones (think that the new results should have a different number of items).
And off course after update the data the call to notifyDataSetChanged();
If you have any doubt don't hesitate to comment.

Assuming itemTexts as String array or String ArrayList,where you are adding new items into itemsTextat that time after that you can call
mAdapter.notifyDataSetChanged();
If you did not get answer then please put some code.

I did something like this. And it works correctly.
Add method to the Adapter class:
public void updateList(ArrayList<ITEM> itemList){
this.itemList.clear();
this.adapterList = new ArrayList<ITEM>();
this.adapterList .addAll(itemList);
notifyDataSetChanged();
}
Call the method in the class you use the adapter:
itemList.add(item);
adapter.updateList(itemList);

Related

ArrayAdapter and ListView never updating

I'm attempting to get method to handle updates to the ListView when SetWeatherData is called. Nothing ever shows up in my listview below. Any ideas? _rootView points to the right root and ListView comes back not null. m_weatherdata has a couple string elements in it.
Note the initial set of data does not show up either. Just blank.
I'm thinking it should be easier to setup a generic method to update a ListView when the data changes using straight up code.
private ArrayList<String> m_weatherdata;
private void SetWeatherData ( ArrayList<String> _weather)
{
m_weatherdata = _weather;
UpdateWeatherUI();
return;
}
ArrayAdapter<String> m_adapter = null;
private void UpdateWeatherUI()
{
if ( m_adapter == null ) {
m_adapter = new ArrayAdapter<String>(
this.getContext(),
R.layout.list_item_forecast,
R.id.list_item_forecast_textview,
m_weatherdata);
View _rootview = this.getLayoutInflater(null).inflate(R.layout.fragment_main, null, false);
ListView _listview = (ListView) _rootview.findViewById(R.id.listview_forecast);
_listview.setAdapter(m_adapter);
}
else
{
m_adapter.notifyDataSetChanged();
}
}
You are assigning a new ArrayList to your dataset.
m_weatherdata = _weather;
Instead add items to the dataset. Like this
m_weatherdata.addAll(_weather);
private void SetWeatherData ( ArrayList<String> _weather)
{
m_weatherdata.addAll(_weather);//change here
UpdateWeatherUI();
return;
}
When you set an adapter there is an observer attached to the
underlying data. So notifyDatasetChanged() only works if you only
modify the data in it.
If you want to clear all data from your dataset before adding new items to it, use the clear() method of ArrayList
private void SetWeatherData ( ArrayList<String> _weather)
{
m_weatherdata.clear();//change here
m_weatherdata.addAll(_weather);//change here
UpdateWeatherUI();
return;
}
m_weatherdata = _weather; // updates the local variable with new set of data. but adapter doesn't know about the changes made as you have created the instance of the adapter with array list by the following line of code.
m_adapter = new ArrayAdapter<String>(this.getContext(), R.layout.list_item_forecast,R.id.list_item_forecast_textview,m_weatherdata);
In you want to updated the data either call
m_adapter.addAll(newsetofstringtobeadded);
or
Create new adapter
This will update your list.

Comments Listview in Android

I have an Activity which contains different items, one of those item is ListView.
I created a custom list adapter and sending to it a json array.
The data for the list arrives from the server.
The list purpose is to make comments list. I allowed the user to insert
a comment and then I show it in the ListView.
When I have some items in the list it works, and the items are shown.
The problem is when listview is empty and the user post a comment.
I see that that data is changed but I don't see the item, means the list is not refreshed..
So I tried to add to the listview an empty view but it doesn't work.
Here is an updated code: (UPDATE)
if (!s.isEmpty() && !s.equals("{}")) {
try {
if (commentsListAdapter == null) {
commentsList.setEmptyView(findViewById(R.id.dummy));
commentsListAdapter = new CommentsListAdapter(PostView.this);
}
JSONObject resObj = new JSONObject(s);
list.add(resObj);
commentsListAdapter.setDataSet(list);
cmntTxt.setText("");
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
commentCounter.setText(Integer.toString(list.size()));
} catch (JSONException e) {
e.printStackTrace();
}
}
And inside the Adapter I have this function:
public void setDataSet(List<JSONObject> list){
commentsList = list;
notifyDataSetChanged();
}
But the problem is not fixed..
I notice the code list.add(resObj) appears after new CommentsListAdapter when the list is empty and appears before new CommentsListAdapter when the list is NOT empty.
I suspect the Adapter CommentsListAdapter is not using the object list for the data storage. In that case, you need to make a public method in the adapter to make updates. Another words, the adapter is using another object for data storage.
It may help to post the code for CommentsListAdapter also. But I hope I am correct about my statements.
I hope that is clear...
Please change the following code:
public void setDataSet(List<JSONObject> list){
commentsList = list;
notifyDataSetChanged();
}
to :
private List<JSONObject> commentsList = new ArrayList<>();
public void setDataSet(List<JSONObject> list){
commentsList.clear();
commentsList.addAll(list);
notifyDataSetChanged();
}
And use commentsList for all other methods in your adapter. This is a better way for notifyDataSetChanged() to work.
Hope it helps! :)
if you are adding your comment from the outside i.e from activity and not from adapter than whenever you set the adapter do this.
youradapterobject.notifyDataSetChanged();
and dont do commentsListAdapter == null than setemptyview
it automatically sets the emptyview if its null
correct usage
list.setEmptyView(findViewById(R.id.erromsg));

Listview adding to the same line

I have an android app that lists connected clients in a listview, but whenever someone connects, it just adds them to the same line, this is the code I use to add connected client. I am new to listview, and not sure how to do this properly, I looked at the android docs but hard to say what needs to be used. If anyone can help me out that would be great.
remoteip += socket.getInetAddress();
ArrayList<String> addclientlist = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainserverActivity.this,
android.R.layout.simple_list_item_1, android.R.id.text1, addclientlist);
addclientlist.add(remoteip);
adapter.notifyDataSetChanged();
listview.setAdapter(adapter)
I think you need to use this constructor
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainserverActivity.this, android.R.layout.simple_list_item_1, addclientlist);
Also no need to set adapter always just set it once and each time you have to add new item to adapter you can use either of these as in java Array objects are pass by reference, and then call notifydatasetchanged
adapter.add(remoteip);
//or addclientlist.add(remoteip);
adapter.notifyDataSetChanged(); // Dont forget this
You are updating the adapter initialization list, which is futile.
Instead - update the actual adapter:
adapter = new ArrayAdapter<String>(MainserverActivity.this,
android.R.layout.simple_list_item_1, android.R.id.text1, addclientlist);
listview.setAdapter(adapter)
...........
adapter.add(remoteip); // <----- instead of addclientlist.add()
adapter.notifyDataSetChanged();

Android null pointer exception on ArrayList for ListView

I have a listview that shows the contents of an arraylist. I'm using a simple adaptor to make this possible like so.
public static ArrayList<String> homeScreenContacts = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.home_screen_contacts_view, NewContact.homeScreenContacts);
The second line is giving me a null pointer exception. I thought about it and I decided it was because the arrayList is empty. So I added the following line between the arraylist declaration and the arrayadaptor declaration...
NewContact.homeScreenContacts.add("A Contact");
This solved the problem and my code worked fine but Now the list view shows "A Contact" and I dont want it to. Is there anyway to get rid of the null pointer exception problem but still have the arraylist empty? Because I want to populate it with user made contacts, not hard-coded, random strings. Thank you.
EDIT: Sorry, The arraylist is located in another class called NewContact, also, I am very beginner Android Programmer I just started.
Simple solution just don't initialize the ListView if there is no element in the ArrayList or the ArrayList is null.
if(NewContact.homeScreenContacts != null && NewContact.homeScreenContacts.size() > 0){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.home_screen_contacts_view, NewContact.homeScreenContacts);
listView.setAdapter(adapter);
}
Also you need to remember that if you you haven't initialize Adapter then dont initialize the ListView and before any operation on list view you should check is it null or not.
As you have said that you want to populate when user add some contact in the application then on add event only you need to populate or update the ListAdapter.
Hope this solution will resolve your problem.
Try this code
public class YourActivity extends Activity
{
private ListView lv;
public void onCreate(Bundle saveInstanceState) {
setContentView(R.layout.your_layout);
lv = (ListView) findViewById(R.id.your_list_view_id);
// Instanciating an array list (you don't need to do this, you already have yours)
ArrayList<String> your_array_list = new ArrayList<String>();
your_array_list.add("foo");
your_array_list.add("bar");
// This is the array adapter, it takes the context of the activity as a first // parameter, the type of list view as a second parameter and your array as a third parameter
ArrayAdapter<String> arrayAdapter =
new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, your_array_list);
lv.setAdapter(arrayAdapter);
}
}
Works fine for me:
if(arrayList.isEmpty())
{
listView.setAdapter(null);
}
else
{
listAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(listAdapter);
}

How do you add array to listview

I have an array of apps(PInfo) and I am wondering how do I add that array to a listview?
ArrayList<PInfo> info = appsGetter.listPackages();
int number = 0;
PInfo appInArray;
while(number < info.size()){
appInArray = info.get(number);
}
This is what I have at the moment, the listPackages() is a method that is getting the names of the apps from the device.
At the moment I am trying to get the information out of the array one by one and add it to the listview like that. Is that how I should do it our should I add the array straight to the listview? And how do you do that?
You can use an ArrayAdapter and initialize it like this:
ArrayAdapter<PInfo> adapter = new ArrayAdapter(context,
android.R.layout.simple_list_item_multiple_choice,
info);
Then you can you use ListView.setAdapter(adapter).
I'm not sure if this is what you're asking though. So please clarify further if this is not what you're asking
Try using an Adapter. For example (using just the String value of an object) you could do the following:
ListView listView = (ListView)findViewById( R.id.myListView );
final ArrayList<String> listItems = new ArrayList<String>();
final ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, listItems );
listView.setAdapter( adapter );
Just a quick example, but I hope it gives you a starting place. Just make sure if you add values to your data source later (in this case the ArrayList) to call the adapter's "notifyDataSetChanged()" method so that it can be properly reflected in whatever has been bound to the adapter (in this case the ListView).
You need to use an ArrayAdapter. Just search for a ListView and ArrayAdapter sample online. It's quite simple once you see it done.

Categories

Resources