Adapt data to ListView - android

In one of my activity I have EditText, Submit Button and a ListView. The data of ListView are retrived from database. To retrive data from database and adapt to ListView I used the following code.
private void loadList() {
mylist = new ArrayList<HashMap<String, Object>>();
mylist.clear();
List<Data> catDesc = dbhelper.getCatMasterDesc(id);
ArrayAdapter<Data> adapter = new SimpleAdapter(getApplicationContext(), R.layout.list, catDesc);
lv1 = (ListView) findViewById(R.id.masListView1);
lv1.setAdapter(adapter);
}
And i call this method every time whenever I update the database to show updated listview.
String str = category.getText().toString();
yes.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
dbhelper.UpdateMasterDesc(str);
loadList(); // see here.
}
});
This is the way I am updating my ListView. I think this is not a good way. If yes means please suggest me how can I update my ListView Whenever I update the database.
Thank You.

notifyDataSetchanged() is the answer as proposed by Raghunandan.
But before calling it, you need to update your object data which has been included in your list of catDesc.
Judging from your code I believe what
dbhelper.UpdateMasterDesc(str);
does is adding a new category? If yes, do a
catDesc.add(new Data(whatever you need to declare it with str))
before calling notifyDataSetChanged().

Related

notifyDatasetChanged() not working on the adapter

i've created a custom list with four textviews...the data in this list is saved through a dialog which has a ok button. when i add the data, it gets saved in the list(works fine till now). when i add the next element, all the rows gets same value as the last one...the notifyDatasetChanged() is also not working...am i wrong somewhere?...this is my code...
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String val = editquantity.getText().toString();
valq1 = Integer.parseInt(val);
ListView l;
l = (ListView) v.findViewById(R.id.order_listview);
myAdapter adapter = new myAdapter(getActivity(), row);
l.setAdapter(adapter);
row.add("");
adapter.notifyDataSetChanged();
builder.dismiss();
}
});
builder.setView(dialog);
builder.show();
You created new adapter everytime you click ok. Put your adapter code outside the onclick method:
ListView l = (ListView) v.findViewById(R.id.order_listview);
myAdapter adapter = new myAdapter(getActivity(), row);
l.setAdapter(adapter);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String val = editquantity.getText().toString();
valq1 = Integer.parseInt(val);
row.add(""); //add new item to the list
adapter.notifyDataSetChanged(); //notify adapter
builder.dismiss();
}
});
builder.setView(dialog);
builder.show();
You need to use addAll() method for adding new values remaining old values are same in arraylist.
row.addAll("test");
Why are you adding row as blank.
Secondly you have set row in adapter without defining it.
Please provide more details to the question as i cannot understand where row has been declared.
Coming to the similar value problem.
You need to update row array because it has been set on adapter.
There are three things you need to change
1. Declare your ListView object outside of the onCreate()
2. Declare your adapter object outside of the onCreate()
Now this initialization of this below line needs to be initialized only once in onCreate(). You need not to initialize it again and again when you add new item.So below line write in your onCreate().
myAdapter adapter = new myAdapter(getActivity(), row);
When you add new item you only need to add that item in your arraylist named row onClick of ok button and then call adapter.notifyDataSetChanged(); it will work fine.

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));

android ArrayAdapter items update

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);

Populate ListView with Dynamic Array

I have a EditText box so a user can input names and then click the Add button and the name saves to the array playerList and clears the box so another name can be added.
I also have a ListView on the same Activity which will then be populated by the names in the Array playerList. The problem is that the ListView dosen't seem to be populated.
So I tried with a defualt set String teststring which you can see below and that populates the ListView fine. My question is how come it isn't working with the Array playerList maybe its not saving to the Array correctly?
Update just need adapter.notifyDataSetChanged(); adding to refresh the ListView Credit to #Lalit Poptani and #Jave
ArrayList<String> playerList = new ArrayList<String>();
ListView listview;
protected String[] teststring = {"Name 1", "Name 2"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addremove);
ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, teststring);
ListView employeeList = (ListView) findViewById(R.id.namelistview);
employeeList.setAdapter(adapter);
Button confirm = (Button) findViewById(R.id.add);
confirm.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText playername = (EditText) findViewById(R.id.userinput);
String name = playername.getText().toString();
playerList.add(name);
playername.setText("");
}});
To refresh the ListView after you add new data to it you have to call adapter.notifyDataSetChanged(). This is refresh your ListView will new data.
But in your case you are populating your ListView with String[] so it won't work dynamically you will have to give the size of the String[]. So, I will suggest you to populate your ListView with ArrayList itself for adding the content dynamically.
ListAdapter adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1,playerList);
You should call adapter.notifyDataSetChanged() after adding new items to make it update with the new data.
Notifies the attached observers that the underlying data has been
changed and any View reflecting the data set should refresh itself.

Categories

Resources