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
Related
My current response is
{"response":"validation error","status":"failure","code":400,"errors":["You can not add multiple items with different categories"]}
My current code is :
String errorBody = response.errorBody().string();
JSONObject jsonObject = new JSONObject(errorBody.trim());
jsonObject = jsonObject.getJSONObject("errors");
Iterator<String> keys = jsonObject.keys();
String errors = "";
while (keys.hasNext()) {
String key = keys.next();
JSONArray arr = jsonObject.getJSONArray(key);
for (int i = 0; i < arr.length(); i++) {
errors += key + " : " + arr.getString(i) + "\n";
}
}
I am trying to get the error code to see if it matches specific keywords to handle the response
i think your current code its not to good,better way for u is:
create modelClass for your json output and in retrofit calls write:
if (model.status=='failure' || model.code==400){
print(response.message) // or something like this
}
You can look through the following code snippet
call.enqueue(new Callback<PagedResponse<NotificationModel>>() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onResponse(Call<PagedResponse<NotificationModel>> call, Response<PagedResponse<NotificationModel>> response) {
if (response.isSuccessful()) {
if (response.code() == 200) {
try {
PagedResponse<NotificationModel> notifications = (PagedResponse<NotificationModel>) response.body();
tvRecordsCount.setText("Total "+response.body().getTotal()+" Notifications ");
showNotification(notifications);
} catch (Exception e){
e.printStackTrace();
}
} else {
showToast(getApplicationContext(), "Server Error");
}
}
}
#Override
public void onFailure(Call<PagedResponse<NotificationModel>> call, Throwable t) {
showToast(getApplicationContext(), t.getMessage());
}
});
I managed to get it working with this code:
String errors = "";
String errorBody = response.errorBody().string();
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(errorBody.trim()).getAsJsonObject();
JsonArray errorArray = rootObj.getAsJsonArray("errors");
for (JsonElement pa : errorArray) {
errors = pa.getAsString();
}
I faced with the problem while trying parse JSON array and list all values it has, I have the following JSON format
{
"sdd": {
"token":"1",
"details":[{
"type":"SOME_TYPE",
"l":,
"expiration_date":"12\/2020",
"default":true,
"expired":false,
"token":"1"
}]
}
}
JSON output I have
public void onResponse(JSONObject response) {
try {
JSONArray ja = response.getJSONArray("ssd");
for (int i = 0; i < ja.length(); i++) {
JSONObject jobj = ja.getJSONObject(i);
Log.e(TAG, "response" + jobj.getString("token"));
Log.e(TAG, "response" + jobj.getString("details"));
}
} catch(Exception e) { e.printStackTrace(); }
}
and in the log cat I getting org.json.JSONException: No value for ssd this output
You have typo. Not ssd but sdd. And also sdd is not array, but object.
So you must write like:
JSONObject jb = response.getJSONObject("sdd");
Full parsing code will be like:
public void onResponse(JSONObject response) {
try {
JSONObject sdd = response.getJSONObject("sdd");
JSONArray details = sdd.getJSONArray("details");
for (int i = 0; i < details.length(); i++) {
JSONObject jobj = details.getJSONObject(i);
Log.e(TAG, "response-type:" + jobj.getString("type"));
Log.e(TAG, "response-token:" + jobj.getString("token"));
Log.e(TAG, "response-expiration_date:" + jobj.getString("expiration_date"));
Log.e(TAG, "response-default:" + jobj.getBoolean("default"));
Log.e(TAG, "response-expired:" + jobj.getBoolean("expired"));
}
} catch(Exception e) { e.printStackTrace(); }
}
Also, let me suggest you to use gson this library will help you deserialize your json representations.
ssd is an object.
You can get the array as follows:
JSONObject jo = response.getJSONObject("sdd");
JSONArray ja = jo.getJSONArray("details");
hi you must json file isn't create
is create :
{ "sdd":{
"token":"1",
"details":[
{
"type":"SOME_TYPE",
"expiration_date":"12/2020",
"default":true,
"expired":false,
"token":"1"
}
] } }
after you can get data from code :
public void onResponse(JSONObject response) {
try {
JSONObject ssd = response.getJSONObject("ssd");
JSONArray details = ssd.getJSONArray("details");
for (int i = 0; i < details.length(); i++) {
JSONObject obj = details.getJSONObject(i);
Log.e(TAG, "response" + obj.getString("type"));
Log.e(TAG, "response" + obj.getString("expiration_date"));
Log.e(TAG, "response" + obj.getBoolean("default"));
Log.e(TAG, "response" + obj.getBoolean("expired"));
Log.e(TAG, "response" + obj.getString("details"));
}
}catch (Exception e){e.printStackTrace();}
}
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();
}
}
i made a asynctask routine to comunicate to all my webservices that looks as follows:
protected String[] doInBackground(String... params) {
String parameterString = params[0];
// effectieve http request met de parameters toegevoegd
HttpClient client = new DefaultHttpClient();
HttpGet aanvraag = new HttpGet(server + parameterString);
// foutanalyse van de http request
try
{
HttpResponse antwoord = client.execute(aanvraag);
StatusLine statuslijn = antwoord.getStatusLine();
int statuscode = statuslijn.getStatusCode();
if(statuscode != 200){
Log.i("statuscode verzending", "statuscode= "+ statuscode);
return null;
}
InputStream jsonStream = antwoord.getEntity().getContent();
BufferedReader reader= new BufferedReader(new InputStreamReader(jsonStream));
StringBuilder builder = new StringBuilder();
String lijn;
while((lijn = reader.readLine())!= null){
builder.append(lijn);
}
String jsonData = builder.toString();
// hier beginnen we met de json data te ontmantelen
JSONArray json = new JSONArray(jsonData);
String[] data = new String[35];
Log.i("jsonparser", "lengte geretourde data " + json.length());
for (int i = 0; i < json.length(); i++)
{
data[i] = json.getString(i).toString();
}
return data;
}
catch (ClientProtocolException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
i use the routine everytime i connect to a webservice for my app, (i have about 15 of them)
all these webservices are made (and used) by the programs my software supplier made
now i would like to connect to them with my android app
some of them are working
others don't
what i found out already in my search for this failure:
some jsondata is returned in the form of:
[
"42416",
" ",
" ",
" "
]
other webservices return data as:
true
but the ones i am strugling with the most are looking like:
{
"z00": "1 ",
"z01": 10000,
"z02": "18/06/2010",
"z03": "A",
"z04": "0000",
"z05": 7735,
"z06": "VANNUYSE BVBA",
"z07": "DEEFA",
"z08": 17170,
"z09": "AFLEVEREN HELI IN GEBRUIK",
"z10": "0000",
"z11": "8770 ",
"z12": "INTER ",
"z13": "HELI ",
"z14": "CPCD25 - C240 ",
"z15": "48182 ",
"z16": "",
"z17": "N",
"z18": "0030",
"z19": 0,
"z20": "X",
"z21": " ",
"z22": "J",
"z23": "",
"z24": 0,
"z25": "22/06/2010",
"z26": 16854,
"z27": 0,
"z28": "AFLEVEREN IN GEBRUIK",
"z29": " "
}
how should i form my asynctask routine so she is able to work for all routines?
because my routine works fine now for the first type of data but at 3th type i get an error (didn't tried yet for 2nd type) :
JSONObject cannot be converted to JSONArray
thanks already for al your help guys
If you don't know what(jsonObject or jsonArray) is coming, you may try something like this:
try {
JSONObject jsonObject = new JSONObject(jsonData);
// handle jsonObject
} catch (JSONException e) {
// Try to parse it to a JSONAray.
// Also you can check the exception message here to determine if jsonArray conversion is wanted
try {
JSONArray jsonArray = new JSONArray(jsonData);
// handle jsonArray
} catch (JSONException e) {
// something which is not JsonObject or JsonArray!
}
}
Or try this:
Object jsonAsObject = new JSONTokener(jsonData).nextValue();
if (jsonAsObject instanceof JSONObject) {
// it is JSONObject
JSONObject jsonObject = (JSONObject) jsonAsObject;
} else if (jsonAsObject instanceof JSONArray) {
// it is JSONArray
JSONArray jsonArray = (JSONArray) jsonAsObject;
}
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();
}