SimpleAdapter show same data in while loop - java

I add many data to SQLite but my list view show last data inserted only. all rows have same value.
public void onResume() {
super.onResume();
db = dbHelper.getWritableDatabase();
String[] queryColumns = new String[]{"_id", DBHelper.COL_VEHICLE_TYPE, DBHelper.COL_OPTION_NAME,DBHelper.COL_DATE };
cursor = db.query(DBHelper.TABLE_NAME, queryColumns, null,null,
null,null,null);
HashMap<String,String> map = new HashMap<String,String>();
while(cursor.moveToNext())
{
map.put("vehicle_type", cursor.getString(1));
map.put("date", cursor.getString(3));
lst_driver.add(map);
}
String[] showColumns = new String[]{"vehicle_type", "date"};
int[] views = new int[] {R.id.ColType, R.id.ColDate};
adapter = new SimpleAdapter(DriverActivity.this,lst_driver, R.layout.activity_list_layout, showColumns, views);
lv_driver.setAdapter(adapter);
}
when I run this app it show last DBHelper.COL_VEHICLE_TYPE and DBHelper.COL_DATE after I insert to SQLi like this.
0
9-12-2018
0
9-12-2018
0
9-12-2018
0
9-12-2018
I don't use any update table function in my code. It should show all data from SQLite that are not same values . How should i fix it?

try this:
HashMap<String,String> map;
while(cursor.moveToNext())
{
map = new HashMap<String,String>();
map.put("vehicle_type", cursor.getString(1));
map.put("date", cursor.getString(3));
lst_driver.add(map);
}

Your problem comes from this snippet. The issue is that map is always the same Map instance, and you're just changing what it holds.
HashMap<String,String> map = new HashMap<String,String>();
while(cursor.moveToNext())
{
map.put("vehicle_type", cursor.getString(1));
map.put("date", cursor.getString(3));
lst_driver.add(map);
}
An easy fix would be to use a different map every time:
while(cursor.moveToNext())
{
HashMap<String,String> map = new HashMap<String,String>();
map.put("vehicle_type", cursor.getString(1));
map.put("date", cursor.getString(3));
lst_driver.add(map);
}
By moving the map declaration and initialization inside the while loop, you're guaranteeing that each iteration through the loop uses a different Map instance.

Related

How I can use HashMap with variables? Java sqlite

I have two variables (nom and marc) that come from a database (sqlite). I need to show these variables with a HashMap. I tried the following but it does not work:
private void populateList(String nom, String marc) {
list = new ArrayList<HashMap<String, String>>();
HashMap<String, String> temp = new HashMap<String, String>();
temp.put(FIRST_COLUMN, nom);
temp.put(SECOND_COLUMN, marc);
temp.put(THIRD_COLUMN, "1");
list.add(temp);
}
What am I doing wrong?
In a click event of a button I use a cursor to fetch data from the database:
Cursor c = db.rawQuery("Select * from prod where id_prod = " + id, null);
if (c.moveToFirst()){
do {
String nom = c.getString(1);
String marc = c.getString(2);
populateList(nom, marc);
} while(c.moveToNext());
}
As you can see PopulateList is a method different from the button that I need to send the variables. Maybe that I am doing wrong. Any answer will help. Thanks
Every time that a the populateList() method is called, you create a new instance of the list that you want to render!
Try to remove
list = new ArrayList<HashMap<String, String>>();
from the populateList(...)

Put HashMap<String,String> into ListVIew with section headers

