Android json web services - java

I am working on web services that I want from my Android application connect to Oracle database, so my server is in java which connects to database... and the connection is done! What I am stuck to is that I got data from database and converted to json in the server side when I retrieve it in my Android app there I get null pointer exception.
Function to create my json in server side:
public static String constructJSN(String tag, boolean status,ArrayList<Teacher> f) {
JSONObject obj = new JSONObject();
try {
for(int i=0;i<f.size();i++){
obj.put("tag", tag);
obj.put("status", new Boolean(status));
String json = new Gson().toJson(f);
obj.put("data",json);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
}
return obj.toString();
}
and when i print it i get :
{"tag":"login","status":true,"data":"[{\"name\":\"rasha\",\"classes\":\"b\",\"freetime\":\"3-4\"},{\"name\":\"heba\",\"classes\":\"a\",\"freetime\":\"3-4\"},{\"name\":\"omnia\",\"classes\":\"c\",\"freetime\":\"2-6\"}]"}
in android client side :
String j= obj.get("data").toString();
JSONObject myJsonObj = new JSONObject(j);
String Name = myJsonObj.getString("name");
String Classes = myJsonObj.getString("classes");
Toast.makeText(getApplicationContext(), Name+ " " + Classes, Toast.LENGTH_LONG).show();
and here I get an error while debugging:
Method threw java.lang.NullPointerException exception. Cannot
evaluate org.json.JSONObject.toString()

JSONObject myJsonObj = new JSONObject(j);
JsonArray data = myJsonObj.getJsonArray("data");
for (JSONObject jObjc: JsonArray) {
String Classes = jObjc.getString("classes");
}

Try the below:
Declare a static JsonObject and assign it to null
static JSONObject jObj = null;
Then in ur web service call, assign this to the JSON Response like this
jObj = new JSONObject(result);
jObj.getString("data");

Related

Modifying nested JSONObject using json simple

Trying to modify values of a JSONObject within another JSONbject throws cannot find symbol error for method getJSONObject...
I can't use the getJSONObject method, a workaround for me was:
JSONObject Player = (JSONObject) PlayerTemp.get("Player");
Player.put("Language", "German");
However the following would not work:
JSONObject Player = PlayerTemp.getJSONObject("Player");
Here is my whole code example where I try to modify a value within a JSONObject that's nested within another JSONObject:
JSONParser parser = new JSONParser();
try (Reader reader = new FileReader("../resources/PlayerTemp.json")) {
JSONObject PlayerTemp = (JSONObject) parser.parse(reader);
PlayerTemp.getJSONObject("Player").put("Language", "German");
System.out.println(PlayerTemp.get("Player").toString());
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
error: cannot find symbol
PlayerTemp.getJSONObject("Player").put("Language", "German");
^
There is no method called getJSONObject in JSONObject class, so you have to use get() with explicit type casting. If you want more advance methods like getJSONObject consider using Gson and jackson
JSONObject PlayerTemp = (JSONObject) parser.parse(reader);
JSONObject temp = (JSONObject) PlayerTemp.getJSONObject("Player");
temp.put("Language", "German");

try catch code reading JSON file Android

having some serious problem when trying to read a local JSON file. I've looked everywhere for many days now and the best and farthest I could get was copying from Faizan's answer.
Reading a json file in Android
How come that Android Studio doesn't let me generate the second try-catch code block here?
Help and advice are very much appreciated!!
This is My code
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("names.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
String jsonString = loadJSONFromAsset();
try {
JSONObject json = new JSONObject(jsonString);
JSONObject jObject = json.getJSONObject("female");
JSONObject jObject2 = jObject.getJSONObject("adult");
String name = jObject2.toString();
}
catch (Exception e) {
e.printStackTrace();
}
}
How come that Android Studio doesn't let me generate the second
try-catch code block here?
Simply, because your code is not inside a method.
Doing something like below should solve the error.
public void someMethodIdentifier(){ // doesn't have to be void return type, you know better than me what type you want to return.
String jsonString = loadJSONFromAsset();
try {
JSONObject json = new JSONObject(jsonString);
JSONObject jObject = json.getJSONObject("female");
JSONObject jObject2 = jObject.getJSONObject("adult");
String name = jObject2.toString();
}
catch (Exception e) {
e.printStackTrace();
}
}
Note - from the looks of the statements that's contained within the try block I think you intended to return some data? if that's the case just replace the void return type with the appropriate return type and return that data.

Android JSONObject becomes null when trying to send

When I'm trying to push a JSONObject over a data stream, and I've built the JSONObject properly, but then I try and publish it to the stream it is null.
JSONObject position = new JSONObject();
try {
position.put("lat", location.getLatitude());
position.put("lng", location.getLongitude());
} catch (JSONException e) {
System.out.println("json not work");
e.printStackTrace();
}
System.out.println(position) //result: {"lat":37,"lng":-122}
pubNub.publish().message(position)//never sent, if other type it works
try pubNub.publish().message(position.toString());

Cannot be converted to JSON

I am reading some JSON from with in an Android App, yet it will not recognise the following JSON
{"value":"1000","make":"Ford","model":"Focus","desc":"1.9 Zetec","Fuel":"petrol"}
This is output generated from a PHP file on a webserver. Is there something wrong with this JSON or is the problem with the following code?
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
String car_value = json_data.getString("value");
Log.e("JSON",car_value);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Given String is not a Json Array. That is Json Object. So parse with Json object.
like below
try {
JSONObject jObject = new JSONObject(result);
String value = jObject.getString("value");
String make = jObject.getString("make");
// TODO and so on
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The json data you are receiving is not a JSONArray. It is a JSONObject. So, you should receive it as:
JSONObject jArray = new JSONObject(result);
And then if you want value you can get it like
String car_value = jArray.getString("value");

Help with JSON error handling and google translate api

I'm currently parsing a JSON response from the Google Translate API. I'm able to do this with no problem. Seeing as how I don't have a lot of XML experience (I'm more of an XML guy), I'm having trouble figuring out how to implement some error handling in my JSON parsing. I am using the JSON j2me library.
Here is a successful response:
{"responseData": {"translatedText":"Teks te vertaal ...","detectedSourceLanguage":"en"}, "responseDetails": null, "responseStatus": 200}
And here is an unsuccessful response:
{"responseData": null, "responseDetails": "could not reliably detect source language", "responseStatus": 400}
So, if the translation is unsuccessful, I want to put the value of "responseDetails" into a string. Here is my parsing code, which is not currently parsing out responseDetails correctly. Instead, the "catch" of the "try" is being caught.
try {
JSONObject responseObject = new JSONObject(response);
if (responseObject != null) {
JSONObject responseData = responseObject
.getJSONObject("responseData");
if (responseData != null) {
String translatedText = responseData
.getString("translatedText");
Notify.alert(translatedText);
} else {
String responseDetails = responseObject
.getString("responseDetails");
Notify.alert(responseDetails);
}
}
} catch (Exception e) {
Notify.alert("Unable to translate!");
}
Can anyone see where I'm going wrong?
Thanks!
Since you say the catch block is being triggered, I'd start debugging by looking at what Exception is being thrown. You could simply append your alert string to include e.toString().
So change your alert in the catch block to be:
Notify.alert("Unable to translate! " + e.toString());
And see what the actual error that's being thrown is.
Based on your comment, yes it looks like it's trying to create a JSONObject on a null value, so nest another try/catch block and parse it accordingly that way.
try {
JSONObject responseObject = new JSONObject(response);
if (responseObject != null) {
/* Try create a new JSON object from the
* responseData object. If it fails,
* display an alert */
try {
JSONObject responseData = responseObject
.getJSONObject("responseData");
if (responseData != null) {
String translatedText = responseData
.getString("translatedText");
Notify.alert(translatedText);
}
} catch (Exception e) {
String responseDetails = responseObject
.getString("responseDetails");
Notify.alert(responseDetails);
}
}
} catch (Exception e) {
Notify.alert("Unable to translate outer block!");
}

Categories