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
}
Related
I'm parsing a JSON string in Android which looks like this:
[
{
"id":70,
"selection":"25"
},
{
"id":71,
"selection":"50"
},
{
"id":72,
"selection":"50"
}
]
Now I want to get the total count of all selection and display it inside a textview. Can anyone give me an example how to do this, or any tutorial about this?
For example:
selection 25 = 1
selection 50 = 2
Thanks for any help!
I think what you're looking for is something like this:
JsonArray selections = new JsonArray(); // This is your parsed json object
HashMap<Integer, Integer> count = new HashMap<>();
for (JsonElement element : selections) {
JsonObject jsonObject = element.getAsJsonObject();
if(jsonObject.has("selection")) {
int selValue = jsonObject.get("selection").getAsInt();
if(count.containsKey(selValue)) {
count.put(selValue, count.get(selValue) + 1);
} else {
count.put(selValue, 1);
}
}
}
What this will do is loop over your json array and get the value of each selection element. To keep track of the count it increments the count inside of the count hashmap.
You can then get the count for a specific value from the hashmap:
count.get(25); // returns 1
count.get(50); // returns 2
// etc...
If you are using Jackson in Java 8, you can first convert the given JSON string to List<Map<String, Object>>, then transform it into List<Integer> for selection. Finally, you can count occurrences in this list as follows:
ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object>> jsonObj = mapper.readValue(jsonStr, new TypeReference<List<Map<String, Object>>>(){});
Map<Integer, Long> counted = jsonObj.stream()
.map(x -> Integer.valueOf(x.get("selection").toString()))
.collect(Collectors.toList())
.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(counted.toString());
Console output:
{50=2, 25=1}
ArrayList<String> data = new ArrayList<>();
ArrayList<String> datacount = new ArrayList<>();
jsonStr = "Your JSON"
JSONArray jsonArr= null;
try {
jsonArr = new JSONArray(jsonStr);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
//here you can set to TextView
String selection = jsonObj.getString("selection");
//System.out.println("adcac"+selection);
if (data.contains(selection)) {
int index = data.indexOf(selection);
int count = Integer.parseInt(datacount.get(index))+1;
// System.out.println("Index==="+index+"---count---"+count);
datacount.set(index,String.valueOf(count));
} else {
datacount.add(String.valueOf(1));
data.add(selection);
}
// Here you can get data and data count...
// System.out.println("data---"+datacount.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
you can get the array of the json and iterate and calculate the sum of the selection
JSONArray selections = jsonObj.getJSONArray("selections");
// looping through All Selections
int totalCount = selections.length();
Why doesn't anybody use Json Path to solve this in two lines?
I am trying to add Objects from MySQL database on ArrayList Object but result gives me only one row
i am using custom adapter on my ListView, i think i could use loop multiple objects to ArrayList object but i failed , please help me,
my code :
String driver_fullname = json.getString("driver_fullname");
String driver_phonenumber = json.getString("driver_phonenumber");
String plate_no = json.getString("plate_no");
String parking_name = json.getString("parking_name");
List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>();
PaymentTiming_Items timingItems = new PaymentTiming_Items();
timingItems.setPlateNo(plate_no);
timingItems.setParkingName(parking_name);
timingItems.setDriverFullName(driver_fullname);
getAllDiverDetails.add(timingItems); // store all drivers' info to
}
if (getAllDiverDetails.size() !=0) {
userList = new ArrayList<> (getAllDiverDetails);
listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList);
myList.setAdapter(listAdapter);
}
Looks like you are creating an ArrayList everytime you parse an object. If I understand correctly, your code should be something like that:
// ArrayList will be created only once for a json response.
List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>();
//Now parse add all elements in json response and add to list.
for(all items in your jsonResponse List ) {
//Parse fields from json object
String driver_fullname = json.getString("driver_fullname");
String driver_phonenumber = json.getString("driver_phonenumber");
String plate_no = json.getString("plate_no");
String parking_name = json.getString("parking_name");
//create object
PaymentTiming_Items timingItems = new PaymentTiming_Items();
timingItems.setPlateNo(plate_no);
timingItems.setParkingName(parking_name);
timingItems.setDriverFullName(driver_fullname);
getAllDiverDetails.add(timingItems); // store all drivers' info to
}
//Now list will have all the items, Add this list to adapter.
if (getAllDiverDetails.size() !=0) {
userList = new ArrayList<>(getAllDiverDetails);
listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList);
myList.setAdapter(listAdapter);
}
Suppose Your Server gives a result in JSONArray say response as a String Try the following
List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>();
JSONArray jsonArray = new JSONArray(response);
int size = jsonArray.length();
if (size > 0)
{
for (int i = 0; i < size; i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String driver_fullname = json.getString("driver_fullname");
String driver_phonenumber = json.getString("driver_phonenumber");
String plate_no = json.getString("plate_no");
String parking_name = json.getString("parking_name");
PaymentTiming_Items timingItems = new PaymentTiming_Items();
timingItems.setPlateNo(plate_no);
timingItems.setParkingName(parking_name);
timingItems.setDriverFullName(driver_fullname);
getAllDiverDetails.add(timingItems); // store all drivers' info to
}
}
if (getAllDiverDetails.size() !=0) {
userList = new ArrayList<> (getAllDiverDetails);
listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList);
myList.setAdapter(listAdapter);
}
You must use JSONArray for getting list of items from JSON. And then populate your ArrayList with them and pass to your adapter.
I want to save data into master - details table.First portion is for master table and last portion is for details table.I have got java.lang.String cannot be cast to [Ljava.lang.String .How to recover from this problem.How to assign map.get("step_id[]") into a string array String[] WfIds. I want to assign each value into distinct string array.
Controller Code
Map<String,Object> wfManager = new HashMap<String,Object>();
//************************Master data sent from view******************************//
wfManager.put("workflow_code",(request.getParameter("workflow_code")).toUpperCase());
wfManager.put("workflow_name",request.getParameter("workflow_name"));
wfManager.put("workflow_descr",request.getParameter("workflow_descr"));
wfManager.put("object_type_code",request.getParameter("object_type_code"));
//*********************Detail item data sent from view********************************//
wfManager.put("wf_block_id[]", request.getParameter("wf_block_id[]"));
wfManager.put("step_code[]" , request.getParameter("step_code[]"));
wfManager.put("step_name[]", request.getParameter("step_name[]"));
wfManager.put("doa_type_code[]", request.getParameter("doa_type_code[]"));
wfManager.put("doa_type_name[]", request.getParameter("doa_type_name[]"));
Service Code
public Map<String, String> insert(Map<String, Object> map) {
//************************Master data sent from view******************************//
Map<String, String> data = new HashMap<String, String>();
Workflow wf = new Workflow();
wf.setWorkflowCode((String)map.get("workflow_code"));
wf.setWorkflowName((String)map.get("workflow_name"));
wf.setWorkflowDescr((String)map.get("workflow_descr"));
wf.setObjectTypeCode((String)map.get("object_type_code"));
String[] WfIds = (String[]) map.get("step_id[]");
String[] wfBlockIds = (String[]) map.get("wf_block_id[]");
String[] wfsCodes = (String[]) map.get("step_code[]");
String[] stepNames = (String[]) map.get("step_name[]");
String[] doaTypeCodes = (String[]) map.get("doa_type_code[]");
String[] doaTypeNames = (String[]) map.get("doa_type_name[]");
List<WorkflowDetails> wfDetailsList = new ArrayList<WorkflowDetails>();
for(int i = 0; i< wfsCodes.length; i++){
WorkflowDetails wfDetails = new WorkflowDetails();
wfDetails.setWorkflowCode(wf.getWorkflowCode());
wfDetails.setWorkflowName(wf.getWorkflowName());
wfDetails.setWorkflowDescr(wf.getWorkflowDescr());
wfDetails.setWorkflowObjectTypeCode(wf.getObjectTypeCode());
wfDetails.setWorkflowObjectTypeName(wf.getObjectTypeName());
wfDetailsList.add(i,wfDetails);
}
wf.setSteps(wfDetailsList);
id = workflowManagerDAO.insertDoc(wf);
data.put("id", id);
return data;
}
Code for DAO:
#Transactional
#Override
public String insertDoc(Workflow wfManager) {
for(int i = 0; i < wfManager.getSteps().size(); i++){
WorkflowDetails wfDetails = new WorkflowDetails();
wfDetails = wfManager.getSteps().get(i);
sessionfactory.getCurrentSession().save(wfDetails);
sessionfactory.getCurrentSession().flush();
}
String id = (String) sessionfactory.getCurrentSession().save(wfManager);
sessionfactory.getCurrentSession().flush();
return id;
}
If you absolutely need to use request.getParameter(), you will have to convert your arrays to strings using a delimiter character, e.g. convert this
String[] array = { "John", "Peter", "Paul" };
to this
String plainTextArray = "John#Peter#Paul";
Then you will be able to pass you array values as String (the only type that getParameter() understands).
You can then restore them like this
String[] restoredArray = request.getParameter("plainTextArray").split("#");
Maybe you want to have a look at setAttribute() and getAttribute() which let you store any objects (including arrays). You can start here Difference between getAttribute() and getParameter()
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.
Query query = s.createQuery("from ClientList");
List <String> results = query.list();
Iterator<String> it = results.iterator();
while(it.hasNext())
{
Object[] row = (Object[]) it.next();
System.out.println("ReturnValues==========" + results);
Map<String, String> jsonObject = new HashMap<String, String>();
jsonObject.put("Record_Id", (String) row[0]);
jsonObject.put("Client_Code", (String)row[1]);
jsonObject.put("Client_Description", (String)row[2]);
returnValues.add(jsonObject);
}
The first column of my table contains an integer value. I'm getting this error message:
Exception===java.lang.ClassCastException: cannot be cast to [Ljava.lang.Object;
Your itetator returns a string. You can't cast it to an array of object.
There is a split method in string, it splits your string by given regex and returns a String[] containing the split parts.
Since you provided no more information on that, I'm going to assume that the data in your row is separated by spaces.
String row = ll.next() // I assume row = "1234 5678 Description_No_Spaces"
String[] data = row.split("\\s+");
String record_Id = data[0];
You don't need an iterator, you can loop through results with foreach loop.
List <String> results =query.list();
for(String result: results) {
String[] row = /* user result.split(...) to get attributes*/
System.out.println("ReturnValues=========="+results);
Map<String, String> JSonObject=new HashMap<String, String>();
JSonObject.put("Record_Id", row[0]);
JSonObject.put("Client_Code", row[1]);
JSonObject.put("Client_Description",row[2]);
ReturnValues.add(JSonObject);
}
Check out String.split(String regex) docs.
Query query = s.createQuery("from ClientList");
List <String> results = query.list();
Iterator<String> it = results.iterator();
while(it.hasNext())`enter code here`
{
Object[] row = (Object[]) it.next();
System.out.println("ReturnValues==========" + results);
Map<String, String> jsonObject = new HashMap<String, String>();
jsonObject.put("Record_Id", String.valueOf(row[0]));
jsonObject.put("Client_Code", row[1]);
jsonObject.put("Client_Description", row[2]);
returnValues.add(jsonObject);
}
Hope this solves your problem