Splitting a string and putting it inside a listview - android

I asked a question before about splitting string but maybe it wasn't clear enough.
I made a simple activity which has an example to what my problem is.
I have a message and it's a long one coming from a server.
I need to split this message and put it inside a listview, I'll show you my code.
public class Page1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity6);
String message = "0---12,,,2013-02-12 08:04,,,this is a test,,,0---11,,,2013-02-12 08:05,,,and this is why it is damaged,,,0---10,,,2013-02-12 08:06,,,what comes from select data randomly";
String[] variables = message.split(",");
ListView listView1 = (ListView) findViewById(R.id.listView12);
String[] items = { variables.toString() };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
listView1.setAdapter(adapter);
}
}
Now let's say that the split is commas ", " so it will be
0---12 ------->ID1
2013-02-12 08:04 ------------>date1
this is a test ----------->subject1
0---11 ------->ID2
2013-02-12 -8:05 ------------>date2
and this is why it is damaged ----------->subject2
And so on, now what I can't do is that I want to put these strings in a loop and write them to a listview such that the subject1 should be in item1 and date1 should be in subitem1 like this
Subject1
Date1
------
Subject2
Date2
------
This is how the listview should look like
Can anyone help me with this please?

You would need to create a custom ArrayAdapter to populate a ListView from your objects the way you want.
The advantage of this technic is that you gain a Views recycle mechanism that will recycle the Views inside you ListView in order to spend less memory.
In Short you would have to:
1. Create an object that represents your data for a single row.
2. Create an ArrayList of those objects.
3. Create a layout that contains a ListView or add a ListView to you main layout using code.
4. Create a layout of a single row.
5. Create a ViewHolder that will represent the visual aspect of you data row from the stand point of Views.
6. Create a custom ArrayAdapter that will populate the rows according to you needs, in it you will override the getView method and use the position parameter you receive for the corrent row View to indicate the row index.
7. Finally assign this ArrayAdapter to your ListView in onCreate.
You can get an idea of how to implement this by reading this blog post I wrote:
Create a Custom ArrayAdapter

Please note that ArrayAdaper is designed for items containing only one single TextView. From the docs:
A concrete BaseAdapter that is backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView
Consider subclassing ArrayAdapter (docs) and override its getView method.

Related

How to divide gridview in sections in android?

My question is basic but I couldn't find any answer for my question. I have a layout which contains 2 textviews and a gridview. I added this layout into a listview.I want to generate multiple layouts. For example;
ListView------------------1stElement
----------textview1-----------------
----------gridview1-----------------
----------textview1-----------------
ListView------------------2ndElement
----------textview2-----------------
----------gridview2-----------------
----------textview2-----------------
ListView------------------3rdElement
----------textview3-----------------
----------gridview3-----------------
----------textview3-----------------
I tried it like that;
for(int i = 0; i<category.getChildren().size(); i++){
listView.setAdapter(new CategoryListAdapter(this, category.getChildren().get(i)));
}
But of course, it showed my last view only. setAdapter() doesn't suit to my code. I need something like adding views over and over.
Thanks for your helps.
You don't have to do this in for loop, Adapter Takes whole list Once Only, If u do it in a loop it will set the last list visible, So make list in For loop first and then add i to adapter only once.
for(int i=0;i<size;i++)
{
ArrayList<Object> myChldrenList = new ArrayList<Object>();
Object mychild = mycategory.getChildren().get(i)
myChildrenList.add(myChild);
}
listView.setAdapter(new CategoryListAdapter(this, myChildrenList));
u can use Ur Class type Instead of object class or simply Type Cast Object Class.

Update custom listview item attribute

