I want to load JSON data into the List view with subtitle and images (Left side on the row).
Here below I have posted my sample JSON response code :
for (int i = 0; i < contacts.length(); i++) {
JSONObject obj = contacts.getJSONObject(i);
Iterator keys = obj.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// store key in an arraylist which is A,B,...
// get the value of the dynamic key
JSONArray currentDynamicValue = obj.getJSONArray(currentDynamicKey);
Log.d("Response: ", "> " + currentDynamicKey);
int jsonrraySize = currentDynamicValue.length();
if(jsonrraySize > 0) {
for (int ii = 0; ii < jsonrraySize; ii++) {
JSONObject nameObj = currentDynamicValue.getJSONObject(ii);
String name = nameObj.getString("name");
System.out.print("Name = " + name);
//Log.d("Response: ", "> " + name);
//store name in an arraylist
}
}
}
}
I want to Show Tittle : currentDynamicKey values and Sub Title : Name string values.
If you already have your data and you don't necessarily need to integrate the server requests with your adapter, then you really just need an adapter which supports a JSONArray. There's a really nice open source one within the Advanced-Adapters library. Then it's just a matter of passing the JSONArray to the adapter and setting the adapter to a ListView.
Related
I am fetching data from JSON to android.But, I am getting an empty JSON response. The PHP code which generates JSON data is as follows:
$result = $conn->query("SELECT dbname FROM users ORDER BY dbname ASC");
//defined second array for dbnames' list
$dblist = array();
while($row = $result->fetch_assoc()){
//array_push($response['dblist'],$row['dbname']);
$dblist[] = array('name'=>$row['dbname']);
}
$response['dblist'] = $dblist;
This is the JSON response.
{"dblist":[{"name":"a"},{"name":"arsod"}]}
The Java code to fetch data in android is as follows:
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for(int i=0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
institutes.add(name);
}
where institutes is an ArrayList in which I want to add each fetched element. But while fetching the data, I get the error in logcat org.json.JSONException: End of input at character 0 of. What is going wrong?
Considering the following:
s = {"dblist":[{"name":"a"},{"name":"arsod"}]}
Your code should be like,
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for(int i=0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
institutes.add(name);
}
remove this line:
JSONObject object = obj.getJSONObject("dblist");
and replace all occurences of object. with obj.
your JSONObject obj doesn't contain "dblist" object, there is only array inside it, so you should look for getJSONArray("dblist") straight inside obj
edit: you are parsing different String s, I've just checked this code:
final String s = "{\"dblist\":[{\"name\":\"a\"},{\"name\":\"arsod\"}]}";
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for (int i = 0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
which is almost exacly same as your and works pretty fine...
I want to parse this JSON in Volley Library. I have set everything I want to parse name of the recipe and image. Problem is that I want three recipes to be parsed at same time but here it have same Object name Recipe and I don't know how to parse same object name for three different TextViews.
Here is the JSON format: link
Here is the code I tried but it gave me one name not three different names:
try {
JSONArray list = response.getJSONArray("hits");
Log.v ("MISH", "List: " + list);
for (int x = 0; x<list.length(); x++) {
JSONObject obj = list.getJSONObject(x);
JSONObject main = obj.getJSONObject("recipe");
String label = main.getString("label");
String image = main.getString("image");
Picasso.with(getApplicationContext()).load(image).into(recipeOne);
Log.v("FISH", "NAME FATCH: " + label);
recipeOneText.setText(label);
}
Try this.
And use optString in your code:
try {
if (TextUtils.isEmpty(response)) {
Toast.makeText(this, "response is null", Toast.LENGTH_SHORT).show();
return;
}
JSONObject jsonObject = new JSONObject(response);
JSONArray hits = jsonObject.getJSONArray("hits");
// edited here ,add data in your code
JSONObject jo1 = hits.getJSONObject(0);
hits.put(0,jo1); // add jo1 JSONObject to the JSON array, the angle is 0
hits.put(1,jo1); // add jo1 JSONObject to the JSON array, the angle is 1
hits.put(2,jo1); // add jo1 JSONObject to the JSON array, the angle is 2
for (int i = 0; i < hits.length(); i++) {
JSONObject jo = hits.getJSONObject(i);
JSONObject recipe = jo.getJSONObject("recipe");
String label = recipe.optString("label");
String image = recipe.optString("image");
Picasso.with(getApplicationContext()).load(image).into(recipeOne);
Log.v("FISH", "NAME FATCH: " + label);
recipeOneText.setText(label);
}
} catch (JSONException e) {
e.printStackTrace();
}
Edit
// If your don't have to much data in your code , you can do like this .
JSONObject jo1 = hits.getJSONObject(0);
hits.put(0,jo1); // add jo1 JSONObject to the JSON array, the angle is 0
hits.put(1,jo1); // add jo1 JSONObject to the JSON array, the angle is 1
hits.put(2,jo1); // add jo1 JSONObject to the JSON array, the angle is 2
I am trying to send an array with a bunch of objects back to android?
I tried String Builder like so:
StringBuilder sb = new StringBuilder();
sb.append("[");
for(int i = 0; i <usersChanged.size(); i++) {
DatabaseUser userChange = usersChanged.get(i);
if(userChange.getIsFollowingType() == 0) {
String userIdStr = "{userId:" + userChange.getUserId() + ",";
String followingStr = "following:" + String.valueOf(userChange.getIsFollowingType())+ "}]";
sb.append(userIdStr).append(followingStr);
but I am doing something wrong here. On my server side I am using node.js and would parse the array if I send over a string no problem, but this is not sending a string version of the array? What do I need to change on my string builder? Or is there a more efficient way to send over the list of usersChanged - (which is List)
I am using retrofit if there is a way to do it easy with that.
Your code will send things like
[{userId: someuserid, following: someparameter}]
You need to have the double quote (" ") sent over as well.
for(int i = 0; i <usersChanged.size(); i++) {
DatabaseUser userChange = usersChanged.get(i);
if(userChange.getIsFollowingType() == 0) {
String userIdStr = "{\"userId\":\"" + userChange.getUserId() + "\",";
String followingStr = "\"following\":\"" + String.valueOf(userChange.getIsFollowingType())+ "\"}]";
sb.append(userIdStr).append(followingStr);
You should also probably move the "]" to after the loop.
EDIT:
Forgot to mention this, but you can definitely use JSONArray and JSONObject to make your life easier.
JSONArray jsonArray = new JSONArray();
for(...){
JSONObject jsonObject = new JSONObject();
jsonObject.put("userId", userChange.getUserId());
jsonObject.put("following", String.valueOf(userChange.getIsFollowingType()));
jsonArray.put(jsonObject);
}
Then send over the jsonArray.
I have JSON :
{"elements":[{"id":5,"name":"Mathematics","shortName":"math","links":{"courses":[15,30,46,47]}}]}
My code :
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
//Log.d("All Products: ", json.toString());
try {
products = json.getJSONArray("elements");
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
int ids = c.getInt(TAG_PID);
String id = String.valueOf(ids);
if (id.compareTo(id_kh) == 0) {
object = c.getJSONObject("links");
JSONArray courses = object.getJSONArray("courses");///???????????
//result = courses.split("[,]");
Toast.makeText(getBaseContext(),"abc",Toast.LENGTH_LONG).show();
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I dont know to get array number after "courses".
I would use HashMaps. Here you have an example (creating Hashmap from a JSON String
) how to get it from a JSON String.
Particularly for the "courses", once you have been parsed until there, I would use a HashMap<String,List<Integer>>
courses is a JSONArray, so you can do like that:
JSONArray coursesArray = linksObject.getJSONArray("courses");
UPDATE:
To get values from coursesArray :
int value = coursesArray.optInt(position);
Almost there. Once you get your
JSONArray courses = object.getJSONArray("courses");
simply iterate over its values:
// you wanted these numbers in an array
// so let's create one, with size being number of elements in
// JSONArray courses
int[] courseIds = new int[courses.length()];
for (int j=0; j<courses.length(); j++) {
// assign current number to the appropriate element in your array of ints
coursesId[j] = courses.getInt(j);
Log.d("TAG", "number: " + number);
}
The above will save these numbers in an array and print them too:
number: 15
number: 30
number: 46
number: 47
Just keep in mind that "courses" key might not exist, the array might be empty etc.
i use www.openweathermap.org FORECAST.
thisi the result of forecat: http://api.openweathermap.org/data/2.5/forecast?lat=35&lon=139
JSONObject coordObj = getObject("coord", jObj);
Latitude=getFloat("lat", coordObj);
Longitude=getFloat("lon", coordObj);
JSONObject coordObj = getObject("city", jObj);
id=getFloat("id", coordObj);
name=getFString("name", coordObj);
JSONObject sysObj = getObject("sys", jObj);
Country=getString("country", sysObj);
Sunrise=getInt("sunrise", sysObj));
Sunset=getInt("sunset", sysObj));
JSONObject jlist = jObj.getObject("list");
JSONObject JSONWeather = jArr.getJSONObject(0);
Condition_id==getInt("id", JSONWeather);
condition_description=getString("description", JSONWeather);
condition=getString("main", JSONWeather);
condition_icongetString("icon", JSONWeather);
JSONObject mainObj = getObject("main", jObj);
Humidity=getInt("humidity", mainObj);
Pressure=getInt("pressure", mainObj);
MaxTemp=getFloat("temp_max", mainObj);
MinTemp(getFloat("temp_min", mainObj);
Temp=getFloat("temp", mainObj);
// Wind
JSONObject wObj = getObject("wind", jObj;
Speed=getFloat("speed", wObj);
Deg=getFloat("deg", wObj);
// Clouds
JSONObject cObj = getObject("clouds", jObj);
Perc=getInt("all", cObj);
please how to loop the weather array ?
First, list is not a JsonObject it's an array, so you should get it doing:
JSONArray jlist = (JSONArray) jObj.get("list");
Depending of which library you are using the syntax can change but the logic is the same, I'm explaining using json simple lib.
after that you should iterate your list array, something like this:
for (int i = 0; i < jlist.size(); i++){
// get all your objects and your weather array
// to get your weather array the logic is the same:
JSONArray jArrayWeather = (JSONArray) jObj.get("weather");
for (int j = 0; j < jArrayWeather ; j++){
//and here you can get your id, main, description and icon using j index
JSONObject currentObj = (JSONObject) jArrayWeather.get(j);
String main = (String) currentObj.get("main");
}
}
I didn't test this code, so follow the idea and try to do it yourself. Take a look here as we can see you haven't experience with json
Here is another example. (For a different JSON format though).
try{
JSONArray list=json.getJSONArray("list");
for(int indx=0;indx<MAX_FORCAST_FRAGMENT;indx++) {
JSONArray weather = list.getJSONObject(indx).getJSONArray("weather");
String weatherIconString=setWeatherIcon(weather.getJSONObject(0).getInt("id"),
0,100);
forcastData[indx][0]=weatherIconString;
JSONObject main=list.getJSONObject(indx).getJSONObject("main");
JSONObject wind=list.getJSONObject(indx).getJSONObject("wind");
String detailsFieldString= weather.getJSONObject(0).getString("description").toUpperCase(Locale.US);
String humidityFieldString="Humidity: " + main.getString("humidity") + "%";
String windFieldString= "Wind: " + wind.getString("speed") + " Km/H";
// populate the list view//
int forecastFragmentId=getResources().getIdentifier("forcast_layout_" + (indx+1), "id", getPackageName());
tv=(TextView)findViewById(forecastFragmentId).findViewById(R.id.details_field);
tv.setText(detailsFieldString);
saveData(F_DETAILS+indx,detailsFieldString);
tv=(TextView)findViewById(forecastFragmentId).findViewById(R.id.weather_icon);
tv.setText(weatherIconString);
saveData(F_ICON+indx,weatherIconString);
tv=(TextView)findViewById(forecastFragmentId).findViewById(R.id.wind_field);
tv.setText(windFieldString);
saveData(F_WIND+indx,windFieldString);
tv=(TextView)findViewById(forecastFragmentId).findViewById(R.id.humidity_field);
tv.setText(humidityFieldString);
saveData(F_HUMIDITY+indx,humidityFieldString);
c = Calendar.getInstance();
int currentDate=c.get(Calendar.DAY_OF_MONTH);
saveTime(LAST_FORCAST_TIME,currentDate);
}
}catch(Exception e){
Log.e("SimpleWeather", "One or more fields not found in the JSON data in renderForecastData");
}
}