I have a HashMap of this data:
{Chefs Choice=Vegetable Samosa with Yogurt Sauce},
{Chefs Choice=Tomato Red Pepper Chutney},
{Cold Cereal=Miscellaneous/Peripherals}, {Dessert=Cheesecake Slice},
{Dessert=Banana Cream Pie with Caramel Topping}
And now I want to put this data into a ListView that will look like this.
So that the key,s are all section headers and then the values of each key goes in that section header. I thinking of using a base adapter but not quite sure how to get it right. Or if there is a better way for me to organize my data. I am also open to that.
Thanks for the help in advance :)
Here is how I add data:
ArrayList<HashMap<String, String>> blogPosts = new ArrayList<HashMap<String, String>>();
while (eventType != XmlResourceParser.END_DOCUMENT) {
String tagName = xmlData.getName();
HashMap<String, String> blogPost = new HashMap<String, String>();
switch (eventType) {
case XmlResourceParser.START_TAG:
if (tagName.equalsIgnoreCase("day")) {
currentDay = xmlData.getAttributeValue(null, "name");
}
if (tagName.equalsIgnoreCase("meal")) {
currentMeal = xmlData.getAttributeValue(null, "name");
}
if (tagName.equalsIgnoreCase("counter") && currentDay.equalsIgnoreCase(day) && currentMeal.equalsIgnoreCase(meal)) {
mealArray.add(xmlData.getAttributeValue(null, "name"));
counter = xmlData.getAttributeValue(null, "name");
}
break;
case XmlResourceParser.TEXT:
if (currentDay.equalsIgnoreCase(day) && currentMeal.equalsIgnoreCase(meal)) {
if (xmlData.getText().trim().length() > 0) {
Log.i(TAG, blogPost + "");
blogPost.put(counter, xmlData.getText());
blogPosts.add(blogPost);
}
}
break;
case XmlPullParser.END_TAG:
recordsFound++;
break;
}
eventType = xmlData.next();
}
You can store the main header tag as arraylist.
Data structure will be like this:
Main tag of hashmap will be coming from arraylist and its value will be list of hashmap again...
Like tag 'chef choice': vegatable ssamosa and tomato red
// list contain your top header.....
List<String> arr=new ArrayList<String>();
//list to store complete data structure.
List<HashMap<String, List<HashMap<String, String>>>> list =new ArrayList<HashMap<String,List<HashMap<String,String>>>>();
// setting the data structure
HashMap<String, List<HashMap<String, String>>> hash=new HashMap<String, List<HashMap<String,String>>>();
List<HashMap<String, String>> hash1=new ArrayList<HashMap<String,String>>();
HashMap<String, String> hash2=new HashMap<String, String>();
hash2.put("tag", "vegetable");
hash1.add(hash2);
// getting tag from tag list......
hash.put(list.get(i).toString(), hash1);
list.add(hash);

How to get the keys from a LinkedHasMap?

I have a code populating a listView:
JSONArray data = responseData.getJSONArray("data");
String[] values = new String[data.length()];//I wanna get rid of this
LinkedHashMap<String, String> helpData = new LinkedHashMap();
for (int i = 0; i < data.length() ; i++) {
String header = data.getJSONObject(i).getString("glossary_header");
String description = data.getJSONObject(i).getString("gloassary_description");
helpData.put(header, description);
values[i] = header;
Log.d("mylog", "counter" + i);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
I want to pass the keys to Arrayadapter, I was hoping to find a getKeys() method that could magically return an array of key from the map.
KeySet() was close but did not work, what is the proper way to do this. I don't want to use string array. I want to have my pair values together.
You can get like this
Collection<String> values = helpData.keySet();
for (String string : values) {
//
}
Set<String> keys = myArray.keySet();
String[] keysAsArray = keys.toArray(new String[0]);
More detail on the toArray method can be found at http://docs.oracle.com/javase/7/docs/api/java/util/Set.html#toArray(T[])
for (final String key : helpData.keySet()) {
// print data...
}
or
final Iterator<String> cursor = helpData.keySet().iterator();
while (cursor.hasNext()) {
final String key = cursor.next();
// Print data
}

HashMap ArrayList show same value two times in AutoCompleteTextView suggestion

My Code:
// Reading all contacts from database
List<BNICorporateBean> contacts = db.getAllInfo();
// Each row in the list stores country name, currency and email
ArrayList<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for (BNICorporateBean cn : contacts)
{
if(!memId.trim().equalsIgnoreCase(cn.getBNIMemID().trim()))
{
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("name", cn.getMemName());
hm.put("email", cn.getMemEmail() );
hm.put("mem_id", cn.getBNIMemID());
Log.d("Result", cn._MemName+"\n"+cn._MemEmail+"\n"+cn._BNIMemID);
aList.add(hm);
}
memId= cn.getBNIMemID();
//infoArry.add(cn);
}
// Keys used in Hashmap
//String[] from = { "name","email"};
// Ids of views in listview_layout
//int[] to = { R.id.mem_name,R.id.mem_email};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(LoginActivity.this, aList, R.layout.list_member, new String[] { "name","email"},
new int[]{ R.id.mem_name,R.id.mem_email});
/** Setting the adapter to the listView */
autoComplete.setAdapter(adapter);
Takes value from database and my log text show that it returns single value, but don't know why it shows same value two times in list suggestion . Note: for some values it shows once.
I have also print my list and gives perfect result no duplicate values
for(int k=0;k<aList.size();k++)
{
System.out.println(""+aList.get(k));
}
Use it.This may help you
do{
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("name", cn.getMemName());
hm.put("email", cn.getMemEmail() );
hm.put("mem_id", cn.getBNIMemID());
Log.d("Result", cn._MemName+"\n"+cn._MemEmail+" \n"+cn._BNIMemID);
aList.add(hm);
memId= cn.getBNIMemID();
}while(!memId.trim().equalsIgnoreCase(cn.getBNIMemID().trim()));

