Create list view with custom set of data in android? - android

I am trying to create ListView with custom data set as follows:
String superType = "random1";
String superTypea = "random12";
String superType12 = "random2";
String superType_amount = "child1";
String childtype_calulated = "2323";
String superType_amount = "child2";
String childtype_calulated = "23223";
String superType_amount = "child2";
String childtype_calulated = "amount3";
Now I want to create ListView with this set of data how to do that?
Here is the list structure...
row1=superType |superType_amount |childtype_calulated
row2=superTypea |superType_amount |childtype_calulated
row3=superType12|superType_amount |childtype_calulated
Is there any solution of this?

It is absolutely possible to do this. First, I would recommend putting your data into a collection. It would be preferable to put them into an object and then a collection of those objects. From there you can add a ListView to your main layout, define a custom layout for your list items, and populate your ListView using an ArrayAdapter.
Here is a really good example of how you can do this well. It includes examples of loading data from an external source, which you don't need.
However, if you're getting into development now I would suggest you look into RecyclerView as well. RecyclerView is new and included in the AppCompat v7 library for use on pre-Lollipop Android. A RecyclerView will be a little more complicated to implement for a simple list but is significantly more scalable and efficient. I believe it is Google's intention to replace ListView with RecyclerView entirely in the future.
Here is a pretty simple introduction to making a list with RecyclerView.
EDIT
Using an ArrayAdapter with a ListView. First you need to create a model to store your data, some kind of class that you can put into a collection, for example:
public class Item {
public String title;
public String sub1;
public String sub2;
public void Item(String t, String s1, String s2) {
title = t;
sub1 = s1;
sub2 = s2;
}
}
Then you need to define the layout for the item in your list:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/sub1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/sub2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Then in you need to make your custom ArrayAdapter by extending the ArrayAdapter class:
public class ItemAdapter extends ArrayAdapter<Item> {
public ItemAdapter(Context context, ArrayList<Item> items) {
super(context, 0, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Item item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_layout, parent, false);
}
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView sub1 = (TextView) convertView.findViewById(R.id.sub1);
TextView sub2 = (TextView) convertView.findViewById(R.id.sub2);
title.setText(item.title);
sub1.setText(item.sub1);
sub2.setText(item.sub2);
return convertView;
}
}
Then all you need to do is create an instance of the adapter in your main class and attach your collection to it:
ArrayList<Item> data = new ArrayList<Item>();
ItemAdapter adapter = new ItemAdapter(this, data);
ListView listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(adapter);
This should populate your ListView with all the items that you need in your list. I haven't run any of this code so there might be one or two small bugs for you to fix.

Related

Making faster ListView with images using multi-threading (Android API 10)

