Android Muticolum listview onListItemClick - android

I have done Muticolum listview onListItemClick .Its working fine.Problem is
This line String selection = l.getItemAtPosition(position).toString(); return this
{routeName=TestRoute2, outlets=5, routeCode=VRT002} .I want to get it selected row's 3rd column value.How to get it.
Please help me..
Thanks in advance..

What kind of Adapter? E.g. for a SimpleCursorAdapter you would do the following:
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
long aLongValue = cursor.getLong(cursor.getColumnIndexOrThrow("anintegercolumn"));

ArrayList<HashMap<String, String>> historyArrayList;
SimpleAdapter histroyListAdapter;
HashMap<String, String> historyObjectMap;
for (CheckInCheckOutHistory checkOutHistoryObj : checkInCheckOutHistoryList) {
historyObjectMap = new HashMap<String, String>();
historyObjectMap.put("assetTag", checkOutHistoryObj.getAssetTag());
historyObjectMap.put("action", checkOutHistoryObj.getAction());
historyObjectMap.put("actionTime", checkOutHistoryObj.getActionDate());
if (checkOutHistoryObj.getAction().equals("Checked out")) {
historyObjectMap.put("gif", R.drawable.radio_button_yellow+ "");
} else {
historyObjectMap.put("gif", R.drawable.radio_button_green+ "");
}
historyArrayList.add(historyObjectMap);
}
histroyListAdapter = new SimpleAdapter(
ViewCheckInCheckOutHistory.this, historyArrayList,
R.layout.multi_colummn_list_text_style_small, new String[] {
"assetTag", "gif" , "action", "actionTime"},
new int[] { R.id.list_content_column1,
R.id.list_content_imagecolumn,
R.id.list_content_column3,
R.id.list_content_column4});
historyListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> historyObjectMapLocal = historyArrayList
.get(position);
final String assetTag = historyObjectMapLocal
.get("assetTag");
System.out.println("assetTag : " + assetTag);
}
});
In the above code the listView contents are populated using an ArrayList historyArrayList
and so the items at any column could be accessed using key ("assetTag", "gif" , "action", "actionTime").

Related

get value from a list view

I have a list view.when any one clicking the list it showing list content as
{first_name=abc, last_name=xyz, id=1, address=kolkata}
but I want those get those value individually from that string who to get that.
My onListItemClick Listner
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
String return_data = o.toString();
Toast.makeText(this, ""+return_data, Toast.LENGTH_LONG).show();
}
Added total class including List adapter
public class showUserInfoListActivity extends ListActivity {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
static final String KEY_ID = "id";
static final String KEY_FIRST_NAME = "first_name";
static final String KEY_LAST_NAME = "last_name";
static final String KEY_ADDRESS = "address";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_user_info_list);
//---get all Records---
DataBaseAdapter db = new DataBaseAdapter(this);
db.open();
Cursor c = db.getAllRecords();
if (c.moveToFirst())
{
do
{
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, c.getString(0));
map.put(KEY_FIRST_NAME, c.getString(1));
map.put(KEY_LAST_NAME, " "+c.getString(2));
map.put(KEY_ADDRESS, c.getString(3));
// adding HashList to ArrayList
menuItems.add(map);
} while (c.moveToNext());
}
db.close();
// Adding menuItems to ListView
// All filed data are not shown in the list KEY_ID is hidden
ListAdapter adapter = new SimpleAdapter(this, menuItems,R.layout.user_info_list_item,
new String[] { KEY_FIRST_NAME, KEY_LAST_NAME, KEY_ADDRESS, KEY_ID },
new int[] {R.id.first_name , R.id.last_name, R.id.address});
setListAdapter(adapter);
}
//On select from the list show data
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
//String return_data = o.toString();
MyClass return_data = (MyClass)o;
Toast.makeText(this, ""+return_data, Toast.LENGTH_LONG).show();
}
class MyClass{
}
}
Instead of
String return_data = o.toString();
you need to cast o to whatever class of object it is.
MyClass return_data = (MyClass)o;
Then you can access its fields and call its methods as usual.
In your case:
HashMap<String, String> returndata = (HashMap<String, String>) o;

Listview shows old and new content after updating

