How to use key and values from a hashmap in ArrayAdapter?

Go To StackoverFlow.com

3

I have a hashmap with key, value pairs example :-

(msisdn,value)

43664xxxxxxx,2 43665xxxxxxx,3

now I want to display this information in a ListView but I don't know how to feed the data to an ArrayAdapter from the Hashmap ?

HERE IS MY ADAPTER, note I want to replace myList with data from the Hashmap a concatentated key+value.

  1. Pass the above hashmap to the adapter, replacing myList with the hashmap

    adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,myList); setListAdapter(adapter);

thanks

Without HASHMAP

packagelistmodified.org;

importjava.util.Arrays;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;

importandroid.app.ListActivity;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.view.View;
importandroid.widget.AdapterView;
importandroid.widget.ArrayAdapter;
importandroid.widget.ListView;
importandroid.widget.TextView;
importandroid.widget.AdapterView.OnItemLongClickListener;
importandroid.view.GestureDetector.OnGestureListener;
importandroid.view.GestureDetector;
importandroid.view.MotionEvent;
importandroid.widget.Toast;




publicclasslistmodifiedextendsListActivityimplements
OnGestureListener{
publicArrayList<String>myList=new
ArrayList<String>(Arrays.asList(items));
privateTextViewselection;//MAIN.xml
publicArrayAdapter<String>adapter;//myadapter
publicOnItemLongClickListeneritemDelListener;
privateGestureDetectorgestureScanner;
publicintlongClickedItem=0;//checkiflongClickisselectedor
not
privateStringitemSelected;//fordeletefunction
privatestaticfinalbyteUPDATE_LIST=100;
publicAdapterView<?>parent;//usedbyOnLitemLongClickListener
publicintposition;

//tieitemstoanarraylistcalledmyList
publicstaticString[]items={"lorem","ipsum","dolor",
"sit","amet",
"consectetuer","adipiscing","elit","morbi","vel",
"ligula","vitae","arcu","aliquet","mollis",
"etiam","vel","erat","placerat","ante",
"porttitor","sodales","pellentesque","augue","purus"};

@Override
publicvoidonCreate(Bundleicicle){
super.onCreate(icicle);

OnItemLongClickListeneritemDelListener=new
OnItemLongClickListener(){

//@Override
publicbooleanonItemLongClick(AdapterView<?>parent,Viewarg1,
intposition,longarg3){
//TODOAuto-generatedmethodstub
itemSelected=parent.getItemAtPosition(position).toString();
adapter.remove(itemSelected);
Toast.makeText(listmodified.this,"positionis:"+position,
Toast.LENGTH_SHORT).show();
myList.remove(this);//removethecurrentobject,positionthrows
anexception
adapter.notifyDataSetChanged();


returnfalse;
}};

setContentView(R.layout.main);


//DEFINEMYOWNVIEWTIETOARRAYLISTmyListWHICHCONTAINSSTRINGS
adapter=new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,myList);
setListAdapter(adapter);

//AVIEWOFTHELISTNECESSARYFORDELETION

selection=(TextView)findViewById(R.id.selection);


//PARTOFLONGCLICKSELECTEDCODE
//CALLSIMPLEMENTEDMETHODS-detectgesturescheckingmylistitems
gestureScanner=newGestureDetector(this);
getListView().setOnTouchListener(newView.OnTouchListener(){
@Override
publicbooleanonTouch(Viewv,MotionEventevent){
returngestureScanner.onTouchEvent(event);
}
});

//UPDATEVIEWDELETEWHENONLONGCLICKISPRESSED
getListView().setOnItemLongClickListener(itemDelListener);

}


//LISTITEMPRESSCHECKING
publicvoidonListItemClick(ListViewparent,Viewv,
intposition,longid){
selection.setText(myList.get(position));
//checktoseeifLONGCLICKISPRESSED
if(longClickedItem!=-1){
Toast.makeText(listmodified.this,"Ashortclickdetected",
Toast.LENGTH_SHORT).show();

}
longClickedItem=0;
}