I have searched for answers but none seemed to help in my case.
App min sdk - API 10
Problem - slow ListView with images.
Reasons - data loading is on the UI thread (without images everything works smoothly) and probbavly the way I get the image resource id.
I have a ListView with two TextViews and an ImageView. I populate the ListView texts from an inserted database with SQLiteAssetHelper.
The table example:
specie_table
_id | LITHUANIAN | LATIN
0 | Paprastasis varnėnas| Sturnus vulgaris
1 | Juodasis strazdas | Turdus merula
Image loading
I have PNG images saved in the drawable folder.
I get the image resource id from the data in the database:
in specie_table.db "Regulus regulus" -> getImageName(name) returns "regulus_regulus" -> getResId(name, class) returns the drawable id -> setImage(ImageView, name) sets the resource for the ImageView
Should I make a different approach?
List_item.xml
<ImageView
android:id="#+id/icon"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="6dip"
android:layout_marginLeft="6dip"
android:layout_marginRight="10dip"
android:src="#drawable/ic_bird_grey"
/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="100dp"
android:orientation="vertical"
android:layout_toRightOf="#id/icon"
android:paddingTop="15dp">
<TextView
android:id="#+id/firstLine"
android:layout_width="match_parent"
android:layout_height="35sp"
android:text="Lithuanian title"
android:textSize="20sp"
/>
<TextView
android:id="#+id/secondLine"
android:layout_width="match_parent"
android:layout_height="24dp"
android:text="Latin title"
android:textSize="12sp" />
</LinearLayout>
SpecieCursorAdapter.java
public class SpecieCursorAdapter extends CursorAdapter {
SpecieCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
SpecieHolder holder = null;
holder = new SpecieHolder();
holder.imgIcon = (ImageView) view.findViewById(R.id.icon);
holder.txtTitle1 = (TextView) view.findViewById(R.id.firstLine);
holder.txtTitle2 = (TextView) view.findViewById(R.id.secondLine);
String nameLT = cursor.getString(cursor.getColumnIndex(SpecieTable.LIT_COL));
String nameLOT = cursor.getString(cursor.getColumnIndex(SpecieTable.LAT_COL));
holder.txtTitle1.setText(nameLT);
holder.txtTitle2.setText(nameLOT);
setImage(holder.imgIcon, nameLOT); //this makes everything laggy but i dont know how to make it as seperate thread.
}
static class SpecieHolder
{
ImageView imgIcon;
TextView txtTitle1;
TextView txtTitle2;
}
public void setImage(ImageView mainImage, String resource){ //these methods are for getting the image resource id from String (latin name).
int id = getResId(getImageName(resource), R.drawable.class);
if(id != -1)
mainImage.setImageResource(id);
else
mainImage.setImageResource(R.drawable.ic_bird_grey);
}
public int getResId(String resourceName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resourceName);
return idField.getInt(idField);
} catch (Exception e) {
return -1;
}
}
public String getImageName(String resource){
String string = resource.toLowerCase();
string = string.replace(' ', '_');
string = string.replace(".", "");
return string;
}}
ListActivity.java
public class ListActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "bird info";
ListView listView;
ListActivity context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView)findViewById(R.id.listView);
Intent intent = getIntent();
Habitats habitat = Habitats.detachFrom(intent); //this is an enum type sent as String, converted back to enum.
Cursor cursor;
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
databaseAccess.open();
cursor = databaseAccess.getCursorByHabitat(habitat);
databaseAccess.close();
SpecieCursorAdapter adapter = new SpecieCursorAdapter(this, cursor);
listView.setAdapter(adapter);// how to seperate the image loading?
}
Examples would help very mutch! I will insert any needed extra code.
Try using Volley HTTP library for faster data transferring and image loading.
Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster.
Follow these links
https://developer.android.com/training/volley/index.html
An example listview with image loading using Volley library
You can either use an existing lib as proposed by #abhilash or implement it on your own
In android displaying an item with an image in a listview works like this (example):
The listview needs to display item that is at position #35
The listview asks its adapter for a filled listviewitemview for the item that is at position #35
listviewitemview is either recycled from an old listviewitemview that is not visible any more or a new listviewitemview is created
each listviewitemview has a corresponding viewHolder with imageID and a bitmap-gui element
the image in the listviewitemview is initally loaded with a placeholder-image that will be visible until the imagload is complete.
the adapter initiates loading the image in the background (async-task) that gets the viewHolder with imageID.
when loading of the image in the background is finished the viewholder-gui element gets the loaded image.
GridView and ListView work the same way.
Here is a working example from APhotoManager. It contains a GalleryCursorFragment with the gridview with an embedded GridCellViewHolder
As suggested by #Neil and #shelll I used the Glide library. I modified my code accordingly:
added to the build.gradle
compile 'com.github.bumptech.glide:glide:3.7.0'
modified the bindView() method by changing
setImage(holder.imgIcon, nameLOT);
to
int imageId = getResId(getImageName(nameLOT), R.drawable.class);
if(imageId == -1)
imageId = R.drawable.ic_bird_grey;
Glide
.with(holder.imgIcon.getContext())
.load(imageId)
.into(holder.imgIcon);
For asynchronous images loading (and caching) use a library created for that, like Glide or Fresco

Retrieve array from SQLite in listview with more than a colum (ANDROID)

