I have a HashMap
HashMap<String, Integer> map = new HashMap<String, Integer>();
in the map there are some value. I want to get the value one by one and add it in listview. The value which is in map are
{Intent { cmp=Bluetooth/300 }=300, Intent { cmp=Audio/400 }=400,
Intent { cmp=Video/500 }=500, Intent { cmp=Display/100 }=100, Intent {
cmp=WiFi/200 }=200}
There are two textview in the listview.
And I want to be display in listview as
Display 100
WiFi 200
Bluetooth 300.
Now I public my Adapter Class which will be helpful to you...
private class NewAdapter extends BaseAdapter {
public NewAdapter(IntentTestingActivity intentTestingActivity,
HashMap<String, Integer> map) {
}
#Override
public int getCount() {
Log.d(TAG, "Map size is: " + map.size());
return map.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
View v = view;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.class_name, null);
}
TextView className = (TextView) v.findViewById(R.id.name);
TextView tagName = (TextView) v.findViewById(R.id.tag_name);
Integer key_name;
key_name = map.get(name);
Log.d(TAG, "Complete map is: " + map.toString());
// String tag = map.get(tagName).toString();
// Integer name = map.get(className);
String keyName;
keyName = map.toString();
Log.d(TAG, "KeyName is: " + map.get(tag));
for (int i = 0; i < map.size(); ++i)
Log.d(TAG, "Tag is: " + tag + " and Name is: " + name + " and Intent is: "+intent);
HashMap<String, Integer> hashmap = map;
for (Entry<String, Integer> e : hashmap.entrySet()) {
String key = e.getKey();
int value = e.getValue();
Set<String>keyname = map.keySet();
Log.d(TAG, "Key: " + key+ " Value: "+value);
}
className.setText(name.toString());
// tagName.setText(keyName);
return v;
}
}
Where name is a just String in which holding all keyValue, such as Display, Vedio ect.
Thanx in advance...
You can create a POJO class with getter-setter and set the key and value to that class.
List<POJO> list = new ArrayList<POJO>();
Iterator<Entry<String, Integer>> iterator = map.entrySet().iterator();
Entry< String, Integer> entry;
while(iterator.hasNext()){
POJO obj = new POJO();
entry = iterator.next();
Log.d("Key Value",entry.getKey()+" "+entry.getValue());
obj.setKey(entry.getKey());
obj.setValue(entry.getValue());
list.add(obj);
}
And then set this list to your Adapter class. This is will be an easy way.
Build a custom Adapter that uses your HashMap and...
Whenever you want to do processing with the views in a ListView you
need to create a custom adapter that will handle your logic
implementation and pass that information to the views as necessary.
Seems like you are showing both values together as a single string, so you may achieve this by simply doing in this way:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.id.text1);
for(String key : map.keySet()){
adapter.add(key + " " + map.get(key));
}
yourListView.setAdapter(adapter);
Related
If I populate my listview with the primary key of my table I can get this primary key using getItemAtPosition and then it works fine.
The problem is that I don't want to use the primarykey to populate de listview, instead I want to use other fields of my table. Doing that, when I use the getItemAtPosition comand, because itsn't unic I can't use this to select my register.
I thought about using getItemIdAtPosition but I didn't reached any solution.
public void populateListView() {
//get the data and append to the list
Cursor data = db.getAllDataFillup(selectedID);
ArrayList<String> listData2 = new ArrayList<>();
while (data.moveToNext()) {
//listData2.add("FILLUP_ID: " + data.getString(0) + " FILLUP_VEHICLE_ID: " + data.getString(1));
//listData2.add(data.getString(7) + " " + data.getString(8) + " " + data.getString(2));
listData2.add(data.getString(3));
//listData2.add(data.getString(2));
}
//create the list adapter and set the adapter
ListAdapter adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listData2);
list_fillup.setAdapter(adapter2);
//set onItemClickListener to the listView
list_fillup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int fillupID = Integer.parseInt(adapterView.getItemAtPosition(i).toString());
long position = adapterView.getSelectedItemId();
//long a = list_fillup.get(codigoDoObjeto).getCodigoIdOuPKQualquer();
toastMessage("position: " + position);
//toastMessage("fillupPosition: " + fillupPosition);
//long fillupPosition = adapterView.getItemIdAtPosition(i);
Log.d(TAG, "onItemClick: You Clicked on " + fillupID);
Cursor data = db.getDataTableFillup(fillupID);//get the data associated with that fillupID
fillupID = -1;
while (data.moveToNext()) {
fillupID = data.getInt(0);
vehicleID = data.getInt(1);
fillupDate = data.getString(2);
odometer = data.getLong(3);
kmDriven = data.getLong(4);
liters = data.getLong(5);
consumption = data.getLong(6);
label = data.getString(7);
sequence = data.getInt(8);
}
if (fillupID > -1) {
Log.d(TAG, "onItemClick: The ID is: " + fillupID);
Intent screenVehicle = new Intent(Vehicle_painel.this, Fillup_edit.class);
screenVehicle.putExtra("fillupID", fillupID);
screenVehicle.putExtra("vehicleID", vehicleID);
screenVehicle.putExtra("vehicleName", selectedName);
screenVehicle.putExtra("date", fillupDate);
screenVehicle.putExtra("odometer", odometer);
screenVehicle.putExtra("kmDriven", kmDriven);
screenVehicle.putExtra("liters", liters);
screenVehicle.putExtra("consumption", consumption);
screenVehicle.putExtra("label", label);
screenVehicle.putExtra("sequence", sequence);
//toastMessage("fillupPosition: " + fillupPosition);
startActivity(screenVehicle);
} else {
toastMessage("fillupID = " + fillupID);
//db.deleteAllFillup(selectedID);
//toastMessage("No ID associated with that name hahaha");
}
The best thing to do would be to create a custom class to hold your data. That way you no longer just get a simple String value back from your adapter. Your ArrayList would be something like:
ArrayList<YourCustomClass> listData2 ...
Create a custom class "YourCustomClass" (Call it what ever you like). It could look like:
public class YourCustomClass {
private long itemId = 0;
private String itemName;
private String itemDescription;
public YourCustomClass(){
}
public void setItemId(long id){ this.itemId = id; }
public void setItemName(String itemName){ this.itemName = itemName; }
public void setItemDescription(String itemDescription){ this.itemDescription = itemDescription; }
public long getItemId() { return this.itemId; }
public String getItemName(){ return this.itemName; }
public String getItemDescription(){ return this.itemDescription; }
}
Now in your onItemClick method get the Id and the other data like this:
YourCustomClass data = (YourCustomClass) adapterView.getItemAtPosition(i);
long orderId = data.getItemId();
String name = data.getItemName();
You will need a custom adapter to populate your ListView with data.
You can also take a look at this answer. It shows how to change the background color of a ListView item, but also shows more detail of how to implement a custom adapter for your ListView.
How to set background color for each item listview depanding on variable value
I'm making a to do list application, i made a SQLite database and linked it with my app and everything seems to work pretty fine except for the data in the array, they get over each other while creating a new item, like when i set a first task (Study) and a second task (Research) it creates two different items each of them has the name (StudyResearch)... here is my code with the base adapter, cursor, and inflater.
class MyCustomAdapter extends BaseAdapter
{
ArrayList<ListItem> Items=new ArrayList<ListItem>();
MyCustomAdapter(ArrayList<ListItem> Items ) {
this.Items=Items;
}
#Override
public int getCount() {
return (int) DatabaseUtils.queryNumEntries(db, "tasks");
}
#Override
public String getItem(int position) {
return Items.get(position).Name;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
String[] cols = {"id", "name", "time", "date"};
Cursor pointer = db.query("tasks", cols, null,null,null,null,null);
String name = "";
String time = "";
String date = "";
//String data = "";
while (pointer.moveToNext()){
name += pointer.getString(1);
time += pointer.getString(2);
date += pointer.getString(3);
//data += pointer.getInt(0) + " - " + pointer.getString(1) + " - " + pointer.getInt(2) +" - " + pointer.getInt(3);
}
LayoutInflater linflater =getLayoutInflater();
View view1=linflater.inflate(R.layout.row_view, null);
final CheckedTextView tvTasks =(CheckedTextView) view1.findViewById(R.id.tvTasks);
CheckedTextView tvDesc =(CheckedTextView) view1.findViewById(R.id.tvDesc);
tvTasks.setText(name);
tvDesc.setText(date + "(" + time + ")"); //date + "(" + time + ")"
tvTasks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvTasks.toggle();
}
});
return view1;
}
The issue you have is that your are traversing all of the data in the cursor combined with += is concatenating the data retrieved.
Rather what you want to do is position to the appropriate row in the cursor and get the data just from that row (not that I'd recommend this way as a CursorAdapter is better suited).
So instead of :-
while (pointer.moveToNext()){
name += pointer.getString(1);
time += pointer.getString(2);
date += pointer.getString(3);
}
You could use :-
if (pointer.moveToPosition(i)){
name = pointer.getString(1);
time = pointer.getString(2);
date = pointer.getString(3);
}
This does assume that the the order in which the pointer cursor and the source array were built is identical.
There is my class with custom adapater
It's working with date and title.
Date and title are with table Page and textTag with Table Tag
public class MyAdapter extends ArrayAdapter <PageTag> {
Context context;
int ressource;
ArrayList<Page> data ;
TextView tvTitreList;
TextView tvDateList;
TextView tvTagList;
Page page;
public MyAdapter(Context context, ArrayList <PageTag> data ) {
super(context, 0, data);
}
My getView method.
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_list_perso, parent, false);
}
tvTitreList = (TextView) convertView.findViewById(R.id.tvTitre);
tvDateList = (TextView) convertView.findViewById(R.id.tvDate);
tvTagList = (TextView) convertView.findViewById(R.id.tvTag);
tvTitreList.setText(getItem(position).getPage().titrePage);
tvDateList.setText(getItem(position).getPage().datePage.toString());
tvTagList.setText(getItem(position).getTag().texteTag);
return convertView;
}
}
My table PageTag
public class PageTag {
Page page ;
Tag tag ;
public PageTag ( Page page, Tag tag){
this.page = page;
this.tag = tag;
}
// with getter and setter
my ListPageActivity
pageMgr = new PageMgr(this);
lvList = (ListView) findViewById(R.id.listPage);
ArrayList<Page> listPage = pageMgr.getAllPageArray();
ArrayList<Tag> listTag = pageMgr.getAllTagArray();
ArrayList<PageTag> pageTag = new ArrayList<>();
for(int i = 0 ;i < listPage.size() ;i++){
Page page = listPage.get(i);
Tag tag = listTag.get(i);
(cannot resolve method) ==> pageTag.setPage(page);
==> pageTag.setTag(tag);
}
MyAdapter myAdapt = new MyAdapter(this,pageTag);
lvList.setAdapter(myAdapt);
getAllpageArray method
public ArrayList<Page> getAllPageArray(){
ArrayList <Page> listPageArray = new ArrayList <Page>();
String rqPage = " SELECT * FROM " + BaseSQLITE.TABLE_PAGE
+ " JOIN " + BaseSQLITE.TABLE_LIENS_TAG_PAGE
+ " ON " + BaseSQLITE.TABLE_PAGE+ "." + BaseSQLITE.COL_ID_PAGE + " = " + BaseSQLITE.TABLE_LIENS_TAG_PAGE+ "." + BaseSQLITE.COL_ID_PAGE_LTP
+ " JOIN " + BaseSQLITE.TABLE_TAG
+ " ON "+ BaseSQLITE.TABLE_TAG+ "." + BaseSQLITE.COL_ID_TAG + " = " + BaseSQLITE.TABLE_LIENS_TAG_PAGE+ "." + BaseSQLITE.COL_ID_TAG_LTP ;
Cursor cPage;
this.open();
cPage = bdd.rawQuery(rqPage,null);
Date date;
long l;
String titre;
while (cPage.moveToNext()){
String titrePage ;
Date datePage ;
l = cPage.getLong(2);
titrePage = cPage.getString(1);
datePage = new Date(l);
listPageArray.add(new Page(titrePage,datePage));
}
this.close();
return listPageArray;
}
same thing for getAllTagArray
Create a new Model class
class Result{
Page page;
Tag tag;
//getters and setters
}
Now loop your result and add it to List of Result
ArrayList<Result> result = new ArrayList<>();
for(int i=0 ;i < listPage.size() ;i++){
Page page = listPage.get(i);
Tag tag = tagList.get(i);
result.setPage(page);
result.setTag(tag);
}
In your adapter change Page to Result
tvTitreList.setText(getItem(position).getPage().getTitrePage());
tvDateList.setText(getItem(position).getPage().getDatePage().toString());
tvTagList.setText(getItem(position).getTag().getTextTag());
Finally it's ok with your method I have changed some code.
thanks to you #rajan ks
pageMgr = new PageMgr(this);
lvList = (ListView) findViewById(R.id.listPage);
ArrayList<Page> listPage = pageMgr.getAllPageArray();
ArrayList<Tag> listTag = pageMgr.getAllTagArray();
ArrayList<PageTag> pageTag = new ArrayList<>();
for(int i = 0 ;i < listPage.size() ;i++) {
Page page = listPage.get(i);
Tag tag = listTag.get(i);
PageTag pageT = new PageTag(page, tag);
pageTag.add(pageT);
}
MyAdapter myAdapt = new MyAdapter(this,pageTag);
lvList.setAdapter(myAdapt);
I just want to know how to, if a Hashmap is already on the list add 1 to quantity, if it is not then add it to list. This is what I've done that just add eventhough the item is already on list.
list = new ArrayList<HashMap<String, String>>();
Cursor c = db.rawQuery("SELECT code,desc,price FROM TbLPrice WHERE code =" + txtCode.getText().toString(), null); //search database
if (c.moveToFirst()){ //if successful
txtDesc.setText(c.getString(1)); //get desc
txtPrice.setText(c.getString(2)); // get price # database
HashMap<String, String> map = new HashMap<String, String>();
map.put("desc", c.getString(1));
map.put("price", c.getString(2));
map.put("quantity","1");
list.add(map);
adapter.notifyDataSetChanged();
From your last comment, I think I see what you're trying to do. Firstly, I would create a small class holding the information about your items, to make it a bit easier to work with (I've only implemented the necessary setters, you'll probably want some getters (and other functions) as well):
public class MyItem
{
String description;
float price;
int quantity;
public void setDescription(String description)
{
this.description = description;
}
public void setPrice(float price)
{
this.price = price;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public void increaseQuantity()
{
this.quantity++;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((description == null) ? 0 : description.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyItem other = (MyItem) obj;
if (description == null)
{
if (other.description != null)
return false;
}
else if (!description.equals(other.description))
return false;
return true;
}
}
I have implement the equals method (and it is common to then also implement the hash method) to easily be able to check if an item exists in the list (for simplicity, I assume that the description uniquely identifies an item, you should change this as needed). You can then continue with your processing like this:
public void queryForItem(String itemCode)
{
Cursor cursor = db.rawQuery("SELECT code,desc,price FROM TbLPrice WHERE code =" + itemCode, null);
if (cursor.moveToFirst())
{
processCursor(cursor);
}
cursor.close();
}
private void processCursor(Cursor c)
{
MyItem newItem = new MyItem();
newItem.setDescription(c.getString(1));
newItem.setPrice(c.getFloat(2));
newItem.setQuantity(1);
// assuming that items (ArrayList<MyItem>) is defined and initialized earlier in the code
int existingItemIndex = items.indexOf(newItem);
if (existingItemIndex >= 0)
{
items.get(existingItemIndex).increaseQuantity();
}
else
{
items.add(newItem);
}
adapter.notifyDataSetChanged();
}
I haven't tested this in any way, but I thing it should do what you want. Hope you're able to see the logic in it :)
I came up with this solution, however if an item exist it only update the quantity 2 times on 3rd try It creates new list item with same desc, price but 1 quantity.
Cursor c = db.rawQuery("SELECT code,desc,price FROM TbLPrice WHERE code =" + txtCode.getText().toString(), null); //search database
if (c.moveToFirst()){ //if successful
txtDesc.setText(c.getString(1)); //get desc
txtPrice.setText(c.getString(2)); // get price # database
HashMap<String, String> map = new HashMap<String, String>();
map.put("desc", c.getString(1));
map.put("price", c.getString(2));
if(list.isEmpty()){
map.put("quantity","1");
list.add(map);
adapter.notifyDataSetChanged();
}
else{
if(list.contains(map)){
int loc = list.indexOf(map);
Object o = list.get(loc);
#SuppressWarnings("unchecked")
HashMap<String, String> map2 = (HashMap<String, String>)o;
String b = (String) map2.get("quantity");
int quantity = Integer.parseInt(b) + 1;
map2.put("quantity", Integer.toString(quantity));
adapter.notifyDataSetChanged();
}
else{
map.put("quantity","1");
list.add(map);
adapter.notifyDataSetChanged();
}
I have some result of array-list after I display the value through looping like this
{First=00157300-SPT R.ALONSO (M) D.GREEN, Fourth=360010.0, Second=10, Third=360000}
And I got that result from :
for(int i = 0; i<list.size(); i++){
Log.d("List Result :", String.valueOf(list.get(i)));
}
I create that arraylist from :
HashMap temp = new HashMap();
temp.put(FIRST_COLUMN, valueSpinner);
temp.put(SECOND_COLUMN, count);
temp.put(THIRD_COLUMN, price);
temp.put(FOURTH_COLUMN, total);
list.add(temp);
I create FIRST_COLUMN, SECOND_COLUMN,THIRD_COLUMN and FOURTH_COLUMN from Constant.java :
public class Constant {
public static final String FIRST_COLUMN = "First";
public static final String SECOND_COLUMN = "Second";
public static final String THIRD_COLUMN = "Third";
public static final String FOURTH_COLUMN = "Fourth";
}
And I use import to MainActivity.java :
import static com.testing.informationsystem.Constant.FIRST_COLUMN;
import static com.testing.informationsystem.Constant.SECOND_COLUMN;
import static com.testing.informationsystem.Constant.THIRD_COLUMN;
import static com.testing.informationsystem.Constant.FOURTH_COLUMN;
How can I get just the 00157300-SPT R.ALONSO (M) D.GREEN and 360010.0 ?
Thank you.
Well it seems as though you're adding a Map to the list, so you end up printing the Map's toString method. There probably isn't any need to have the Map in a list like that but I'll assume it should be. What you want to do is request the key-value pairs from the map instead of working with the toString method.
for(int i = 0; i < list.size(); i++)
{
HashMap temp = list.get(i);
Log.d("List Result :", "index " + i);
Log.d("List Result :", "First = " + temp.get(FIRST_COLUMN));
Log.d("List Result :", "Second = " + temp.get(SECOND_COLUMN));
Log.d("List Result :", "Third= " + temp.get(THIRD_COLUMN));
Log.d("List Result :", "Forth= " + temp.get(FOURTH_COLUMN));
}