In my application, listview is loaded from SQLite database and it is using SimpleAdapter to set ListView. When user perform longclick on listitem, that item will be deleted from database and it should update listviw. But when i remove item from database, listview shows both old and new data.
Please suggest some solution.
Thanx.
Following is my code:
public class FavouriteListActivity extends ListActivity {
public final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
ListAdapter adapter;
public ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
ArrayList<String> titles = new ArrayList<String>();
String title,artist;
SQLiteAdapter adp;
SimpleCursorAdapter cursoradp;
Cursor cursor,cursorDB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favouritelist);
// Adding menuItems to ListView
final String[] from = {"songTitle", "artist","duration"};
final int[] to={R.id.fav_songTitle,R.id.fav_songArtist,R.id.fav_duration};
ListView lv = getListView();
songsListData = getFavourites();
final ListAdapter adapter = new SimpleAdapter(this,songsListData,
R.layout.favouritelist_item, from, to);
lv.setFastScrollEnabled(true);
setListAdapter(adapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
public boolean onItemLongClick(AdapterView<?> av, View v,
final int pos,final long id) {
final AlertDialog.Builder b = new AlertDialog.Builder(FavouriteListActivity.this);
b.setTitle("Are you sure you want to delete?");
b.setIcon(android.R.drawable.ic_delete);
b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String title = songsListData.get(pos).get("songTitle");
ListAdapter adapter = null;
adp.delete_byTitle(title);
songsListData.clear();
setListAdapter(null);
songsListData = getFavourites();
adapter = new SimpleAdapter(getApplicationContext(), songsListData,R.layout.favouritelist_item, from, to);
setListAdapter(adapter);
Toast.makeText(FavouriteListActivity.this,"Song is removed from Favourites", Toast.LENGTH_SHORT).show();
}
});
b.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
b.show();
return true;
}
});
}
public ArrayList<HashMap<String,String>> getFavourites()
{
ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
ArrayList<String> titles = new ArrayList<String>();
adp = new SQLiteAdapter(this);
adp.openToRead();
cursorDB = adp.queueAll();
if(cursorDB.moveToFirst())
{
for(int i=0;i<cursorDB.getCount();i++)
{
titles.add(cursorDB.getString(cursorDB.getColumnIndex("Title")));
cursorDB.moveToNext();
}
String[] songTitles = new String[titles.size()];
songTitles = titles.toArray(songTitles);
if(songTitles == null)
{
songTitles =null;
}
String whereClause = MediaStore.Audio.Media.TITLE + " IN ( ?";
if (songTitles.length>1)
{
for (int j = 1 ; j < songTitles.length; ++j)
{
whereClause+=", ?";
}
}
whereClause+=")";
Cursor cursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null ,whereClause,songTitles,MediaStore.Audio.Media.TITLE);
if (cursor == null)
{
//Query Failed , Handle error.
}
else if (!cursor.moveToFirst())
{
//No media on the device.
}
else
{
int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = cursor.getColumnIndexOrThrow(android.provider.MediaStore.Audio.Media.DATA);
int artistcolumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
int durationcolumn =cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.DURATION);
for(int i=0;i<cursor.getCount();i++)
{
String thisTitle = cursor.getString(titleColumn);
String path = cursor.getString(idColumn);
String artist = cursor.getString(artistcolumn);
Long duration = cursor.getLong(durationcolumn);
Utilities objUtilities = new Utilities();
String timeDuration = objUtilities.milliSecondsToTimer(duration);
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle",thisTitle);
song.put("songPath", path);
song.put("artist", artist);
song.put("duration",timeDuration);
// Adding each song to SongList
songsList.add(song);
cursor.moveToNext();
}
}
// looping through playlist
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
HashMap<String, String> song = songsList.get(i);
// adding HashList to ArrayList
songsListData.add(song);
}
}
return songsListData;
}
}
You never clear songList, to which therefore is added all your items at each deletion.
Which in turn are all copied to songsListData.
After removing data from the database , call
Listview.invalidateViews();
and reset the adapter to the list .
Actually it gets removed from the database but it shows the older list in the ListView , so invalidate your older views and reset the adapter .
Call adapter.notifyDataSetChanged() every time your data changes.
b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String title = songsListData.get(pos).get("songTitle");
adp.delete_byTitle(title);
songsListData.clear();
setListAdapter(null);
songsListData = getFavourites();
adapter = new SimpleAdapter(getApplicationContext(), songsListData,R.layout.favouritelist_item, from, to);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
Toast.makeText(FavouriteListActivity.this,"Song is removed from Favourites", Toast.LENGTH_SHORT).show();
}
});