I am using listview in my app.I am adding items to list with this line:
conversationsAdapter.add(user);
and this initializes list
conversationsAdapter=new ArrayAdapter<JsonObject>(this,0) {
#Override
public View getView(int c_position,View c_convertView,ViewGroup c_parent) {
if (c_convertView == null) {
c_convertView=getLayoutInflater().inflate(R.layout.random_bars,null);
}
JsonObject user=getItem(c_position);
String name=user.get("name").getAsString();
String image_url="http://domain.com/photos/profile/thumb/"+user.get("photo").getAsString();
TextView nameView=(TextView)c_convertView.findViewById(R.id.tweet);
nameView.setText(name);
ImageView imageView=(ImageView)c_convertView.findViewById(R.id.image);
Ion.with(imageView)
.placeholder(R.drawable.twitter)
.load(image_url);
return c_convertView;
}
};
ListView conversationsListView = (ListView)findViewById(R.id.conversationList);
conversationsListView.setAdapter(conversationsAdapter);
conversationsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
startChat(conversationsAdapter.getItem(position));
}
});
My list view is looking like this:
I want to update an item in the list.How can I do this ?
Example:We can write a method like: changeName when this method calls,method sets name "Tolgay Toklar" to "Tolgay Toklar Test" so I want to update custom listview item attributes.
I totally disagree with tyczj. You never want to externally modify an ArrayAdapter's list and yes it's possible to update just an individual item. Lets start with updating an individual item.
You can just invoke getItem() and directly modify the object and call notifyDataSetChanged(). Example:
JSONObject object = conversationAdapter.getItem(position);
object.put("name", data);
conversationAdapter.notifyDataSetChanged();
Why does this work? Because the adapter will feed you the same object reference used internally, allowing you to modify it and update the adapter. No problem. Of course, I'd recommend instead building your own custom adapter to perform this directly on the adapter's internal list. As an alternative, I highly recommend using the ArrayBaseAdapter instead. It already provides that ability for you while fixing some other major bugs with Android's ArrayAdapter.
So why is tyczj wrong about modifying the external list? Simple. There's no guarantee that your external list is the same as the adapters. Once you perform a filter on the ArrayAdapter, your external list and the adapters are no longer the same. You can get into a dangerous scenario where (for example) index 5 no longer represents position 5 in the adapter because you later added an item to the adapter. I suggest reading Problems with ArrayAdapter's Constructors for a little more insight.
Update: How External List Fails
Lets say you create a List of objects to pass into an ArrayAdapter. Eg:
List<Data> mList = new ArrayList<Data>();
//...Load list with data
ArrayAdapter<Data> adapter = new ArrayAdapter<Data>(context, resource, mList);
mListView.setAdapter(adapter);
So far so good. You have your external list, you have an adapter instantiated with it and assigned to listview. Now lets say at some later point, the adapter is filtered and cleared.
adapter.filter("test");
//...later cleared
adapter.filter("");
Now at this point mList is NOT the same as the adapter. So if the adapter is modified:
adapter.add(newDataObject);
You'll find that mList does not contain that new data object. Hence why external lists like this can be dangerous as the filter creates a NEW ArrayList instance. It won't continue to use your mList referenced one. You could even try adding items to mList at this point and it won't be reflected in the adapter.
If you change the data in your list you need to call notifyDatasetCanged on the adapter to notify the list that the underlying data has changed needs to be updated and.
Example
List<MyData> data = new ArrayList<MyData>();
private void changeUserName(String name){
//find the one you need to change from the list here
.
.
.
data.set(myUpdatedData);
notifyDatasetChanged()
}

Android/java sqlite data to list

Im following a tutorial and i have created a database class and a activity class. Here is my activity class:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
datasource = new CommentsDataSource(this);
datasource.open();
List<Comment> values = datasource.getAllComments();
// Use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
My db is a bit different but most of the stuff is the same as in tutorial. Comment is just a setter/getter class.
Now the problem is that in my list i want to display comment name but i get "com.example.blabla.Comment#40dca9d0". I think it is because i am passing the whole comment class to the adapter. How would be the right way to pass the name?
Here is the link to tutorial, i must be missing something because it seems to work there but i dont know what exactly: http://www.vogella.com/articles/AndroidSQLite/article.html#sqliteoverview_sqliteopenhelper
// Will be used by the ArrayAdapter in the ListView
#Override
public String toString() {
return comment;
}
Did you make sure you added this to your Comment class?
In java the default implementation of toString() is Class#Hashcode which is what currently yours is showing, hence you need to override the default implementation by returning the comment.
You do not see toString() being called because it says in DOCS(parag2)
However the TextView is referenced, it will be filled with the
toString() of each object in the array. You can add lists or arrays of
custom objects. Override the toString() method of your objects to
determine what text will be displayed for the item in the list.