So I want to create a listview that consists of more than a column. I already succeed called the database, but the layouting still not work. I think this is because the all my data are put in one array and its difficult to make them in three columns. anyone can find solution for me?
My program result is like this in listview:
John Doe 12 Argentina
Marilyn Rose 32 Russia
Annabella 19 United States
However what I want is more like this:
John Doe 12 Argentina
Marilyn Rose 32 Russia
Annabella 19 United States
From what I read, we will need 2 XMLs. One for listview, and another is for layouting (give space between text). And One .JAVA called adapter to connect my MainActivity.java and layouting XML.
add:
I already tried using two XMLs. one XML, lets call it main.XML is for calling ListView. And grid.XML, is where i put android:layout_alignParentLeft="true" (to create spaces).
I used MyAdapter.JAVA to convertview in grid.XML. and in MainActivity.JAVA i called MyAdapter. However my code in MainActivity became error when its connected it MyAdapter.
this was my code that gave error java.lang.RuntimeException. So I had to delete it.. more information about it, please check two last code...
MainActivity.java (error)
public static ArrayList<String> arraydealer = new ArrayList<String>();
MyAdapter bohwat = new MyAdapter(MainActivity.this, arraydealer);
lvcustom.setAdapter(bohwat);
And here is the code that is working well. It uses class MainActivity, AstraDB, and MySetGet, and main.XML. Other class thats not working is MyAdapter and grid.xml
This is how I called my database:
public class MainActivity extends Activity
{
public static ArrayList<String> arraydealer = new ArrayList<String>();
AstraDB astrahandler = new AstraDB(this);
Spinner spDealer;
ListView lvcustom;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lvcustom = (ListView)findViewById(R.id.custom_lv);
ShowListView();
}
private void ShowListView()
{
astrahandler.getAllDealer();
ArrayAdapter<String> adapt = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, arraydealer);
lvcustom.setAdapter(adapt);
}
}
This code of ArrayList in Activity and String name in AstraDB are very important to connect my MainActivity with the database but it seems this create trouble in layouting. because they are contained in ONE array
And this is function to get all data in my DB. its on AstraDB.java:
public List<MySetGet> getAllDealer()
{
List<MySetGet> info = new ArrayList<MySetGet>();
db = DBHelper.getReadableDatabase();
// Select All Query
String selectQuery = "SELECT * FROM Dealer";
cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
MySetGet lets = new MySetGet();
lets.setDealerID(Integer.parseInt(cursor.getString(0)));
lets.setDealerName(cursor.getString(1));
lets.setDealerOwner(cursor.getString(2));
lets.setDealerWil(cursor.getString(3));
String name = cursor.getInt(0) +
"\u00A0 "+ cursor.getString(1)+
"\u00A0 "+ cursor.getString(2)+
"\u00A0 "+ cursor.getString(3);
MainActivity.arraydealer.add(name);
//add
info.add(lets);
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
//return contentdealer;
return info;
}
The MySetGet in getAllDealer() connects with MySetGet.java where I put setter and getter so the data can become object. which is more like this:
public int getDealerID(){ return DealerID;}
public void setDealerID(int DealerID) { this.DealerID = DealerID; }
Code to connect other XML with Java but still gave error:
grid_dealer.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_height="wrap_content"
android:layout_width="50dp"
android:id="#+id/col1"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text=""/>
<TextView
android:layout_height="wrap_content"
android:layout_width="100dp"
android:id="#+id/col2"
android:layout_toRightOf="#id/col1"
android:layout_centerVertical="true"
android:text=""/>
important code in MyAdapter.java:
public class MyAdapter extends BaseAdapter
{
Context context;
ArrayList<MySetGet> dealerlist;
public MyAdapter(Context context, ArrayList<MySetGet>list)
{
this.context = context;
dealerlist = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
MySetGet yay = dealerlist.get(position);
//this is to customize the layout of the listview
if(convertView == null)
{
LayoutInflater inflater = null;
inflater = (LayoutInflater)context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.grid_dealer, null);
}
TextView tvID = (TextView)convertView.findViewById(R.id.col1);
tvID.setText(yay.getDealerID());
TextView tvName = (TextView)convertView.findViewById(R.id.col2);
tvName.setText(yay.getDealerName());
TextView tvOwner = (TextView)convertView.findViewById(R.id.col3);
tvOwner.setText(yay.getDealerOwner());
return convertView;
}
}
Please help me. I am very new to this. Is there a way to modify my code without changing too much on how I called my database? The class and XML below works fine in showing database, but didnt create a neat layout space between columns
Working class : AstraDB, MainActivity, MySetGet
Working XML : main.xml
Im sorry, if the post becomes longer. I want to clarify several things so that there is no misunderstanding.
you can use android:layout_weight="" for better arrangement of views
Using SimpleCursorAdapter is the ideal solution in your case. Please checkout a tutorial here that will take you through the steps in achieving what you want.
In simple_list_item_1 layout if you arrange items relative to each other you will get the result what you are getting now. If you want proper formatting, relate the elements to left, center and right using android:layout_alignParentLeft="true", android:centerHorizontal="true" and android:layout_alignParentRight="true" respectively

