Android JSONObject becomes null when trying to send - java

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());

Related

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 json web services

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");

string value to JSON object in java but No value for

response
deneme2="{\"NUKE_USER_NO\":\"1494\",\"WEB_PIN\":\"metin\",\"CARI_NO\":\"2611\",\"FIRMA_ADI\":\"\",\"CARI_UNVANI\":\"LTDSTI\",\"MOD\":\"Müşteri\",\"RENK\":\"'#fbbb5e'\",\"EMAIL\":\"yok\",\"SAHIS_NO\":\"9\",\"ADISOYADI\":\"Metin\",\"YETKILER\":\"UrunListesi, KampanyaList, YeniUrunler, SepetListe, SiparisTakip, BekleyenSiparisler, TaksitBilgi, TaksitliOdeme, CariEkstre, HavaleEftBildir, BankaHesapNumaralari, PcShirbazi, IadeTalep, IadeSonuclari, GarantiSorgulama, ArizaTakip, UyelikBilgilerim, KullaniciList, SevkAdres, CariHareketler, BorcAlacakDurumu, AlisAnalizi, AlisCirolari, BABS, StandartFormlar, ArizaIadeProseduru, SevkiyatProseduru, Organizasyon, Iletisim, SiparisVerme, GuvenliOdeme3D, MailOrderOranlari, KargoTakip, FiyatMod, AnaSayfa, MusteriTemsilcisiniGorsun, Ihaleler, Puanlarim, UyeIsyeri, IadeDegerlendir, IadeSonucDepo\",\"CARI_TIP_NO\":\"6\",\"AKTIF_SEPET\":\"197\",\"KAR_MARJI\":\"0\",\"ODEME_NO\":\"21\",\"DOVIZ_BIRIMI\":\"USD\",\"NAKLIYE_TIP_NO\":\"11\",\"ROLE_ADI\":\"Bayi\"}";
Java code
public JSONObject stringToJson(String deneme2)
{
JSONObject json= new JSONObject();
try {
json.getString(deneme2);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
and then error and exception. It doesn't change string value JSONObject
http://i.stack.imgur.com/roVu5.png
Firstly:
JSONObject json= new JSONObject();
is not taking the actual String which need to be converted.
public JSONObject stringToJson(String deneme2)
{
JSONObject json= new JSONObject(deneme2); //pass a String here
try {
json.getString("key name"); //key for which you need to retrieve data
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
Hope it helps.
deneme2 is string value and deneme2 is JSON writing format. and then i sent deneme2 stringToJson function for string to JSON object bu return exceptation in image and null json.
Try this it will help you : Firstly convert above String to json object
JSONObject jsonobject = new JSONObject(deneme2);
try {
String abc = json.getString("NUKE_USER_NO");
Log.i("Log", abc);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

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