Strange behavior with ArrayAdapters in Android

I've been playing around with ArrayAdapters and I've reached a point where I'm getting different results from two almost identical ArrayLists + ArrayAdapter combinations.
The first one:
An ArrayList of 'Restaurant' objects, an ArrayAdapter that uses this ArrayList and a ListView that binds this ArrayAdapter.
private ArrayList<Restaurant> model = new ArrayList<Restaurant>();
private ArrayAdapter<Restaurant> restaurantAdapter = null;
...
public void onCreate(Bundle savedInstanceState){
...
restaurantAdapter = ArrayAdapter<Restaurant>(this, android.R.layout.simple_list_item_1, model);
...
listView.setAdapter(restaurantAdapter);
...
}
The second one:
An ArrayList of String objects, an ArrayAdapter that uses this ArrayList and a AutoCompleteTextView that binds this ArrayAdatper.
private ArrayList<String> prevAddressList = new ArrayList<String>();
private ArrayAdapter<String> addListAdapter = null;
...
public void onCreate(Bundle savedInstanceState){
...
addListAdapter = ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, prevAdddressList);
...
autoCompleteField.setAdapter(addListAdapter);
...
}
I have a save button, on click, I'm creating a restaurant object with a name and an address and adding it to the first adapter, additionally, I want to create a list of previously used address so they are "auto completed" next time they are typing it, so I'm taking the text, and adding it to the second adapter.
...onSave = new View.OnClickListener(){
...
restaurantAdapter.add(r); //r is a Restaurant object.
addListAdapter.add(autoCompleteField.getText().toString());
...
}
Now, everything is working properly. I get the Restaurants displayed in a ListView. The AutoComplete is working as expected.... but I noticed something when I was checking the values while debugging:
The actual ArrayLists, model (Restaurant) is getting updated after adding an object to the adapter , but prevAddressList (String) is not.
Unless, I set the AutoCompleteTextField empty.... then, the prevAddressList gets updated after adding something to the second adapter.
Already tried using notifyDataSetChanged(), but it makes no difference (and it is set to true on every adapter by default anyway).
Other behavior that differs between the two adapters is that in the first one (Restaurant), values are going to the mObjects field, while in the second one (String) they are going to mOriginalValues instead.
I'm completely stomped. The only difference between those two adapters is that one is type "Restaurant" and the other is type "String".
Any ideas? Maybe I'm missing something very obvious? Let me know if you need the full code.
thanks
Instead of adding it to the adapter, try adding the object to your list and then calling notifyDataSetChanged on your adapter. The adapter should pick up your changes and your list of course will have the object you just added.
For anyone coming here from google:
Unable to modify ArrayAdapter in ListView: UnsupportedOperationException
This might explain the behavior, although I have to test it myself.

How To Set the Text of an item in ListView

I have a list of ListItems's in my listview. The ListItem has a name instance variable. I am trying to get the text of each of the items just to be the name.
How can I do this?
public class List extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<ListItem>(this, R.layout.list_item, Previousclass.LinkedList-from-previous-class));
Right now it is just displaying the memory location of each item i.e. ListItem#47234c10
You have to extend ArrayAdapter to implement getView(). The ArrayAdapter implementation is returning the toString() value of your ListItem object.
Or alternatively stringify your data before adding it to the adapter.
What is Previousclass.LinkedList-from-previous-class ? Is it a list of your items?
If yes,
Your list of items should be a list of names of items. Your resulting screen should have listview in it and the adapter you created should be used this way
result.setListAdapter(Youradapter)
I am just giving you sample based on what code you have posted. If you need details, please elaborate your code.
result.setListAdapter(new ArrayAdapter<ListItem>(this, R.layout.list_item, Previousclass.LinkedList-from-previous-class))

Categories

Resources