Changing ListView selected item

I have a list view, each item is composed of three elements: picture view and 3 text view, the latter contains the name of a product, product price and quantity, i want when I click on the item it correspanding quantity increases by one.
Here's the code:
public class BoissonActivity extends Activity {
ListView maListViewPerso;
BaseDeDonne db = new BaseDeDonne(this);
private static String choix="boisson";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.boisson_layout);
maListViewPerso = (ListView) findViewById(R.id.listviewperso);
Log.d("Lire: ", "Lire tous les produits..");
ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map;
listItem.clear();
List<Produit> produit = db.getSelectProduit(choix);
for (Produit cn : produit) {
map = new HashMap<String, Object>();
map.put("titre",String.valueOf(cn.getNom()));
map.put("description","Prix:"+cn.getPrix_produit());
map.put("quantite", 0);
String url="/sdcard/Image_Produits/"+cn.getImage_produit()+".jpg";
URL pictureURL = null;
try {
pictureURL = new URL(url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeFile(url);
map.put("img", bitmap);
listItem.add(map);
String log = "Id: "+cn.getId()+" ,Nom: " + cn.getNom()+ " ,Image: " + cn.getImage_produit() +
" ,Prix: " + cn.getPrix_produit()+" ,Catégorie: " + cn.getCategorie();
Log.d("produits: ", log);
}
SimpleAdapter mSchedule = new SimpleAdapter (this.getBaseContext(), listItem, R.layout.affichageitem,
new String[] {"img", "titre", "description","quantite"}, new int[] {R.id.img, R.id.titre, R.id.description,R.id.quantite});
mSchedule.setViewBinder(new MyViewBinder());
maListViewPerso.setAdapter(mSchedule);
i tried this but only the first textview is changed :
maListViewPerso.setOnItemClickListener(new OnItemClickListener()
{ int compteur=0;
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
TextView t = (TextView)findViewById(R.id.quantite);
t.setText(String.valueOf(compteur));
compteur++;
}
});
Add an onListItemClick..
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Your code here to increment the qty
}
EDIT
Use the View parameter passed in to access the proper view (i'm taking values from the code you added above, so it doesn't exactly match what I show above).
TextView t = (TextView) arg1.findViewById(R.id.quantite);
t.setText(String.valueOf(compteur));

Suggest me a suitable adapter to pass arraylist containing image url and title to display in listview

