read Json data in android studio - android

I am building an app in android studio that uses JSON to acess to my postgresql where is my data and I am receiving the data this way:
[
{"id":"1","title":"12 May to 30 Jun"},
{"id":"2","title":"3 Jun to 20 Jun"}
]
I tried to find every where how to use JSONObject or JSONArray for "unlock" the data for pass it to other variables

After sometime trying and trying I found a way to
String finalJson = buffer.toString();
try {
JSONArray parentArray = new JSONArray(finalJson);
int count = 0;
int[] id = new int[parentArray.length()];
String[] title = new String[parentArray.length()];
StringBuffer finalBufferedData = new StringBuffer();
while (count < parentArray.length())
{
JSONObject finalObject = parentArray.getJSONObject(count);
id[count] = finalObject.getInt("id");
title[count] = finalObject.getString("title");
finalBufferedData.append(id[count] + " - " + title[count] + "\n");
count++;
}
return finalBufferedData.toString();
} catch (JSONException e) {
e.printStackTrace();
}
this way I was able to get the 2 rows from postgresql and show it (later will add it the app sqlite so it doesn't require always to check in my postgresql)

Here is the working code:
public void parseJson() {
// Response from API call
String response = "[{\"id\":\"1\",\"title\":\"12 May to 30 Jun\"},\n" +
"{\"id\":\"2\",\"title\":\"3 Jun to 20 Jun\"}]";
try {
JSONArray jsonArray = new JSONArray(response);
// Get all jsonObject from jsonArray
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = null, title = null;
// Id
if (jsonObject.has("id") && !jsonObject.isNull("id")) {
id = jsonObject.getString("id");
}
// Title
if (jsonObject.has("title") && !jsonObject.isNull("title")) {
title = jsonObject.getString("title");
}
Log.d("SUCCESS", "JSON Object: " + "\nId: " + id
+ "\nTitle: " + title);
}
} catch (JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
}
OUTPUT:
D/SUCCESS: JSON Object:
Id: 1
Title: 12 May to 30 Jun
D/SUCCESS: JSON Object:
Id: 2
Title: 3 Jun to 20 Jun

protected void onPostExecute(String result)
{
//result parameter should be final so that it can be used in cross thread operation
super.onPostExecute(result);
if (result != null) {
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String Brand = object.getString("UserName");
HashMap<String, String> itemList = new HashMap<String, String>();
itemList.put("UserName", Brand);
BrandList.add(itemList);
}
**adapter = new SimpleAdapter(Main2Activity.this, BrandList, R.layout.list, new String[]{"UserName"}, new int[]{R.id.txtTitel});
((AdapterView<ListAdapter>) listView).setAdapter(adapter);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
Toast.makeText(Main2Activity.this, "Could not get any data.", Toast.LENGTH_LONG).show();
}
}

Related

Request timed out in volly class android