How to use custom Adapter

I KNOW this is a repost, but I've been trying to get this to work for ages (hours) now and I really can't understand the existing answers.
All i want to know is: How can I edit this code so it works? I'm trying to populate both textviews from two different arrays.
Only the second adapter gets read and the first one's textview stays blank.
Any help at all would be appreciated.
public void run () {
if (t.getState() == Thread.State.TERMINATED) {
adapter2 = new ArrayAdapter<String>(getApplicationContext(), R.layout.listlook, R.id.txtl2, names);
setListAdapter(adapter2);
adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.listlook, R.id.txtl1, comments);
setListAdapter(adapter);
return;
} else {
h.postDelayed(this, 1000);
}
}}
, 1000);
}
Thanks in advance.
Listview within Usercomments.xml
<ListView
android:id="#+android:id/list"
android:layout_width="match_parent"
android:layout_height="150dp" >
</ListView>
listlook.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtl1"
android:paddingLeft="2dp"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#0000FF"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/txtl2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/txtl1"
android:gravity="bottom|right"
android:paddingLeft="5dp"
android:text="TextView"
android:textColor="#5C002E"
android:textSize="15sp" />
</RelativeLayout>
listlook is just the layout i use in the listview? Don't really know what I'm doing.
You're telling your list view that you want to use adapter2, and then telling it you want to use adapter - it can only read data from one adapter at a time.
If you want to display data from two lists, you could do something like this.
First, combine your two lists into a class, and build a List<Post> of these, instead of having two arrays:
public class Post {
String mName, mComment;
public Post(String name, String comment) {
mName = name;
mComment = comment;
}
public String getName() {
return mName;
}
public String getComment() {
return mComment;
}
}
Then, write an adapter that knows how to display Post items:
public class PostAdapter extends BaseAdapter {
private Activity mActivity;
private List<Post> mPosts;
public TweetstreamAdapter(Activity activity, List<Post> posts) {
mActivity = activity;
mPosts = posts;
}
#Override
public int getCount() {
return mPosts.size();
}
#Override
public Post getItem(int position) {
return mPosts.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Post post = getItem(position);
if (convertView == null) {
convertView = mActivity.getLayoutInflater().inflate(R.layout.listlook, parent, false);
}
((TextView)convertView.findViewById(R.id.txtl1)).setText(post.getName());
((TextView)convertView.findViewById(R.id.txtl2)).setText(post.getComment());
return convertView;
}
}
Then in your activity, you set the adapter like this:
setListAdapter(new PostAdapter(this, posts));
where posts is a List<Post> of posts.
Note: You'll need to ensure you have TextView entries in your listlook layout that have IDs that match those that the adapter is searching for. Update the code to match your IDs accordingly. Updated to match your id's. This should just drop in, provided you construct a list of Post objects correctly.
Update 2: You could build a list like this, assuming the two arrays (names/comments) are the same length:
List<Post> posts = new ArrayList<Post>();
for(int i = 0; i < names.length; i++) {
posts.add(new Post(names[i], comments[i]);
}
You have two lines with setListAdapter(). The second overwrite the first. If you have two ListViews then do this:
listView1.setListAdapter(adapter2);
listView2.setListAdapter(adapter);

Updating crossed-out items on loading ListView

I am fairly new to Android programming and trying to set items in a listview upon loading the information from internal storage.
I have two global arrays that I am using: first one is a String array that has the names of the items in the list, and the second is a boolean array that keeps track of which items are crossed out. I am using a TextView in the listview.
main_activity.xml:
<ListView
android:id="#+id/listViewMyList"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
rowlayout.xml:
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:layout_marginBottom="3dp"
android:text="#+id/label" />
I have created an onClickListener() which successfully updates the state of each list item:
public class MainActivity extends Activity
{
// Initialize the list (global list values)
String[] values = new String[0]; // array of items for the list
boolean[] checkedVals = new boolean[0]; // keep track of which items are crossed-off
String localFileName = "myListData.csv";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// read the data from file if present
readListFromFile();
// find the ListView
ListView lst = (ListView) findViewById(R.id.listViewMyList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.rowlayout, R.id.label, values);
lst.setAdapter(adapter);
// define what happens on click
lst.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
// read crossed status and set text flags for strikethrough
if (checkedVals[position])
{
TextView text1 = (TextView)view.findViewById(R.id.label);
text1.setPaintFlags(text1.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
text1.setTextColor(0xff000000);
checkedVals[position] = false;
}
else
{
TextView text1 = (TextView)view.findViewById(R.id.label);
text1.setPaintFlags(text1.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
text1.setTextColor(0xff888888);
checkedVals[position] = true;
}
// save the data in a file
saveListToFile();
}
});
}
So this code works fine for crossing out and un-crossing out the items. I don't know how can I cross-out some of the items (determined by the checkedVals boolean array) without clicking or any activity when I load the list.
Thanks in advance.
You need to create a custom Adapter by extending ArrayAdapter and overriding getView().
The getView() method loads every row's layout, this is where you should check if the row is in your checkedVals array and draw with the appropriate flags. This Google Talk by an Android lead programmer, Romain Guy, provide a wealth of information about best practices on how to do this.

