repeating ListView - android

Hey guys I am a working on displaying a list of items on listview, the code I am using is
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_list_view);
ListView lv= (ListView)findViewById(R.id.listview);
rtrnList = new ArrayList<HashMap<String,String>>();
getmyLocation();
listclass = new listClass(offersobj);
listclass.populate();
rtrnList = listclass.getListArray();
adapter = new SimpleAdapter(
this,
rtrnList,
R.layout.custom_row_view,
new String[] {"Name","Msg","time"},
new int[] {R.id.text1,R.id.text2, R.id.text3}
);
lv.setAdapter(adapter);
}
problem is say I am displaying three names Avinash, Arun, Rajesh. When application starts these three names are displayed on list. When I close and again start the application the values are repeating Avinash, Arun, Rajesh,Avinash, Arun, Rajesh. I am not able to figure out how to solve this.

The code you show seems fine. My guess is that listclass.populate() modifies offersobj and that offersobj is reused over several creations of your activity. So, whenever the activity is created, additional data is populated.

public class ListViewA extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lv= (ListView)findViewById(R.id.listview);
// create the grid item mapping
String[] from = new String[] {"rowid", "col_1", "col_2", "col_3"};
int[] to = new int[] { R.id.item1, R.id.item2, R.id.item3, R.id.item4 };
// prepare the list of all records
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
for(int i = 0; i < 10; i++){
HashMap<String, String> map = new HashMap<String, String>();
map.put("rowid", "" + i);
map.put("col_1", "col_1_item_" + i);
map.put("col_2", "col_2_item_" + i);
map.put("col_3", "col_3_item_" + i);
fillMaps.add(map);
}
// fill in the grid_item layout
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.grid_item, from, to);
lv.setAdapter(adapter);
}
}
for more example see this linkthis alsolistview about adapter, for create a hashmap, why bitmap type imported cannot show image in listview?What adapter shall I use to use HashMap in a ListView

Related

How to assign value to each item in listView?

I am working on health related app. In ListView I want to assign value to each item. For example milk contains 21 calories so I want to assign 21 to ListView item milk.
Here is my activity code containing ListView.
public class FoodEntry extends AppCompatActivity {
// Array of strings...
String[] food = {"Naan","Pav bhaji","chole tikiya", "rice", "soybean", "milk", "curd"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_entry);
ArrayAdapter adapter = new ArrayAdapter<>(this, R.layout.activity_item, food);
ListView listViewFoodItems = (ListView)findViewById(R.id.listViewFood);
listViewFoodItems.setAdapter(adapter);
}
}
Instead of using a String[] to store your data like you're doing here:
// Array of strings...
String[] food = {"Naan","Pav bhaji","chole tikiya", "rice", "soybean", "milk", "curd"};
Use a new object, such as CalorieCount.
// Array of CalorieCount
CalorieCount[] food = { new CalorieCount("Naan", 20) ... };
You can use SimpleAdapter with Hashmap
foodItems= new ArrayList<HashMap<String, String>>();
//create first item object
HashMap<String, String> item1= new HashMap<String, String>();
item1.put("name", "Naan");
item1.put("calories", "21");
foodItems.add(item1)//add multiple items like this
String[] from = { "name"};
// view id's to which data to be binded
int[] to = { R.id.name};
//Creating Adapter
ListAdapter adapter = new SimpleAdapter(MainActivity.this, foodItems,
R.layout.activity_item, from, to);
//Setting Adapter to ListView
listViewFoodItems.setAdapter(adapter);
To know more visit How SimpleAdapter Binds Hashmap Data to items of ListView

add subitems in listview in android

