Unable to fetch data from Hashmap properly - android

I have an Arraylist of HashMap. Each HashMap element contains two columns: column name and corresponding value. This HashMap will be added into a ListView with 3 TextView.
I populate the ArrayList as follows, and then assign that to an adapter in order to display it:
ArrayList<HashMap<String, String>> list1 = new ArrayList<HashMap<String, String>>();
HashMap<String, String> addList1;
for (int i = 0; i < count; i++) {
addList1 = new HashMap<String, String>();
addList1.put(COLUMN1, symbol[i]);
addList1.put(COLUMN2, current[i]);
addList1.put(COLUMN3, change[i]);
list1.add(addList1);
RecentAdapter adapter1 = new RecentAdapter(CompanyView.this,
CompanyView.this, list1);
listrecent.setAdapter(adapter1);
}
.
Now on listItemClick, the fetched data is of the different form at different time.
For eg. My list contains following data:
ABC 123 1
PQR 456 4
XYZ 789 7
i.e. When I log the fetched string after clicking 1st list item, I get one of the several outputs:
{1=ABC ,2=123 ,3=1}
{First=ABC ,Second=123 ,Third=1}
{1=123 ,0=ABC ,2=1}
and even
{27=123 ,28=1 ,26=ABC}
Initially I used:
int pos1 = item.indexOf("1=");
int pos2 = item.indexOf("2=");
int pos3 = item.indexOf("3=");
String symbol = item.substring(pos1 + 2,pos1 - 2).trim();
String current = item.substring(pos2 + 2, pos3 - 2).trim();
String change = item.substring(pos3 + 2, item.length() - 1).trim();
Then for the 4th case, I have to use:
int pos1 = item.indexOf("26=");
int pos2 = item.indexOf("27=");
int pos3 = item.indexOf("28=");
String symbol = item.substring(pos1 + 3, item.length() - 1).trim();
String current = item.substring(pos2 + 3, pos3 - 3).trim();
String change = item.substring(pos3 + 3, pos1 - 3).trim();
So that I get ABC in symbol and so on.
But, by this approach, application loses it's reliability completely.
I also tried
while (myVeryOwnIterator.hasNext()) {
key = (String) myVeryOwnIterator.next();
value[ind] = (String) addList1.get(key);
}
But it's not giving proper value. Instead it returns random symbol for eg. ABC or PQR or XYZ.
Am I doing anything wrong?
Thanks in advance!

The HashMap's put function does not insert value in specific order. So the best way is to put the keyset of the HashMap in a ArrayList and use the ArrayList index in retrieving the value
ArrayList<HashMap<String, String>> list1 = new ArrayList<HashMap<String, String>>();
HashMap<String, String> addList1;
ArrayList<String> listKeySet;
for (int i = 0; i < count; i++) {
addList1 = new HashMap<String, String>();
addList1.put(COLUMN1, symbol[i]);
addList1.put(COLUMN2, current[i]);
addList1.put(COLUMN3, change[i]);
listKeySet.add(COLUMN1);
listKeySet.add(COLUMN2);
listKeySet.add(COLUMN3);
list1.add(addList1);
RecentAdapter adapter1 = new RecentAdapter(CompanyView.this,
CompanyView.this, list1);
listrecent.setAdapter(adapter1);
}
And when retrieving use
addList1.get(listKeySet.get(position));
Here, the arraylist listKeySet is just used to preserve the order in which the HashMap keys are inserted. When you put data in HashMap insert the key into the ArrayList.

I don't think using HashMap for this purpose is a good idea. I would implement Class incapsulating your data like
class myData {
public String Column1;
public String Column2;
public String Column3;
// better idea would be making these fields private and using
// getters/setters, but just for the sake of example these fields
// are left public
public myData(String col1, String col2, String col3){
Column1 = col1;
Column2 = col2;
Column3 = col3;
}
}
and use it like
ArrayList<myData> list1 = new ArrayList<myData>();
for (int i = 0; i < count; i++) {
list1.add(new myData(symbol[i], current[i], change[i]));
}
//no need to create new adapter on each iteration, btw
RecentAdapter adapter1 = new RecentAdapter(CompanyView.this,
CompanyView.this, list1);
listrecent.setAdapter(adapter1);
You will need to make changes in your adapter to use myData instead of HashMap<String,String>, of course.

Related

Can I populate a listView with a nested array using Simpleadapter and hashmap?