Getting Checkboxes in a custom ListView to work properly

what i do have is a custom row layout for my listview:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/chkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
I am using this layout for my adapter in the activity:
adapter = new AdapterCustomBoxes(context, R.layout.custom_check_row, (ArrayList<Map<String, String>>) list_values);
list.setAdapter(adapter);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
And an adapter for that, here is the getView method of my adapter:
public class AdapterCustomBoxes extends ArrayAdapter<Map<String, String>> {
private List<Map<String, String>> list;
private List<Map<String, String>> orig_list;
private Context upper_context;
private View view;
public AdapterCustomBoxes(Context context, int textViewResourceId, ArrayList<Map<String, String>> items) {
super(context, textViewResourceId, items);
this.list = items;
this.orig_list = items;
this.upper_context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater)upper_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.custom_check_row, null);
}
Map<String, String> selectedgroup = new HashMap<String, String>();
selectedgroup = (Map<String, String>) list.get(position);
String itemtext = (String) selectedgroup.get("item_text");
TextView row_text = (TextView) view.findViewById(R.id.text);
row_text.setText(itemtext);
return view;
}
}
And now here comes the point where i get confused. When i check one of those checkboxes the clicked one gets checked. But without any logic somes of the other line's checkboxes also get checked. And if i then scroll the list the checked status of each box may change from one time i come across this line to the next time.
So what is the problem here?
I already tried to do add an onclicklistener to the view in the adapter and then set the explicit checkbox to cheched/unchecked when this listener is triggered but this also does not work as i expected, i clicked on the one box and the other one got checked.
So i guess this is a problem with recycled views? Do i have to store the checked Status seperately and restore it every time in the getView method could this be a solution? Or is there an easier way? Please help ;)
So can anybody give me a hint? Thnaks a lot!
--- EDIT ---
So what i now tried to save the status of the checkboxes was to creat a map:
private Map<View, Boolean> itm = new HashMap<View, Boolean>();
and save the status when a box is clicked in in the getView method:
CheckBox chkbox = (CheckBox) view.findViewById(R.id.chkbox);
chkbox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
itm.put(buttonView, isChecked);
}
});
if(itm.containsKey(chkbox)){
iteminfo_row_chkbox.setChecked( itm.get(chkbox) );
}else{
iteminfo_row_chkbox.setChecked(false);
}
Sorry if this is the completely wrong approach in any way but shouldn't this work? The result is the same that the whole list and checked statuses are not correct, what am i doing wrong?
A few off-topic comments:
First you don't need this:
Map<String, String> selectedgroup = new HashMap<String, String>();
You can just do this:
Map<String, String> selectedgroup = (Map<String, String>) list.get(position);
Also, are you sure you need the TextView? The checkbox can hold text too.
About your problems, how do you save which checkbox is checked? You should set the checkbox when returning the view, specially when reusing views.
-- Edit --
Why don't you create a private class like this?
private class ListItem{
String text;
boolean value;
}
And then instead of a List<Map<String,String>> you could just have a List<ListItem>.
About the onCheckedChangeListener, you could iterate of the list using the text from the checkbox to find the correct position and then change the value. If the text is not unique,
instead of using onCheckedChangeListener, you could use on the ListView a OnItemClickListener which holds the position of the click.
Okay i think i got it, i used a static id value from the selectedgroup map as the key in the itm map to find the checked/unchecked status of the checkbox. Using the view was the wrong approach because they can't be used as the key.

Categories

Resources