I have a listvew and I add subitem into the listview like this code
public class MyCustomListView extends Activity {
/** Called when the activity is first created. */
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_list_view);
lv=(ListView) this.findViewById(R.id.lvvv);
SimpleAdapter adapter = new SimpleAdapter(this,list, R.layout.custom_row_view,new String[] {"pen","color"},
new int[] {R.id.text1, R.id.text3}
);
populateList();
lv.setAdapter(adapter);
}
static final ArrayList<HashMap<String,String>> list =
new ArrayList<HashMap<String,String>>();
private void populateList() {
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("pen","MONT Blanc");
temp.put("color", "Black");
list.add(temp);
HashMap<String,String> temp1 = new HashMap<String,String>();
temp1.put("pen","Gucci");
temp1.put("color", "Red");
list.add(temp1);
HashMap<String,String> temp2 = new HashMap<String,String>();
temp2.put("pen","Parker");
temp2.put("color", "Blue");
}
}
but in the color key, if I have a lot of colors for a pen, and I want to arrange the colors into a list and this color list is under the pen.
ex:
-pen: Parker.
+color: blue.
+color: red.
how should I do that? please help me!
thank alot.
You need to use an ExpanadableListView. Check out this -
ExpanadaleListView Tutorial

Reusing the same ListView to display different data

ListViews have always been my weak point and right now I am practicing putting a Listview, within a Listview. Anyway, I first call my ListView at the start of my program and it loads it with an array saved in my strings.xml:
String[] departments = getResources().getStringArray(
R.array.departments_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
departments));
setContentView(R.layout.main);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
What I want to do is update this ListView with a new array of values each time a list item is clicked. The reason why I am trying to do it this way is because I plan on having 27 different arrays with different values for each position, and I feel it would be lighter on my resources if instead of making a ListView for each array of items, I would update this one ListView. I know I am probably not doing this the most efficient way, but if there is another way of implementing my idea please tell me.
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
switch (position) {
case 0:
try {
//It is here that i dont know what to do, I was going to call
//the Listview the same way i did previously using my setlistadapter,
//but i kept getting errors about the code being undefined
String[] listitems1 = getResources().getStringArray(
R.array.items_array);
} catch (ClassCastException e) {
Toast.makeText(getApplicationContext(), "Error",
Toast.LENGTH_SHORT).show();
}
break;
case 1:
try {
//The listview will be changed again here
} catch (ClassCastException e) {
Toast.makeText(getApplicationContext(), "Error",
Toast.LENGTH_SHORT).show();
}
break;
}
};
});
Have you thought of using a BaseAdapter and setting it as the list adapter
http://developer.android.com/reference/android/widget/BaseAdapter.html
Your approach is wrong( if I understand what are you doing). Instead of replacing the adapter of the ListView every time the user clicks(and simply setting a new adapter should work) a element in the initial list you should start a new activity passing the clicked position and in your new activity set the adapter on a ListView with the correct array based on that position.
A small example:
Main class:
/**
* The main class with the initial 27 items array.
*/
public class Class1 extends ListActivity {
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// start the second activity that will show our array depending on the
// position clicked
Intent i = new Intent(this, Class2.class);
// put the position in the Intent so we can know in the other activity
// what array to load.
i.putExtra("pos", position);
startActivity(i);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// I just used a simple array of 2 items, you'll load your 27 items
// array
String[] items = { "1", "2" };
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items));
}
}
Secondary activity that will show the array based on the previously selected position:
public class Class2 extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get the Intent that started the activity
Intent i = getIntent();
// find out what position did that other activity send to us.
int position = i.getIntExtra("pos", -1);
// load the ListView with an adapter based on the array that you
// want(according to that position)
if (position == 0) {
// the first element in the main list
String[] items = getResources().getStringArray(R.array.a1);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items));
} else if (position == 1) {
// the second element in the main list
String[] items = getResources().getStringArray(R.array.a2);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items));
} else {
// etc
}
}
}
Luksprog's answer is indeed correct, and it is very useful for lists many levels deep (you do not put limits, just keep spawning new activity instances with the proper list loaded)
BUT
If your list isn't more than 2 levels deep you can use ExpandableListActivity instead of ListActivity which is basically an enhanced version of the single-level list you're using which natively handle group collapsing/expanding and therefore you do not need the spawn of a new activity for each sublevel.
again note that this approach works only for lists which do not go deeper than 2 levels
ExpandableListActivity documentation
ExpandableListView documentation
ExpandableListAdapter documentation - you should be fine with the BaseExpandableListAdapter implementation
And here you have some nice example from Google itself:
public class ExpandableList3 extends ExpandableListActivity {
private static final String NAME = "NAME";
private static final String IS_EVEN = "IS_EVEN";
private ExpandableListAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();
for (int i = 0; i < 20; i++) {
Map<String, String> curGroupMap = new HashMap<String, String>();
groupData.add(curGroupMap);
curGroupMap.put(NAME, "Group " + i);
curGroupMap.put(IS_EVEN, (i % 2 == 0) ? "This group is even" : "This group is odd");
//filling with dummy data...
List<Map<String, String>> children = new ArrayList<Map<String, String>>();
for (int j = 0; j < 15; j++) {
Map<String, String> curChildMap = new HashMap<String, String>();
children.add(curChildMap);
curChildMap.put(NAME, "Child " + j);
curChildMap.put(IS_EVEN, (j % 2 == 0) ? "This child is even" : "This child is odd");
}
childData.add(children);
}
// Set up our adapter
mAdapter = new SimpleExpandableListAdapter(
this,
groupData,
android.R.layout.simple_expandable_list_item_1,
new String[] { NAME, IS_EVEN },
new int[] { android.R.id.text1, android.R.id.text2 },
childData,
android.R.layout.simple_expandable_list_item_2,
new String[] { NAME, IS_EVEN },
new int[] { android.R.id.text1, android.R.id.text2 }
);
setListAdapter(mAdapter);
}
}