I'm trying to populate a ListView using a HashMap and a SimpleAdapter from a nested array with 12 columns and 12 rows
So here is my code
try {
String [][] array2 = new String[cursor.getCount()][cursor.getColumnCount()];
cursor.moveToFirst();
for (int i =0; i<cursor.getCount();i++){
for(int j = 0; j < cursor.getColumnNames().length; j++) {
String uname = cursor.getString(j);
array2[i][j]=uname;
}
cursor.moveToNext();
}
} finally {
cursor.close();
}
and then the simple adapter with hashmap
int[] to = new int[]{R.id.item2, R.id.item3, R.id.item4, R.id.item5, R.id.item6, R.id.item7, R.id.item8 ,R.id.item9, R.id.item10, R.id.item11, R.id.item12};
List<HashMap<String,String>> fillMaps = (List<HashMap<String, String>>) new ArrayList<HashMap<String, String>>();
for(int i = 0; i<10;i++){
HashMap<String,ArrayList> map = new HashMap<String, ArrayList>();
}
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.grid_item, array2, to);
when I try this I get an error
SimpleAdapter(android.content.Context, java.util.List<? extends java.util.Map<java.lang.String,?>>, int, java.lang.String[], int[])' in android.widget.SimpleAdapter cannot be applied to
(com.example.thevenom1215.prueba.MainActivity, java.util.List<java.util.HashMap<java.lang.String, java.lang.String>>, int, java.util.ArrayList<java.lang.String>, int[])
Or I thought that I could convert the nested array to a simple array is that possible? If so how can I accomplish that? I tried this
String from [] = new String from[252]:
from[0]= array[0][1]+"|"+array[0][2]+"|"+array[0][3]+......+array[0][12];
but it doesn't work.
In the array2, which is array2[12][21], every row has 12 columns, which are information of a person, for example (name, age)
Cesar Joel Gurrola, xx
The first row of the array is: [Cesar, Joel, Gurrola, xx]
I need that in an array because further in my code I need String by String and not a whole String "Cesar, Joel, Gurrola, xx"
Sql query
sql="select b.CVE_CONTR, r.NO_RECIBO , a.NOM_SOLICIT ,r.NO_PARCIAL ,r.SDO_TOTAL, r.STS_PAGO ,a.AP_PATSOLICIT,a.AP_MATSOLICIT, " +
"f.DESCRIPCION, b.NO_PARCIALID , b.PAGO_PARCIAL, b.TOT_APAG from MFRF_M_SOLICITANTES a, MFRF_M_CONTPREV_H b, MFRF_M_CONTPREV_D_RECGEN_2 r," +
"C_PAQUETE f , C_PARCIALIDADES g, MFRF_C_COLONIAS c where b.CVE_CONTR = '"+etnumcontrato.getText().toString() + "' and r.STS_PAGO in ('1','10','11','12')" +
"and c.ID_COLONIA = a.ID_COLONIA and f.ID_PAQUETE = b.ID_PAQUETE and g.ID_PARCIALIDAD = b.ID_PARCIAL AND a.ID_SOLICIT = b.ID_SOLICITANTE ";
Overall, I wouldn't recommend this.
String [][] array2 = new String[cursor.getCount()][cursor.getColumnCount()];
An adapter displays one row-item at a time, not the whole table.
I would instead recommend a CursorAdapter since you do have a Cursor object, but I'll continue with a SimpleAdapter.
First, you need to create an XML layout, let it be named item_layout.xml. It contains all the Views that you want to bind the row from the database to. I believe these must all be TextViews for a SimpleAdapter.
String[] from = new String[] {"rowid", "fname", "mname", "lname"};
int[] to = new int[] { R.id.item1, R.id.item2, R.id.item3, R.id.item4 };
Then, loop over the rows of the cursor, and pull out the necessary information into a List of HashMaps. Note: this is one row of data each time that we are looping over the cursor results. And, as described earlier, you only have TextViews, so you can only store String values.
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
final int rows = cursor.getCount();
for (int i = 0; i < rows; i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("rowid", "" + i);
map.put("fname", cursor.getString(cursor.getColumnIndexOrThrow("fname"));
map.put("mname", cursor.getString(cursor.getColumnIndexOrThrow("mname"));
map.put("lname", cursor.getString(cursor.getColumnIndexOrThrow("lname"));
fillMaps.add(map);
cursor.moveToNext();
}
Now that you have looped over all the rows of the data and are satisfied with that data, you just set the adapter.
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps,
R.layout.item_layout,
from, to);
listView.setAdapter(adapter);

How to get items from Listadapter in android?

I have a Listadapter wherein there are 4 different strings, and storing them to my listview. Now I want to get all the items from one of those strings and parse it to "date", so how can I able to populate my calendar dates from my listadapter?
Following the codes:
// Get User records from SQLite DB
ArrayList<HashMap<String, String>> eventsList = controller.getAllevents();
// If users exists in SQLite DB
if (eventsList.size() != 0) {
// Set the User Array list in ListView
ListAdapter adapter = new SimpleAdapter(CalendarActivity.this, eventsList, R.layout.calendar_event_list, new String[]{TAG_PID,
TAG_EVENTTITLE,TAG_EVENTSTART,TAG_EVENTEND},
new int[]{R.id.pid, R.id.eventname, R.id.eventstart, R.id.eventend});
ListView myList = (ListView) findViewById(android.R.id.list);
myList.setAdapter(adapter);
String eventstart = adapter.toString(); //I got null exception here..
Date edate = ParseDate(eventstart);
if (caldroidFragment != null) {
caldroidFragment.setBackgroundResourceForDate(R.color.Green, edate);
caldroidFragment.refreshView();
}
}
If you want to fetch an item from your adapter you can use
adapter.getItem(position);
which will return the item at the specified position. In your case, that method will return the HashMap<String, String> at the specified position:
Example:
/* adapter.getCount() returns the count of how many items
(HashMaps, in your case) that is represented in this adapter. */
for(int i = 0; i < adapter.getCount(); i++){
HashMap<String, String> myHashMap = adapter.getItem(i);
//"myKey" is the key that you provided, when mapping your key-values
String myVal = myHashMap.get("myKey");
Date edate = ParseDate(myVal);
/* Handle your Date object here. I'm just printing it to the console
in this example. */
System.out.println("Item at position " + i + " " + edate.toString());
}
Problem solved! Just simply put inside the loop and change the 'position' variable into the variable that handles the loop e.g for (int i = 0; i < eventsList.size(); i++) change adapter.getItem(position) to adapter.getItem(i)

Show data with hidden ID with android

I have JSONArray with several JSONObjects and each JSONObject contains Name and ID. How can I show only the name and leave the ID hidden. I need to be able to get the ID afterwards by knowing which row was pressed. I don't care how to show it, with list view, table, grid or whatever. This is how I get the data from the JSONArray:
for (int i = 0; i < ans.length(); i++) {
int id = Integer.parseInt(ans.getJSONObject(i).getString("UserID"));
String disName = ans.getJSONObject(i).getString("DisplayName");
adapter.add(disName + " - " + id);
}
Thank you in advance
After the first answer I created a Class name DisNameID containing diaplyName and ID and the toString is return displayName. The listView on this activity is called "frndLst". This is the code that should fill the listview:
ListView lstFrnd = (ListView) findViewById(R.id.frndLst);
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(this, android.R.layout.XXX, listItems);
for (int i = 0; i < ans.length(); i++) {
int id = integer.parseInt(ans.getJSONObject(i).getString("UserID"));
String disName = ans.getJSONObject(i).getString("DisplayName");
DisNameID dis = new DisNameID(disName, id);
adapter.add(disName + " - " + id);
}
Now I have 2 new questions: How to change the adapter to hold my new class - DisNameID? What to write instead of the XXX on the new adapter constructor?
Create Holder object, override toString:
class Holder {
private String name;
private String id;
//getters and setters;
public String toString(){ return name };
}
Then add such objects to your adapter. This way, the name will be displayed, but you can get Holder objects from your adapter using this method and use the id.

Using a variable to switch to a certain spinner item

I have:
a String array with an unknown length that's populated with unknown items (let's say fish, bird, cat)
an ArrayAdapter and a Spinner that displays the items
a variable that contains one unknown item from the string array (let's say cat)
I want to set the Spinner to the value from the variable (cat). What's the most elegant solution? I thought about running the string through a loop and comparing the items with the variable (until I hit cat in this example), then use that iteration's # to set the selection of the Spinner, but that seems very convoluted.
Or should I just ditch the Spinner? I looked around and found a solution that uses a button and dialog field: https://stackoverflow.com/a/5790662/1928813
//EDIT: My current code. I want to use "cow" without having to go through the loop, if possible!
final Spinner bSpinner = (Spinner) findViewById(R.id.spinner1);
String[] animals = new String[] { "cat", "bird", "cow", "dog" };
String animal = "cow";
int spinnerpos;
final ArrayAdapter<String> animaladapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, animals);
animaladapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bSpinner.setAdapter(animaladapter);
for (Integer j = 0; j < animals.length; j++) {
if (animals[j].equals(animal)) {
spinnerpos = j;
bSpinner.setSelection(spinnerpos);
} else {
};
}
(Temporarily) convert your String array to a List so you can use indexOf.
int position = Arrays.asList(array).indexOf(randomVariable);
spinner.setSelection(position);
EDIT:
I understand your problem now. If your String array contains all unique values, you can put them in a HashMap for O(1) retrieval:
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < animals.length; i++) {
map.put(animals[i], i);
}
String randomAnimal = "cow";
Integer position = map.get(randomAnimal);
if (position != null) bSpinner.setSelection(position);

Populating ExpandableListView Header and Child with arrays in Android

I have two string arrays in my resources. First is
arr_song_title contains:
Love on Top
Pricetag
Titanium
It will rain
and second array strings are the artist:
Beyonce
Jessie J.
David Guetta
Bruno Mars
++Header++
--Child
++Header++
--Child
++Header++
--Child
What I want is to place the title as headers in expandable listview and the artist as item.
What I know is to create the header manually and populate it with arrays. How to do this?
Here is my code:
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
String[] a = getResources().getStringArray(R.array.arr_title);
String[] b = getResources().getStringArray(R.array.arr_artist);
for ( String str : a ) {
listDataHeader.add(str);
}
int counter = 0;
List<String> artist = new ArrayList<String>();
for ( String str : b ) {
artist.add(str);
listDataChild.put(listDataHeader.get(counter), artist);
counter = counter + 1;
}

Categories

Resources