I have the json array below which I am parsing and displaying it in listview row wise but I would like to combine/group same users to one row .Should I do it in android or mysql ? I am giving the working code for mysql too .I really appreciate any help.Thanks in Advance.
MYSQL:
http://sqlfiddle.com/#!2/19ea8/5
ANDROID:
wihin mainactivity for listview:
JSONArray arr = result.getJSONArray("JsonResultArray");
for(int i=0;i<arr.length();i++)
{
JSONObject e1 = arr.getJSONObject(i);
JSONObject json2 = (JSONObject) e1.get("data");
String name = json2.getString("name").trim();
String receiver = json2.getString("receiver").trim();
String sender = json2.getString("sender").trim();
String date = json2.getString("date").trim();
String msg = json2.getString("msg").trim();
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID, Integer.toString(i+1));
map.put(KEY_TITLE, name);
map.put(KEY_msg, msg);
map.put(KEY_date,date);
// adding HashList to ArrayList
msgList.add(map);
}
}catch(Exception e){
e.printStackTrace();
}
in convert view:
HashMap<String, String> msgs = new HashMap<String, String>();
msgs = data.get(position);
name.setText(msgs.get(PopoverViewActivity.KEY_TITLE));
msg.setText(msgs.get(PopoverViewActivity.KEY_msg));
date1.setText(msgs.get(PopoverViewActivity.KEY_date));
If you want to group same users to one row. I suggest you to edit your mysql. You need to use
select * from table group by user
in your mqsql query, that can make you convenient to change your db and doesn't influence your UI.
In Android, just call your api and present data to listView.
Related
I have a piece of code which basically synchronises data between an online database. However I am getting an error on one particular line of code (map.put("id", obj.get(mydb.WEB_ID).toString());) where an integer value is obtained from the android sqlite databasse and submitted to the online database. The full cose is as displayed below :
public void updateSQLite(String response){
ArrayList<HashMap<String, String>> syncL;
syncL = new ArrayList<HashMap<String, String>>();
// Create GSON object
Gson gson = new GsonBuilder().create();
try {
// Extract JSON array from the response
JSONArray arr = new JSONArray(response);
System.out.println(arr.length());
// If no of array elements is not zero
if(arr.length() != 0){
// Loop through each array element, get JSON object which has userid and username
for (int i = 0; i < arr.length(); i++) {
// Get JSON object
JSONObject obj = (JSONObject) arr.get(i);
System.out.println(obj.get("web_id"));
System.out.println(obj.get("phone_id"));
System.out.println(obj.get("msg_id"));
mydb.updateWebSync(obj.get(obj.get("phone_id").toString(), obj.get("msg_id").toString(), obj.get("web_id").toString());
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", obj.get(mydb.WEB_ID).toString());
map.put("p_id", obj.get(mydb.COLUMN_ID).toString());
map.put("s", "1");
syncL.add(map);
}
updateMySQLSyncSts(gson.toJson(syncL), "syncsts");
Toast.makeText(getApplicationContext(), "Download Messages success!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Download Messages error!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
In my android sqlite database, the value of mydb.WEB_ID is stored as an integer. Any assistance is appreciated.
Hashmap<String,String>
it only contains String values. So you have to convert it to String.
with using
toString()
function it ll give you error.
Try with
String.ValueOf(obj.get("web_id"))
it ll convert the interger value to String and your problem gets resolved.
Happy coding. :P
I figured out my mistake...I was calling the database column name in the HashMap which is different from the json variable. Thanks all for your assistance.
I've created a JSON encode where you enter a HashTable (public Hashtable<?, ?> JSonDecode(String data) {... return objJS.toString(); } ) and get a string in JSON format. That is:
If I have a Hashtable with this (Hashtable in Hashtable):
Example Hashtable:
Hashtable<String, Object> exampleHT = new Hashtable<String, Object>();
exampleHT.put("Color", "Red");
exampleHT.put("OtherKey", "OtherValue");
exampleHT.put("OtherKey2", "OtherValue2");
Hashtable<String, Object> country = new Hashtable<String, Object>();
country.put("Spain", "Madrid");
country.put("France","Paris");
country.put("Italy", "Rome");
Hashtable<String, String> pokemon = new Hashtable<String, String>();
pokemon.put("Pikachu", "Electric");
pokemon.put("Charmander","Fire");
country.put("Pokemons", pokemon);
exampleHT.put("Countries", country);
I use my function(JSonEncode(exampleHT);) and I get this string:
{
"Color":"Red",
"Countries":{
"Spain":"Madrid",
"France":"Paris",
"Italy":"Rome",
"Pokemons":{
"Pikachu":"Electric",
"Charmander":"Fire"
}
},
"OtherKey":"OtherValue",
"OtherKey2":"OtherValue2"
}
It works perfectly! My problem is to create the reverse process, with JSonDecode.
Hashtable<?, ?> hashUnknown = JSonDecode(jsonStringExample);
public Hashtable<?, ?> JSonDecode(String data) {
// I do not know how to parse json in Hashtable, without indicating the tags manually.
}
I do not know how to parse json in Hashtable, without indicating the tags manually.
That is, without it:
JSONArray menuObject = new JSONArray (jObject.getString ("Color"));
JSONArray menuObject = new JSONArray (jObject.getString ("Countries"));
This should be dynamic without knowing json content without writing manually Color, Countries, ....
Any ideas or advice? Thanks,
You can get an Iterator object (java.util.Iterator) over the keys of your JSONObject (jObject)
So you can write something like this:
Iterator<String> it = jObject.keys();
String key = null;
Object value = null;
while (it.hasNext()) {
key = it.next();
value = jObject.get(key);
// Then test the instance of the value variable
// and perform some logic
}
I'm parsing the json object taken from server. I want to put the list in reverse order. In order to do that I made a code like this.
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Contacts
for(int i = products.length(); i >0; i--){
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String cid = c.getString(TAG_CID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CID, cid);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
contactList.add(map);
Log.d("value", contactList.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME,}, new int[] {
R.id.name});
setListAdapter(adapter);
If I try to do it in the right order, the list will appear. But if I try reverse, I won't get any output. The problem is in for looping. But cannot findout where it is actually.
Yes, the problem is in the loop. The first pass through should throw some sort of "out of bounds" exception, because products.getJSONObject(products.length()) does not exist. Look in logcat for the details, and/or step through your code with a debugger. Remember, with zero-indexed collections (arrays, lists, etc.) the smallest index value is 0 and the largest is 1 less than the total number of elements in the collection.
The fix is to change this:
for(int i = products.length(); i >0; i--){
to this:
for(int i = products.length() - 1; i >= 0; i--){
change your for loop Syntax as Below
for(int i = products.length() - 1; i >= 0; i--){
// your Code
}
Change your loop like this
for(int i = products.length()-1; i >=0; i--){
It should work
Add this between parsing of json and creating of adapter:
Collections.reverse(contactList);
To reverse list:-
ArrayList<Element> tempElements = new ArrayList<Element>(mElements);
Collections.reverse(tempElements);
Hi friends i got stucked into these problem at the last stage of my program.Here is some description about my project:i am calling a web service with the help of Ksoap and getting the JSON response from the server than,i am parsed that response and store it into the correspondent arraylist.Till here everything is working fine.Now the problem starts here i want to store all these AppID,AppName,AppTabID,Icon,Tabname into a multimap with same key for the same index.How can i achieve that ?Any help would highly appreciated!
private SoapPrimitive response;
ArrayList<String> AppID = new ArrayList<String>();
ArrayList<String> AppName = new ArrayList<String>();
ArrayList<String> AppTabId = new ArrayList<String>();
ArrayList<String> Icon = new ArrayList<String>();
ArrayList<Drawable> drawables=new ArrayList<Drawable>();
ArrayList<String> TabName = new ArrayList<String>();
<!--here are the Arraylist declaration->
public String parse(String a) throws Exception {
JSONArray jsonArry1 = new JSONArray(res); // create a json object from a string
// JSONArray jsonEvents = jsonObj.optJSONArray("AppItems"); // get all events as json objects from AppItems array
System.out.println("Length of array for AppItem tag is.. "+jsonArry1.length());
for(int i = 0; i < jsonArry1.length(); i++){
JSONObject event = jsonArry1.getJSONObject(i); // create a single event jsonObject
String AppID=event.getString("AppId");
System.out.println("AppId is "+AppID);
String AppName=event.getString("AppName");
System.out.println("AppName is "+AppName);
String AppTabId=event.getString("AppTabId");
System.out.println("AppTabId is "+AppTabId);
String Icon=event.getString("Icon");
System.out.println("Icon is "+Icon);
TabHtml=event.getString("TabHtml");
System.out.println("TabHtml = "+TabHtml);
}
System.out.println("return"+TabHtml);
return TabHtml;
}
the above code i am using for saving all the content into arraylist object.From here i want to set all these diferent Arraylist into same MultiMap.How can i achieve that?
I'd just define an AppData container class to hold all data related to a single response, and then just put AppData objects into your multimap.
On this link (Java Map Interface) search for multimap which gives a straight forward implementation of a multimap.
However from what I understand of your question, you'll have to put all your Lists into a List and that would go into a MultiMap (which will just be a HashMap<String,ArrayList<ArrayList>>).
It is not very good approach to have all these different lists for different fields in response, but as you have implemented almost completed, I would lead this approach further:
You can have a Map into map to resolve this prob:
All you need to have follow the below loop:
HashMap<Integer, HashMap<String, String> parsed=new HashMap<Integer, HashMap<String, String>();
for(int i=0;i<AppID.size();i++)
{
HashMap<String, String> keyValues= new HashMap<String, String>();
keyValues.put("id", AppName .get(0));
keyValues.put("id", AppTabId .get(0));
keyValues.put("id", Icon .get(0));
.....
parsed(new Integer(i), keyValues);
}
hiii,
I am working on a project where i am calling a url and fetching data as json . Now , this json object will be parsed.
Now i am getting a json tag like status= active or status = notActive.
Based on this response , i have to place some data tags which have a status "Active" under group title "Active" under listview and notActive data under "NOT-ACTIVE" group title.
*How to different data based on status value under two groups seperately so that when i click Active group , i will ge*t different data for Active only .
Any kind of help will be highly appreciated....
This way i solved it.
try{
jArray = new JSONArray(json);
for(int i=0;i<jArray.length() ;i++){
Map<String, String> childdata1 = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String status = e.getString("2");
// Log.e("log_tag","Status: "+status);
if (status.contains("active")){
// Log.e("log_tag","StatusActive: "+status);
//childdata1.put("child", String.valueOf(i));
childdata1.put("child", e.getString("mlsid"));
childdata1.put("child1", e.getString("status"));
childdata1.put("child2", e.getString("address"));
childdata1.put("child3", e.getString("city"));
child1.add(childdata1);
}else if(status.contains("pending")){
//Log.e("log_tag","StatusPending: "+status);
Map<String, String> childdata2= new HashMap<String, String> ();
// childdata2.put("0", String.valueOf(i));
childdata2.put("child", e.getString("mlsid"));
childdata2.put("child1", e.getString("status"));
childdata2.put("child2", e.getString("address"));
childdata2.put("child3", e.getString("city"));
child2.add(childdata2);
}
}
// Log.e("log_tag","ARRAY Length : "+jArray.length());
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());