local host giving me data in browser as shown in screenshot but Volly class giving me 'Request timed out.'
*it was working well in window 8 but recently i changed my window 8 to 10 so now i am facing this problem but i think it is not happen with this reason *
public DataPoint[] getTimeAndU() {
final DataPoint[] dataPoint = new DataPoint[2000];
final DataTransmit dataTransmit = new DataTransmit(mContext) {
#Override
protected void onCompleted(String json) {
Log.v("joson",json);
if (json != null) {
// Toast.makeText(this,"sucess"+json+"",Toast.LENGTH_LONG).show();
try {
Log.v("testt","dtsfasdf");
// JSONArray ja = new JSONArray(json);
JSONObject jo = new JSONObject(json);
for(int i = 0; i < jo.length(); i++){
if (i > 1) {
JSONObject obj2 = jo.getJSONObject("a"+i);
double x = toDouble(obj2.getString("time_s"));
double y = toDouble( obj2.getString("u_mv"));
dataPoint[i] = new DataPoint(x,y);
}else{
dataPoint[i] = new DataPoint(0,0);
}
}
} catch (Throwable t) {
Log.e("app", "Could not parse malformed JSON: \"" + String.valueOf(t) + "\"");
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
}
}
};
//dataTransmit.requestJasonArray("http://192.168.1.12//Rehan/UrbanClout.php?FunctionKey=loginUser&login_name=aaa&login_pass=aaa", "Schedule");
// dataTransmit.requestJasonArray("http://192.168.1.8/ahsan_bhai_project/excel_reader/excel_reader/example.php", "Schedule");
dataTransmit.requestJasonObject("http://192.168.10.32/ahsan_bhai_project/excel_reader/excel_reader/example.php?FunctionKey=time_u","Schedule");
return dataPoint;
}
here my services in php

How to parse this wikipedia response?

{
"batchcomplete": "",
"query": {
"pages": {
"25675557": {
"pageid": 25675557,
"ns": 0,
"title": "Cricket",
"extract": "Cricket is a bat-and-ball game played between two teams of eleven players each on a cricket field, at the centre of which is a rectangular 22-yard-long (20 metres) pitch with a target at each end called the wicket (a set of three wooden stumps upon which two bails sit). "
}
}
}
}
this is the code I tried :
public void getJSON(final String city) throws JSONException {
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=" + city);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader reader =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp = "";
while ((tmp = reader.readLine()) != null) {
json.append(tmp).append("\n");
}
reader.close();
data = new JSONObject(json.toString());
if (data.getInt("cod") != 200) {
System.out.println("Cancelled");
return null;
}
} catch (Exception e) {
System.out.println("Exception " + e.getMessage());
return null;
}
return null;
}
#Override
protected void onPostExecute(Void Void) {
if (data != null) {
Log.d("my weather received", data.toString());
try {
//JSONObject forecastJson = new JSONObject(data);
JSONObject forecastArray = data.getJSONObject("query");
System.out.println(forecastArray);
JSONArray pagesArray = forecastArray.getJSONArray("pages");
// JSONArray idArray = pagesArray.getJSONArray(0);
//JSONArray idArray = pagesArray.get(0);
System.out.println(pagesArray);
JSONObject obj = pagesArray.getJSONObject(0);
System.out.println(obj);
//JSONObject weatherarray = data.getJSONObject("pages");
//JSONObject weather = weatherarray.getJSONObject(0);
// final String des = weather.getString("description");
/*for (int i = 0; i < forecastArray.length(); i++) {
JSONObject dailyForecast = forecastArray.getJSONObject(i);
JSONObject tempObject = dailyForecast.getJSONObject("main");
minTemp = tempObject.getDouble("min");
maxTemp = tempObject.getDouble("max");
//add these minTemp and maxTemp to array or the
//way you want to use
}*/
System.out.println("Temp Value : "+" : ");
runOnUiThread(new Runnable() {
#Override
public void run() {
textvw.setText("");
}
});
} catch (Exception e) {
Log.e("GetFeedTask", "Error:" + e.getMessage());
}
}
}
}.execute();
}
The exception is because the response does not contain JSON Array. Change your
JSONArray pagesArray = forecastArray.getJSONArray("pages");
to
JSONObject pagesArray = forecastArray.getJSONObject("pages");
and I believe that you're trying to get keys which are dynamic. You cloud get the objects using JSONObject.getKeys() like below.
Iterator keys = pagesArray.keys();
while(keys.hasNext()) {
String dynamicKey = (String)keys.next();
JSONObject jObj = pagesArray.getJSONObject(dynamicKey);
//Get other attributes by jObj.getString() method.
}
Try and let me know if it works.
The error is clear enough. you try to assign a JSONobject to a JSONArray
JSONArray pagesArray = forecastArray.getJSONArray("pages");
Replace by
JSONObject pagesArray = forecastArray.JSONObject("pages");
the data of a JSONArray are between [] and not {}.
your error is in :
JSONArray pagesArray = forecastArray.getJSONArray("pages");
Your problem is that you getJSONArray while pages are a JsonObject in your data .if your "pages" is a array in your data you must send it in [] from server like this:
{
"batchcomplete": "",
"query": {
"pages": [ {
"pageid": 25675557,
"ns": 0,
"title": "Cricket",
"extract": "Cricket is a bat-and-ball game played between two teams of eleven players each on a cricket field, at the centre of which is a rectangular 22-yard-long (20 metres) pitch with a target at each end called the wicket (a set of three wooden stumps upon which two bails sit). "
},
{
"pageid": 25675557,
"ns": 0,
"title": "Cricket",
"extract": "Cricket is a bat-and-ball game played between two teams of eleven players each on a cricket field, at the centre of which is a rectangular 22-yard-long (20 metres) pitch with a target at each end called the wicket (a set of three wooden stumps upon which two bails sit). "
}
]
}
}
and in android :
try {
//JSONObject forecastJson = new JSONObject(data);
JSONObject forecastArray = data.getJSONObject("query");
System.out.println(forecastArray);
JSONArray pagesArray = forecastArray.getJSONArray("pages");
System.out.println(pagesArray);
for (int k = 0; k < pagesArray.length(); k++) {
try {
JSONObject object = pagesArray.getJSONObject(k);
String pageid = object.getString("pageid");
String ns = object.getString("ns");
String title = object.getString("title");
String extract = object.getString("extract");
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Log.e("GetFeedTask", "Error:" + e.getMessage());
}

Json move to next item

I have a dynamic JSON string that looks like this:
{"_id":"7","food_name":"Fiber Balance"},{"_id":"8","food_name":"Sport +"}
I am able to get the first name, but not the second one. This is my code for getting the first (Fiber Balance):
// Dynamic text
TextView textViewDynamicText = (TextView)getActivity().findViewById(R.id.textViewDynamicText);
String stringJSON = textViewDynamicText.getText().toString();
String stringFoodname = "";
try {
JSONObject jsonObject = new JSONObject(stringJSON);
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
stringFoodname = jsonObject.getString("food_name");
Toast.makeText(getContext(), stringFoodname, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// Something went wrong!
}
}
} catch (org.json.JSONException e) {
// Something went wrong!
}
How can I go to the next item in the json string?
If you have multiple data than you need to use Array,if you want to get all data from your json use below trick,
String json = "{\"_id\":\"7\",\"food_name\":\"Fiber Balance\"},{\"_id\":\"8\",\"food_name\":\"Sport +\"}";
json = "[" + json + "]";
try {
JSONArray array = new JSONArray(json);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String foodName = object.getString("food_name");
Log.e("FoodName:", foodName);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", "json", e);
}

How to get particular values from JSON response by using Android code?

I need to get Particular Object values ( A, B, C, D) and related key values (#"name" ). After getting (A, B, C, D ) object values I need to list out into list view Android. Here below I have posted my sample code and response. Please help me.
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray("response");
Log.d("Response: ", "> " + contacts);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
My JSON Response :
{"response" : [ {
"A" : [ {
"name" : "tango"
},
{
"name" : "ping"
}
],
"B" : [ {
"name" : "tango"
},
{
"name" : "ping"
}
]
} ]}
Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.
You can get dynamic keys like this
JSONObject responseDataObj = new JSONObject(responseData);
JSONArray responseArray = responseDataObj.getJSONArray("response");
for (int i = 0; i < responseArray.length(); i++) {
nodes = new ArrayList<ArrayList<String>>();//nodes ArrayList<ArrayList<String>> declared globally
nodeSize = new ArrayList<Integer>();//nodeSize ArrayList<Integer> declared globally
JSONObject obj = responseArray.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);
int jsonrraySize = currentDynamicValue.length();
int sizeInArrayList = jsonrraySize + 1;
nodeSize.add(sizeInArrayList);
if(jsonrraySize > 0) {
for (int ii = 0; ii < jsonrraySize; ii++) {
nameList = new ArrayList<String>();//nameList ArrayList<String> declared globally
if(ii == 0) {
JSONObject nameObj = currentDynamicValue.getJSONObject(ii);
String name = nameObj.getString("name");
System.out.print("Name = " + name);
//store name in an arraylist
nameList.add(name);
}
}
}
nodes.add(nameList);
}
}
You can use following method to parse your response and handle output as per requirement.
private void parseJson(String res) {
try {
JSONObject mainObject = new JSONObject(res);
JSONArray response = mainObject.getJSONArray("response");
for (int i = 0; i < response.length(); i++) {
JSONObject obj = response.getJSONObject(i);
JSONArray A = obj.getJSONArray("A");
for (int j = 0; j < A.length(); j++) {
JSONObject objA = A.getJSONObject(j);
String name = objA.getString("name");
// use or store name here
}
JSONArray B = obj.getJSONArray("B");
for (int k = 0; k < B.length(); k++) {
JSONObject objB = B.getJSONObject(k);
String name = objB.getString("name");
// use or store name here
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This may work for you :
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray contacts;
contacts = jsonObj.getJSONArray("response");
Log.d("Response: ", "> " + contacts);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
JSONArray jsonArrayA=new JSONArray();
jsonArrayA=c.getJSONArray("A");
for(int j=0;j<jsonArrayA.length();j++){
String name=jsonArrayA.getJSONObject(j).getString("name");
Log.e("Name","name of jsonarray A "+i+" "+name);
}
JSONArray jsonArrayB=c.getJSONArray("B");
for(int k=0;k<jsonArrayB.length();k++){
String name=jsonArrayB.getJSONObject(k).getString("name");
Log.e("Name","name of jsonarray B "+i+" "+name);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}

conversion from string to JSON object Android

I am working on an Android application. In my app I have to convert a string to JSON Object, then parse the values. I checked for a solution in Stackoverflow and found similar issue here link
The solution is like this
`{"phonetype":"N95","cat":"WP"}`
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
I use the same way in my code . My string is
{"ApiInfo":{"description":"userDetails","status":"success"},"userDetails":{"Name":"somename","userName":"value"},"pendingPushDetails":[]}
string mystring= mystring.replace("\"", "\\\"");
And after replace I got the result as this
{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"Sarath Babu\",\"userName\":\"sarath.babu.sarath babu\",\"Token\":\"ZIhvXsZlKCNL6Xj9OPIOOz3FlGta9g\",\"userId\":\"118\"},\"pendingPushDetails\":[]}
when I execute JSONObject jsonObj = new JSONObject(mybizData);
I am getting the below JSON exception
org.json.JSONException: Expected literal value at character 1 of
Please help me to solve my issue.
Remove the slashes:
String json = {"phonetype":"N95","cat":"WP"};
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
This method works
String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
Log.d("phonetype value ", obj.getString("phonetype"));
} catch (Throwable tx) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
try this:
String json = "{'phonetype':'N95','cat':'WP'}";
You just need the lines of code as below:
try {
String myjsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JSONObject jsonObject = new JSONObject(myjsonString );
//displaying the JSONObject as a String
Log.d("JSONObject = ", jsonObject.toString());
//getting specific key values
Log.d("phonetype = ", jsonObject.getString("phonetype"));
Log.d("cat = ", jsonObject.getString("cat");
}catch (Exception ex) {
StringWriter stringWriter = new StringWriter();
ex.printStackTrace(new PrintWriter(stringWriter));
Log.e("exception ::: ", stringwriter.toString());
}
just try this ,
finally this works for me :
//delete backslashes ( \ ) :
data = data.replaceAll("[\\\\]{1}[\"]{1}","\"");
//delete first and last double quotation ( " ) :
data = data.substring(data.indexOf("{"),data.lastIndexOf("}")+1);
JSONObject json = new JSONObject(data);
To get a JSONObject or JSONArray from a String I've created this class:
public static class JSON {
public Object obj = null;
public boolean isJsonArray = false;
JSON(Object obj, boolean isJsonArray){
this.obj = obj;
this.isJsonArray = isJsonArray;
}
}
Here to get the JSON:
public static JSON fromStringToJSON(String jsonString){
boolean isJsonArray = false;
Object obj = null;
try {
JSONArray jsonArray = new JSONArray(jsonString);
Log.d("JSON", jsonArray.toString());
obj = jsonArray;
isJsonArray = true;
}
catch (Throwable t) {
Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
}
if (object == null) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
Log.d("JSON", jsonObject.toString());
obj = jsonObject;
isJsonArray = false;
} catch (Throwable t) {
Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
}
}
return new JSON(obj, isJsonArray);
}
Example:
JSON json = fromStringToJSON("{\"message\":\"ciao\"}");
if (json.obj != null) {
// If the String is a JSON array
if (json.isJsonArray) {
JSONArray jsonArray = (JSONArray) json.obj;
}
// If it's a JSON object
else {
JSONObject jsonObject = (JSONObject) json.obj;
}
}
Using Kotlin
val data = "{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"somename\",\"userName\":\"value\"},\"pendingPushDetails\":[]}\n"
try {
val jsonObject = JSONObject(data)
val infoObj = jsonObject.getJSONObject("ApiInfo")
} catch (e: Exception) {
}
Here is the code, and you can decide which
(synchronized)StringBuffer or
faster StringBuilder to use.
Benchmark shows StringBuilder is Faster.
public class Main {
int times = 777;
long t;
{
StringBuffer sb = new StringBuffer();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
sb.append("");
getJSONFromStringBuffer(String stringJSON);
}
System.out.println(System.currentTimeMillis() - t);
}
{
StringBuilder sb = new StringBuilder();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
getJSONFromStringBUilder(String stringJSON);
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}
private String getJSONFromStringBUilder(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
private String getJSONFromStringBuffer(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
}
May be below is better.
JSONObject jsonObject=null;
try {
jsonObject=new JSONObject();
jsonObject.put("phonetype","N95");
jsonObject.put("cat","wp");
String jsonStr=jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}

Categories

Resources