Using simple_list_item_2 and can't figure out how to use setOnItemClickListener

Please excuse me, I'm new:new at this. I use a simple_list_item_2 to display 11 items. These 11 items have been loaded by using HashMap and then SimpleAdapter. This works fine in displaying everything. The problem is that I cannot get setOnItemClickListener going. The code:
public class TwoLineActivity extends ListActivity
{
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(2);
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.scrolllist);
// enter valid data, these 2 are the same as the remaining 9
HashMap<String, String> maplist;
maplist = new HashMap<String, String>();
maplist.put("line1", "a11 data");
maplist.put("line2", "asd asd ad 1234569780");
list.add(maplist);
maplist = new HashMap<String, String>();
maplist.put("line1", "a12 data");
maplist.put("line2", "asd asd ad 1234569781");
list.add(maplist);
String[] from = { "line1", "line2" };
int[] to = { android.R.id.text1, android.R.id.text2 };
SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2, from, to);
setListAdapter(adapter);`
So up to here things are great, I get my list. Now I want to be able to select an item from the list, so I coded the next 2 lines
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener()
{ .....
I get the following errors
The method setAdapter(SimpleAdapter) is undefined for the type ArrayList<HashMap<String,String>>
and
The method setOnItemClickListener(new AdapterView.OnItemClickListener(){}) is undefined for the type ArrayList<HashMap<String,String>>
If your activity extends ListActivity, you should override
protected void onListItemClick(ListView l, View v, int position, long id) {
}

How to add Image to the Custom List View in Android?

I have a custom list view with image view and text view.I am loading text view data from SQLite Database and I want to add image from my drawable folder to the image view contain in list based on some condition
I am using cursor to load data to the list view.Please any one guide me how to do this
Very simple solution for that,using a simple adapter.
public class TestList extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView list = (ListView) findViewById(R.id.list);
ArrayList<Map<String, String>> arrlist = new ArrayList<Map<String, String>>();
Map<String, String> m = null;
for (int i = 0; i <=50; i++) {
m = new HashMap<String, String>();
m.put("key", String.valueOf(R.drawable.ic_launcher));
m.put("title", "Title-" + i);
m.put("subtitle", "SubTitle-" + i);
arrlist.add(m);
}
SimpleAdapter adapter = new SimpleAdapter(this, arrlist,
R.layout.sample, new String[] { "key", "title", "subtitle" },
new int[] { R.id.imageView1, R.id.title, R.id.subtitle });
list.setAdapter(adapter);
}
}
Xml layouts: main xml layout has a listview with id-list,and sample.xml is your inflating layout,it has one image,two textviews.Modify the code as your requirement.

Categories

Resources