ListView issue when displaying strings - android

can any one help me to display set of results in my app in a list view. i got the following
codeList<Result> results = response.results;
for (Result result : results) {
//Toast.makeText(this, result.fromUser, Toast.LENGTH_SHORT).show();
Toast.makeText(this, result.text, Toast.LENGTH_LONG).show();
//String[] ch=getResources().getString(result.text);//result.text;
//adapter = new ArrayAdapter<String>(this,R.layout.mainlist,result.text);
//SimpleArrayAdapter adapter = new SimpleArrayAdapter(this, result.text);
setListAdapter(adapter);
}
i want to show result.text in a listview for each value. i tried everything commented in the code, but not getting. please help me.

with this short snippet of code it is hard to know what the problem might be,
possibly this will help
http://developer.android.com/resources/tutorials/views/hello-listview.html
after setListAdapter(adapter); try adding adapter.notifyDataSetChanged() or alternatively try adapter.setNotifyOnChange(true) just after initializing the adapter this might solve your issue if it is what i think it is. else post more of your code

You can use **ExpandableListView**
Refer : http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/ExpandableList3.html

1) extend ArrayAdapter with your custom class:
class MyAdapter extends ArrayAdapter<Result>
2) create xml for layout of each row, eg. row.xml and set it in constructor of your adapter:
MyAdapter(Activity context, int resourceId, ArrayList<Result>
mResults) {
super(context, R.layout.row, mResults);
}
3) in getView method of your adapter fill apropriate field with your result.text
4) set list adapter to your custom adapter
MyAdapter adapter = new MyAdapter(this, 0, mResults);
setListAdapter(adapter);

Related

Custom adapter size 0 after notifyDataSetChanged()

I have a ListView, an ArrayList and an MaterielAdapter that extends ArrayAdapter. My problem is that calling notifyDataSetChanged() won't update my ListView... I spent 3 hours trying all similar issues on SO but none was efficient for me.
private ListView lvMateriels;
private ArrayList<Materiel> materiels = new ArrayList<>();
...
lvMateriels = new ListView(this);
lvMateriels.setAdapter(new MaterielAdapter(this, R.layout.object_line,materiels));
...
materiels.add(new Materiel());
((MaterielAdapter)lvMateriels.getAdapter()).notifyDataSetChanged();
My collection has all the objects but listview never refreshes, nor the adapter...
You're probably not even adding the ListView to the activity view. Instead of doing new Listview(this), I'd recommend you to define a listview in your layout xml
Something like:
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Then in your activity:
lvObjects = (ListView) findViewById(R.id.listview);
Found out solution
My problem was that I was setting my ArrayList another ArrayList
materiels = getMateriels() // getMateriels() returns an ArrayList<Materiel>
It seems that setting a new object to the list doesn't work, what I finally did is the following :
materiels.clear();
materiels.addAll(getMateriels());
And by the way for those who need to have a header into their ListView, you have to do like :
((YourAdapter)((HeaderViewListAdapter)yourListView.getAdapter()).getWrappedAdapter()).notifyDataSetChanged();
Stock your adapter, and your adapter will be your list too.
MaterialAdapter adapter = new MaterialAdapter(this,
R.layout.object_line);
lvObjects = new ListView(this);
lvObjects.setAdapter(adapter);
...
adapter.add(new Object());
adapter.notifyDataSetChanged();
Currenlty your adapter, do not know that he need to use the list that you pass in argument. But you extends ArrayAdapter, that means that your adapter is a 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));

Constructor cannot be resolved

I am trying to create an array adapter to populate my list view.
Below is the code I have however the Array Adapter gets the error "Cannot resolve constructor".
Can anybody please help me with why this might be happening?
Thanks.
private void populateListView(){
//Create list of items'
String[] myItems = {"Blue", "red", "green", "purple"};
//Build adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.deal_items, myItems);
//Configure the list view
ListView list = (ListView) findViewById(R.id.listViewMain);
list.setAdapter(adapter);
}
The first parameter to the ArrayAdapter constructor needs to be a Context. You appear to have implemented this method in a Fragment, which is not a Context. If so, then replace this in the ArrayAdapter constructor with getActivity().

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

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

Categories

Resources