Why doen't this for loop work?

This is an android app that gets data from two different JSON URLs. Then I want to mix their data and put them in a map. To do so, I use a nested for loop. But the problem is it only show YEARS and SYSTEMDATA2 and not SYSTEMDATA1. I think my nested loop is not correct.
Does anyone know the reason?
for(int i = 0; i < array2System1.length(); i++){
c1 = array2System1.getJSONObject(i);
for(int x = 0; x < array2System2.length(); x++){
c2 = array2System2.getJSONObject(x);
}
//Storing JSON item in a Variable
valueSystem2 = c2.getString(SYSTEMDATA2);
year = c1.getString(YEAR);
valueSystem1 = c1.getString(SYSTEMDATA1);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, valueSystem1);
map.put(SYSTEMDATA2, valueSystem2);
map.put(YEAR, year);
mylist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(Search.this, mylist,
R.layout.list_M,
new String[] {SYSTEMDATA1, SYSTEMDATA2, YEAR}, new int[] {
R.id.systemData1, R.id.systemData2, R.id.years});
mylist.setAdapter(adapter);
}
result should be like
Year value(SYSTEMDATA2) value(SYSTEMDATA1)
Current problem
it does not show one of the values. (SYSTEMDATA1 or SYSTEMDATA2)
http://i40.tinypic.com/2wqykvr.png
NEW UPDATE
//Getting JSON Array
JSONObject myJson1 = jsons[0];
JSONObject myJson2 = jsons[1];
try {
List<Map<String, String>> listValues = new ArrayList<Map<String, String>>();
JSONArray array1C1 = myJson1.getJSONArray("myDATA");
JSONArray array2C1 = array1C1.getJSONArray(1);
JSONArray array1C2 = myJson2.getJSONArray("myDATA");
JSONArray array2C2 = array1C2.getJSONArray(1);
for (int i=0; i<array2C1.length(); i++)
{
JSONObject entryJsonC1 = array2C1.getJSONObject(i);
String val1 = entryJsonC1.getString(SYSTEMDATA1);
String year = entryJsonC1.getString("date");
JSONObject entryJsonC2 = array2C2.getJSONObject(i);
String val2 = entryJsonC2.getString(SYSTEMDATA2);
Map<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, val1);
map.put(SYSTEMDATA2, val2);
map.put(YEAR, year);
listValues.add(map);
}
list = (ListView) findViewById(R.id.list);
String[] adaptersKeys = new String[] {SYSTEMDATA1, SYSTEMDATA2, YEAR};
int[] adapterViews = new int[] {R.id.systemData1, R.id.systemData2, R.id.years};
ListAdapter adapter = new SimpleAdapter(MultiMainActivity.this, listValues, R.layout.list2, adaptersKeys, adapterViews);
list.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now the result is like: YEAR SAME-VALUE SAME-VALUE
for(int i=0; i<array2System1.length(); i++)
{
c1 = array2System1.getJSONObject(i);
year = c1.getString(YEAR);
valueSystem1 = c1.getString(SYSTEMDATA1);
for(int x=0; x<array2System2.length(); x++)
{
c2 = array2System2.getJSONObject(x);
//Storing JSON item in a Variable
valueSystem2 = c2.getString(SYSTEMDATA2);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, valueSystem1);
map.put(SYSTEMDATA2, valueSystem2);
map.put(YEAR, year);
mylist.add(map);
}
}
list = (ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(Search.this, mylist, R.layout.list_M, new String[] {SYSTEMDATA1, SYSTEMDATA2, YEAR}, new int[] {R.id.systemData1, R.id.systemData2, R.id.years});
// Shoudl be list and not mylist
list.setAdapter(adapter);
You need to put all your code in the inner loop. Currently you just close the inner loop - it runs and overwrites c2 and does nothing.
Something like:
for(int i = 0; i < array2System1.length(); i++){
c1 = array2System1.getJSONObject(i);
for(int x = 0; x < array2System2.length(); x++){
c2 = array2System2.getJSONObject(x);
//Storing JSON item in a Variable
valueSystem2 = c2.getString(SYSTEMDATA2);
year = c1.getString(YEAR);
valueSystem1 = c1.getString(SYSTEMDATA1);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, valueSystem1);
map.put(SYSTEMDATA2, valueSystem2);
map.put(YEAR, year);
mylist.add(map);
}
}
The second for loop closes very early. it should be as follows.
for(int x = 0; x < array2System2.length(); x++){
c2 = array2System2.getJSONObject(x);
//Storing JSON item in a Variable
valueSystem2 = c2.getString(SYSTEMDATA2);
year = c1.getString(YEAR);
valueSystem1 = c1.getString(SYSTEMDATA1);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, valueSystem1);
map.put(SYSTEMDATA2, valueSystem2);
map.put(YEAR, year);
mylist.add(map);
} // This is where it should get closed
Otherwise, you are just reassigning the c2 variable and loosing the other values execpt the last value. Now, you will be able to place the valueSystem1, valueSystem2 and YEAR values in map and then added to the list. Hope this helps
List<Map<String, String>> listValues = new ArrayList<Map<String, String>>();
JSONArray jsonArray = new JSONArray(.....); // Contains all the indicators
for (int i=0; i<jsonArray.length(); i++)
{
JSONObject entryJson = jsonArray.getJsonObject(i);
// Check integrity
if (!entryJson.hasKey("country")) throw new Exception("No 'country' key found");
if (!entryJson.hasKey("value")) throw new Exception("No 'value' key found");
if (!entryJson.hasKey("date")) throw new Exception("No 'date' key found");
// Get country
JSONObject countryJson = entryJson.getJsonObject("country");
if (!countryJson.hasKey("value")) throw new Exception("No 'value' key found");
String country = countryJson.getString("value");
// Get population
String population = entryJson.getString("value");
// Get year
String year = entryJson.getString("date");
// Create a new Map
Map<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, country);
map.put(SYSTEMDATA2, population);
map.put(YEAR, year);
// Add to list
listValues.add(map);
}
// Get the ListView
ListView Llist = (ListView) findViewById(R.id.list);
// Create a new adapter to attach this listView
String[] adapterKeys = new String[] {SYSTEMDATA1, SYSTEMDATA2, YEAR};
int[] adapterViews = new int[] {R.id.systemData1, R.id.systemData2, R.id.years};
ListAdapter adapter = new SimpleAdapter(Search.this, listValues, R.layout.list_M, adapterKeys, adapterViews);
// Attach the adapter to the listView
Llist.setAdapter(adapter);
Here is another way that should work better. I haven't tested the code as it was made in notepad. Please tell me if you have any issue.
Because you have defined this:
private static final String SYSTEMDATA1 = "value";
private static final String SYSTEMDATA2 = "value";
//you can't have 2 entries with the same key
private static final String SYSTEMDATA2_KEY = "value2";
The issue appears where you are creating your map:
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, valueSystem1);
map.put(SYSTEMDATA2_KEY, valueSystem2);
map.put(YEAR, year);
A Map is:
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value
From the docs for put() method:
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value.
So you place valueSystem1 using SYSTEMDATA1 as key, which is "value" and then you place valueSystem2 using SYSTEMDATA2 as key, which is ALSO "value", so you are overwriting valueSystem1!
See the edit below...
EDIT:
I'm guessing that to retrieve your values, you must use keys which are "value", that's fine, but to insert in the map later, you must have unique keys. If you still have SYSTEMDATA1="value" and SYSTEMDATA2="value", add one more which you'll use to store in the map and later in the adapter:
//you can't have 2 entries with the same key
private static final String SYSTEMDATA2_KEY = "value2";
// Create a new Map
Map<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, val1);
map.put(SYSTEMDATA2_KEY, val2);
map.put(YEAR, year);
and then, when you set your adapter keys:
// Create a new adapter to attach this listView
String[] adapterKeys = new String[] {SYSTEMDATA1, SYSTEMDATA2_KEY, YEAR};
Code updated in my original answer.

Categories

Resources