//IMPLEMENTEDBYGESTURE
@Override
publicbooleanonDown(MotionEventarg0){
//TODOAuto-generatedmethodstub
returnfalse;
}


@Override
publicbooleanonFling(MotionEvente1,MotionEvente2,float
velocityX,
floatvelocityY){
//TODOAuto-generatedmethodstub
returnfalse;
}


//CHECKSONLONGPRESSEVENTSSETLONGPRESSTO-1,
//COOLICANUSETHISTOSEEIFALONGCLICKWASSELECTEDLATERON

@Override
publicvoidonLongPress(MotionEvente){
//TODOAuto-generatedmethodstub
Toast.makeText(listmodified.this,"Alongclickdetected",
Toast.LENGTH_SHORT).show();


if(e.getAction()==MotionEvent.ACTION_DOWN)
{

longClickedItem=-1;

}

}


@Override
publicbooleanonScroll(MotionEvente1,MotionEvente2,float
distanceX,
floatdistanceY){
//TODOAuto-generatedmethodstub
returnfalse;
}


@Override
publicvoidonShowPress(MotionEvente){
//TODOAuto-generatedmethodstub

}


@Override
publicbooleanonSingleTapUp(MotionEvente){
//TODOAuto-generatedmethodstub
returnfalse;
}
privateHandlerupdateListHandler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
switch(msg.what){
caseUPDATE_LIST:
intposition=msg.arg1;
myList.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(listmodified.this,"OnSingleTapUp",
Toast.LENGTH_SHORT).show();
break;

}
;
};
};


}
2012-04-03 19:34
by user803271


4

I don't know how to feed the data to an ArrayAdapter from the Hashmap ?

Use new ArrayList<String>(myHashMap.keySet()), assuming myHashMap is a HashMap<String, Something>.

2012-04-03 19:54
by CommonsWare
Took me a while to find what he wanted to display, but it's the key and the value: "I want to replace myList with data from the Hashmap a concatentated key+value. - dmon 2012-04-03 20:03
Thanks CommonsWare I'll give that a go, not easy .... - user803271 2012-04-03 20:05
Hi, the code I posted includes items of type String, and it is part of myList

publicArrayListmyList=new ArrayList(Arrays.asList(items));

and my ArraryAdapter is using this ArrayAdapter(this,android.R.layout.simplelistitem_1,myList); setListAdapter(adapter);

but if I have an hash which contains key value pairs which I want to pass these instead of a simple string array this is were I am having problem - user803271 2012-04-03 20:15

@user803271: You don't "pass them". Either fill into the ArrayList precisely what you want to have appear, or extend ArrayAdapter, override getView(), and handle populating the list rows yourself. Somewhere, you are going to need to concatenate your strings -- whether you do that up front or on a per-row basis is up to you - CommonsWare 2012-04-03 20:20
Thanks CommonsWar - user803271 2012-04-03 20:28
One more question when I declare a test HashMap it seems only to work as static

private static final Map myHashMap = new HashMap(); static { myHashMap.put(1, "one"); myHashMap.put(2, "two"); } and I am unable to access the HashMap outside of the brackets. So new ArrayList(MyHashMap.KeySet()) fails as MyHashMap cannot be resolved ... - user803271 2012-04-03 20:37

public class MyClass { private Map myHashMap;

 public MyClass() 
 { 
      myHashMap = new HashMap<Integer, String>(); 
      myHashMap.put(1, "one"); 
      myHashMap.put(2, "two"); 
 }

- user803271 2012-04-03 21:06

So I have something like this now public class listmodified extends ListActivity implements OnGestureListener { //public ArrayList myList = new ArrayList(Arrays.asList(items)); public Map myHashMap; { String Result=""; myHashMap = new HashMap(); myHashMap.put(1, "one"); myHashMap.put(2, "two"); myHashMap.keySet().toArray(); myHashMap.values().toArray(); Result = ": + myHashMap.keySet().toArray() + myHashMap.values().toArray()";}How do iterate over the HashMap - user803271 2012-04-03 21:29