i hav to display the thumbnail of the image along with the title of it in a list view by parsing the JSON feed.. My code
public class Main extends ListActivity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
String url;
Bitmap bitmap;
ImageView img;
int im ;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = Json_mysamActivity.getJSONfromURL("http://gdata.youtube.com/feeds/mobile/videos?max-results=3&alt=json");
try {
JSONObject jb = json.getJSONObject("feed");
JSONArray jarr = jb.getJSONArray("entry");
for(int i=0;i<jarr.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jarr.getJSONObject(i);
JSONObject det = e.getJSONObject("title");
map.put("id", String.valueOf(i));
map.put("$t", "t:" + det.getString("$t"));
map.put("type", "type: " + det.getString("type"));
JSONObject det1 = e.getJSONObject("media$group");
JSONArray det12 = det1.getJSONArray("media$thumbnail");
for(int j=0;j<1;j++)
{
JSONObject det12obj = det12.getJSONObject(i);
url = det12obj.getString("url");
map.put("url", "url:"+ det12obj.getString("url"));
mylist.add(map);
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String[] from = new String[] { "$t", "type","url" };
int[] to = new int[] { R.id.item_title, R.id.item_subtitle, R.id.test_image };
MySimpleCursorAdapter adapter = new MySimpleCursorAdapter(this, R.layout.main, mylist ,
from, to);
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
public class MySimpleCursorAdapter extends SimpleCursorAdapter {
// SimpleCursorAdapter requires cursor in the place of ArrayList but I need to pass //arraylist, how should I implement it
public MySimpleCursorAdapter(Context context, int layout, ArrayList<HashMap<String, String>> mylist,
String[] from, int[] to) {
super(context, layout, mylist, from, to);
}
#Override
public void setViewImage(ImageView v, String url) {
String path =url ;
Bitmap b = BitmapFactory.decodeFile(path);
v.setImageBitmap(b);
}
}
}
What you need is a SimpleAdapter. A cursor adapter is used for displaying daat in a list that comes from a database. SimpleAdapter is used for data in RAM (your list after parsing the json).
Check this first google entry, it should do.
In case you are using arraylist as datasource you should use ArrayAdapter, so Extend your adapter from ArrayAdapter. see link for Custom Array Adapter:
http://android-er.blogspot.in/2010/06/custom-arrayadapter-with-with-different.html
When you are loading image views in list, its good practice to use LazyLoading, see below link for Lazy Loading in android:
http://ballardhack.wordpress.com/2010/04/05/loading-remote-images-in-a-listview-on-android/
for this you have to use LayoutInflater, write your own adapter class extends ArrayAdapter,
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
adapter = new CustomAdapter(this, R.layout.list_row, R.id.title, data,
mInflater, imgid);

List not getting refreshed

I am trying to refresh my list view after deleting items from it, but i am not geting the desired result. The items are getting deleted when i reload the activity but not at the time i press the delete button. Here is my code:
public void deletelist()
{
mylist = new ArrayList<HashMap<String,Object>>();
HashMap<String,Object> map = new HashMap<String, Object>();
for(int i=0;i<favtitle.size();i++)
{
map = new HashMap<String, Object>();
map.put("train",favtitle.get(i));
map.put("value",favloc.get(i));
map.put("employer",favemp.get(i));
mylist.add(map);
}
mSchedule = new SimpleAdapter(this, mylist, R.layout.listdelete,
new String[] {"train","value","employer"}, new int[] {R.id.dept,R.id.jobloc,R.id.employer});
lv.setAdapter(mSchedule);
lv.setDividerHeight(2);
lv.setCacheColorHint(Color.WHITE);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,View view,int position,long id)
{
String str3 = favtitle.get(position);
db.delete("Favorites7","title= '"+str3+"'",null);
db.close();
//Data Base Select
db = openOrCreateDatabase(
"ClassifiedAds.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
//End-----
cur= db.query("Favorites7",
null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfterLast() == false) {
favtitle.add(cur.getString(1));
favloc.add(cur.getString(3));
favemp.add(cur.getString(2));
lat.add(cur.getString(7));
log.add(cur.getString(8));
cur.moveToNext();
}
cur.close();
//mylist = new ArrayList<HashMap<String,Object>>();
HashMap<String,Object> map = new HashMap<String, Object>();
for(int i=0;i<favtitle.size();i++)
{
map = new HashMap<String, Object>();
map.put("train",favtitle.get(i));
System.out.println("==="+favtitle.get(i));
map.put("value",favloc.get(i));
System.out.println("==="+favloc.get(i));
map.put("employer",favemp.get(i));
System.out.println("==="+favemp.get(i));
mylist.add(map);
}
mSchedule.notifyDataSetChanged();
mSchedule = new SimpleAdapter(Favorites.this, mylist, R.layout.listdelete,
new String[] {"train","value","employer"}, new int[] {R.id.dept,R.id.jobloc,R.id.employer});
lv.setAdapter(mSchedule);
lv.setDividerHeight(2);
lv.setCacheColorHint(Color.WHITE);
}
});
}
Any help would be appreciated.
Thanx in advance.
Use notifyDataSetChanged() method with the listview within the condition where you are deleting the record , just after deleting the record put the listview.notifyDataSetChanged() code.
hope this will solve your problem.
Did you tried invalidateViews, it will redrawn you list view.
My problem is solved. What i had to do was that whenever the arraylist was reloading i had to clear the previous one.
Like:
array-list name.clear();
before adding items into the hashmap.

Categories

Resources