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(...)
Related
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.
Im trying to display some json records using a MultiList. I followed what was done here https://www.codenameone.com/manual/graphics.html but mine is returning only one record (Please see this image). The response came from this webservice
Below is my code. Please kindly show me where i'm wrong.
#Override
protected void beforeFormA(Form f) {
Style s = UIManager.getInstance().getComponentStyle("Button");
FontImage p = FontImage.createMaterial(FontImage.MATERIAL_PORTRAIT, s);
EncodedImage placeholder = EncodedImage.createFromImage(p.scaled(p.getWidth() * 3, p.getHeight() * 4), false);
getattractive();//fetch results from webservice and store inside response variable
ArrayList arr = (ArrayList) response.get("results");
for (Object m:arr){
Map ma = (Map)m;
address =(String) ma.get("formatted_address");
name=(String)ma.get("name");
icon=(String)ma.get("icon");
ArrayList<Map<String, Object>> data = new ArrayList<>();
data.add(createListEntry(name,address,icon));
DefaultListModel<Map<String, Object>> model = new DefaultListModel<>(data);
MultiList ml = new MultiList(model);
ml.getUnselectedButton().setIconName("icon_URLImage");
ml.getSelectedButton().setIconName("icon_URLImage");
ml.getUnselectedButton().setIcon(placeholder);
ml.getSelectedButton().setIcon(placeholder);
f.add(BorderLayout.CENTER, ml);
}
}
private Map<String, Object> createListEntry(String name, String addr, String coverURL) {
Map<String, Object> entry = new HashMap<>();
entry.put("Line1", name);
entry.put("Line2", addr);
entry.put("icon_URLImage", coverURL);
entry.put("icon_URLImageName", name);
return entry;
You should fix the indentation. The for loop encapsulates everything so you are looping over all the elements and for X elements you are adding X multi lists.
This is something you would instantly see if you step over the code with a debugger...
done. I moved the line below out of the method and place it inside the class.
ArrayList> data = new ArrayList<>();
public List<Contact> getContacts()
{
SQLiteDatabase db;
String cmd;
List<Contact> name = new ArrayList<Contact>();
db = myDb.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM contact;" , null);
while(cursor.moveToNext())
{
int contactID = Integer.parseInt(cursor.getString(0));
String familyName = cursor.getString(1);
String firstName = cursor.getString(2);
int houseNumber = Integer.parseInt(cursor.getString(3));
String street = cursor.getString(4);
String town = cursor.getString(5);
String country = cursor.getString(6);
String postcode = cursor.getString(7);
int telephoneNumber = Integer.parseInt(cursor.getString(8));
Contact contact = new Contact(contactID,familyName,firstName,houseNumber,street,town,country,postcode,telephoneNumber);
}
Intent intent = new Intent(Database.this,MainActivity.class);
intent.putStringArrayListExtra("contacts", name);
startActivity(intent);
return name;
}
The method putStringArrayListExtra(String, ArrayList<String>) in the type Intent is not applicable for the arguments (String, List<Contact>)
in order to use putStringArrayListExtra(); method, i need to convert List<contact> name to List name, How do i convert it?
thank you
because list of object is actually not a list of strings, the best way as i know is to loop over list and convert each item into a new list of strings :
List<String> stringsList = new ArrayList<>(list.size());
for (Object object : list) {
stringsList.add(Objects.toString(object, null));
}
First Declare a new Array Of Strings.
List<String> newList = new ArrayList<String>(list.size());
newList.addAll(list);
This adds all elements into the new String List. Where list is your previous container.
Also to pass objects between components use Parceble, Android uses Binder to facilitate such communication in a highly optimized way. The Binder communicates with Parcels, which is a message container. The Binder marshals the Parcel to be sent, sends and receives it, and then unmarshals it on the other side to reconstruct a copy of the original Parcel.Please read up on it here.
Seems like you are trying to pass your List<Contacts> to via Intent -
No need to use putStringArrayListExtra() methods as there is putParcelableArrayList() method using which you can pass ArrayList<Contact> directly.
Simply use,
putParcelableArrayList("KEY", your ArrayList<Contact>); // Make sure Contact implementes Parcelable
You can get the ArrayList<Contact> in Receiver Activity -
Bundle b = getIntent().getExtras();
ArrayList<Contact> data = b.getParcelableArrayList("KEY");
However, You can use Serializable instead of Parcelable but Parcelable is recommended as it is like Flash. Here is why?
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()));
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.