Get errror JSONException: No Value For - android

i have a problem with json parsing code it shows error json no value for konteks lokasi which is use TAG_KONTEKS variable.
This is my code for get json response.
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
//mendapatkan data dari database berupa alamat, konteks, latitude, longitude
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("lat", Integer.toString(latPengguna)));
params.add(new BasicNameValuePair("lng", Integer.toString(lngPengguna)));
params.add(new BasicNameValuePair("konteks", konteksCocok));
Log.d("lat dan lng kirim", "data: " + Integer.toString(latPengguna) + " " + Integer.toString(lngPengguna));
Log.d("konteks kirim", "data: " + konteksCocok);
JSONObject json = jParser.makeHttpRequest(url_webservice, "POST", params);
Log.d("data: ", json.toString());
//menampilkan data lokasi POI
try {
int sukses = json.getInt(TAG_SUCCESS);
if(sukses == 1) {
POI = json.getJSONArray(TAG_POIN);
for(int i = 0; i < POI.length(); i++) {
JSONObject c = POI.getJSONObject(i);
int latDB = c.getInt(TAG_LAT);
int lngDB = c.getInt(TAG_LNG);
String alamat = c.getString(TAG_ALAMAT);
String konteks = c.getString(TAG_KONTEKS);
Log.d("latDB", "data: " + latDB);
Log.d("lngDB", "data: " + lngDB);
Log.d("altDB", "data: " + alamat);
Log.d("ktsDB", "data: " + konteks);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ALAMAT, alamat);
map.put(TAG_KONTEKS, konteks);
POIList.add(map);
}
} else {
Log.d("JSON error", "JSON trouble");
}
} catch(JSONException ex) {
ex.printStackTrace();
}
return null;
}
This is my json response:
{
"success": 1,
"point": [
{
"point": {
"konteks_lokasi": "kuliah",
"nama_lokasi": "Teknik Perkapalan",
"longitude": "-60",
"latitude": "117"
},
"hasil": 15.811388300842
},
{
"point": {
"konteks_lokasi": "kuliah",
"nama_lokasi": "Teknik Kimia",
"longitude": "-80",
"latitude": "145"
},
"hasil": 33.376638536557
},
{
"point": {
"konteks_lokasi": "kuliah",
"nama_lokasi": "Teknik Arsitektur",
"longitude": "-22",
"latitude": "111"
},
"hasil": 53.009433122794
}
]
}
I would be very happy if you could help me...

Longitude and Latitude are strings, as they are surrounded by quotes. so you should get them with getString()
parse them like this
Your JSONArray contain another json Array so parse it like this
int sukses = json.getInt(TAG_SUCCESS);
if(sukses == 1) {
POI = json.getJSONArray(TAG_POIN);
for(int i = 0; i < POI .length(); i++) {
JSONObject c = POI .getJSONObject(i);
JSONObject d = c.getJSONObject(0);
String latDB = d.getString(TAG_LAT);
String lngDB = d.getString(TAG_LNG);
String alamat = d.getString(TAG_ALAMAT);
String konteks = d.getString(TAG_KONTEKS);
}

Related

Unable to fetch data from Json volley

I'm unable to fetch from this type of JSON, I'm confused in how to get data from inside of JsonObject, I got the value of "dealer_name", "phone_no" and "address" but I'm not getting the value of other.
This is my Solution.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
urlLink, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("suraj", response.toString());
try {
for (int i = 0; i < response.length(); i++) {
String name = response.getString("dealer_name");
String phone_no = response.getString("phone_no");
String add = response.getString("address");
JSONObject phone = (JSONObject) response.get(String.valueOf(i));
String acc_name = phone.getString("auto_dealer_id");
String acc_price = phone.getString("accessory_price");
jsonResponse = "";
jsonResponse += "dealer_name: " + name + "\n\n";
jsonResponse += "dealer_phone: " + phone_no + "\n\n";
jsonResponse += "dealer_add: " + add + "\n\n";
jsonResponse += "acc_name: " + acc_name + "\n\n";
jsonResponse += "acc_price: " + acc_price + "\n\n";
}
txt.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(Activity3.this).add(jsonObjReq);
}
This is my JSON data:-
{
"auto_dealer_id": "1",
"dealer_name": "RAJ MOTORS",
"phone_no": "9004296356",
"address": "THANE WEST 40002",
"0": {
"auto_dealer_accessory_id": "1",
"auto_dealer_id": "1",
"accessory_name": "CAR OILING",
"accessory_price": "40"
},
"1": {
"auto_dealer_accessory_id": "2",
"auto_dealer_id": "1",
"accessory_name": "CAR WASHING",
"accessory_price": "40"
},
"2": {
"auto_dealer_gallery_id": "1",
"auto_dealer_id": "1",
"image": "1.jog",
"status": "1",
"sort": "1",
"added_date": "0000-00-00 00:00:00"
}
}
try this code:
try
{
String jsonString="";//your json string here
JSONObject jObject= new JSONObject(jsonString);
Iterator<String> keys = jObject.keys();
while( keys.hasNext() )
{
String key = keys.next();
Log.v("key Items", key);
JSONObject innerJObject = jObject.getJSONObject(key);
Iterator<String> innerKeys = innerJObject.keys();
while( innerKeys.hasNext() )
{
String innerKkey = keys.next();
String value = innerJObject.getString(innerKkey);
Log.v("key = "+key, "value = "+value);
}
}
}
catch (JSONException e){
e.printStackTrace();
}
but it is better approach to convert you JsonObject "1","2"... to JsonArray
Since you want to get json object inside json object,
here you can get
JSONObject number = response.getJSONObject("1");
number.getString("auto_dealer_accessory_id")
and so on.
But there are some better approaches as well. Use Gson and also improve your data structure coming from server. using an array is better option and don't forget to check if the object or string exists before you try to get a value. you can use
jsonObject.has("key")
Try this:
ArrayList acc_name = new ArrayList();
...
...
try
{
JSONObject obj=new JSONObject(responseString);
String name = obj.getString("dealer_name");
String phone_no = obj.getString("phone_no");
String add = obj.getString("address");
Iterator<String> keys = obj.keys();
while( keys.hasNext() )
{
String key = keys.next();
JSONObject innerJObject = obj.getJSONObject(key);
Iterator<String> inKeys= innerJObject .keys();
while( inKeys.hasNext() )
{
String inKeys= keys.next();
acc_name.Add(innerJObject .getString(inKeys);
..
}
}
}
catch (JSONException e)
{ e.printStackTrace(); }

Fetching an array of coordinates from sql server and plotting it on maps in android

I am trying to create an android application where I want to receive an array of coordinates from SQL server using web services.
Suppose there is an array containing 30 coordinates(Latitude, Longitude) in SQL server, I want these coordinates to be fetched using web-services and plotting the markers on my map created in my application.
Please Help. Thank You!!
Hi Hope This help to u
class MyTask extends AsyncTask<Void, Void, Void> {
String msg = "";
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
URL url = new URL(
"url");
InputStream isr = url.openStream();
int i = isr.read();
while (i != -1) {
msg = msg + (char) i;
i = isr.read();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
Log.i("========>Message<=====",msg);
try
{
JSONObject mainObject=new JSONObject(msg);
//use this get Toast message of each object Toast.makeText(getActivity(), "hello1 "+mainObject, Toast.LENGTH_LONG).show();
JSONObject maJsonObject = mainObject.getJSONObject("Response");
//Toast.makeText(getActivity(), "hello2 "+maJsonObject, Toast.LENGTH_LONG).show();
JSONArray jsonArray = maJsonObject.getJSONArray("Result");
//Toast.makeText(getActivity(), "hello3 "+jsonArray, Toast.LENGTH_LONG).show();
// Log.i("<======JSONARRAY==>",jsonArray.toString());
for(int i=0;i<jsonArray.length();i++)
{
JSONObject subObject=jsonArray.getJSONObject(i);
String vocherId=subObject.getString("Voucher No");
tv1.setText("Voucher ID: "+vocherId);
String vocherAmount=subObject.getString("Voucher Amount");
tv2.setText(vocherAmount);
String store_name=subObject.getString("Store Name");
tv3.setText(store_name);
String location=subObject.getString("Location");
tv4.setText(location);
String recipient_name=subObject.getString("Recipient Name");
tv5.setText(recipient_name);
String Recipent_mobile=subObject.getString("Recipient Mobile");
tv6.setText(Recipent_mobile);
Toast.makeText(getActivity(), vocherId+"\n"+vocherAmount+"\n"+location+"\n", Toast.LENGTH_LONG).show();
Log.i("==vocherId==", vocherId);
}
/*JSONObject jsonRootObject = new JSONObject(msg);
JSONArray jsonArray = jsonRootObject.optJSONArray("Response");
for(int i=0; i < jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String VoucherId = jsonObject.optString("voucherid").toString();
String Amount = jsonObject.optString("amount").toString();
String StoreName = jsonObject.optString("storename").toString();
String Location=jsonObject.optString("location").toString();
String Recipient_Name=jsonObject.optString("recipient_name").toString();
String Recepient_Mobile=jsonObject.optString("recepient_mobile").toString();
msg += "Node"+i+" : \n voucerId= "+ VoucherId +" \n Amount= "+ Amount +" \n StoreName= "+ StoreName +" \n Location="+Location+"\n Recipient_Name"+Recipient_Name+"\n"+Recepient_Mobile;
}
tv1.setText(msg);*/
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
I am using volley library for network calling you can further research how volley is implemented into android
when you hit YOUR_WEB_SERVICE_URL in response it will send JSON array after that parsing it you can place markers
The response should be like
[
{
"id": "1",
"lat": "21.3",
"lon": "23.55",
}, {
"id": "2",
"lat": "21.3",
"lon": "23.55",
}
//...
{
"id": "30",
"lat": "21.3",
"lon": "23.55"
}
]
JsonArrayRequest req = new JsonArrayRequest(YOUR_WEB_SERVICE_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject location = (JSONObject)response.get(i);
String id = location.getString("id");
String lat = location.getString("lat");
String lon = location.getString("lon"); //lat and lon are String you have to typecast it to double before using it
Latlon ll = new Latlon(lat, lon);
placeYourMarkerFuction(ll);
}
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Add Request to queue
}

How to get Multiple return value From JSON in Android

I have received a string value from JSON, but when I add that JSON value to a JSON array it gives an error stating that it can not convert String value to JSONArray. Please help me.
In the response there are a 3 values in "Value"
protected class AsyncMenuRate extends
AsyncTask<ForGettingRate, JSONObject, JSONObject> {
JSONObject jsonObj = null;
#Override
protected JSONObject doInBackground(ForGettingRate... params) {
RestAPI api = new RestAPI();
try {
jsonObj = api.MenuRate(params[0].getTableId(), params[0].getMenulist());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncCreateUser", e.getMessage());
}
return jsonObj;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected void onPostExecute(JSONObject objects) {
try {
//String ss= objects.getString("Value").;
JSONArray jarray=objects.getJSONArray("Value");
//jarray = new JSONArray(ss);
for (int i = 0; i < jarray.length(); i++) {
jsonObj = jarray.getJSONObject(i);
}
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(DisplayActivity.this, "Successfully inserted...", Toast.LENGTH_LONG).show();
}
}
This is a function that I have return value:
String menuTotal = "0";
String item_rate;
public String MenuRate(int t_id, String menunameoflist) {
if (dbConnection.State.ToString() == "Closed") {
dbConnection.Open();
}
if (db.ChkDb_Value("select * from table_status where table_type='" + "A/C" + "'and t_id='" + t_id + "'"))
item_rate = db.getDb_Value("select rate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
else if (db.ChkDb_Value("select * from table_status where table_type='" + "Non A/C" + "'and t_id='" + t_id + "'"))
item_rate = db.getDb_Value("select non_ACrate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
else
item_rate = db.getDb_Value("select driverRate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
//menuRate = db.getDb_Value("select menu_id From menu where m_name='" + getMenuname + "'");
dbConnection.Close();
return item_rate;
}
This is the JSON format:
{
"name": "MenuRate",
"parameters": [
{
"name": "t_id",
"type": "int32"
},
{
"name": "menunameoflist",
"type": "string"
}
],
"returnvalue": "string"
}
This is function that I have get a response from JSON:
public JSONObject MenuRate(int t_id, String menunameoflist) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "MenuRate");
p.put("t_id",mapObject(t_id));
p.put("menunameoflist",mapObject(menunameoflist));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
First your MenuRate method returns String not JSONObject. So you had to get that as String and convert it into JSONObject, as shown below.
#Override
protected JSONObject doInBackground(ForGettingRate... params) {
RestAPI api = new RestAPI();
try {
String jsonString = api.MenuRate(params[0].getTableId(), params[0].getMenulist());
return new JSonObject(jsonString);
} catch (Exception | JsonException e) {
// TODO Auto-generated catch block
Log.d("AsyncCreateUser", e.getMessage());
}
return jsonObj;
}
Don't forgot to add the JsonException, no problem some how it will ask to add the exception.
Now the string value is converted to JSON, so now you can fetch the values and while fetching use opt instead of get like optJsonArray("key") instead of getJsonArray("key") by this way we will get null value instead of exception, if the key is not present in the JSON.
Now coming to the "value" key access in your JSON response. Below is the JSON value which you have provided,
{
"name": "MenuRate",
"parameters": [{
"name": "t_id",
"type": "int32"
}, {
"name": "menunameoflist",
"type": "string"
}],
"returnvalue": "string"
}
In your question you have mentioned that you need access a json array with the key "Value". But in this there is no array with key "Value". So the below code will explain you how to access the "name" string value and "parameters" Json array.
try {
//Name String value...
String name = objects.optString("name");
//Parameter Json Array...
JSONArray parameterarray =objects.optJSONArray("parameters");
for (int i = 0; i < parameterarray.length(); i++) {
JsonObject jsonObj = parameterarray.optJSONObject(i);
}
} catch (Exception e) {
e.printStackTrace();
}
Hope this is helpful :)

JsonArray post from Android to Laravel Rest Error

I am trying to post some data form android app to Laravel rest api. The data is converted and posted as jsonArray.
The code works fine in HttpRequester (Firefox extension) but throws 500 Internal Server Error when posted from Android.
Android
public static int check(String token) throws IOException
{
int flag;
String response=Constants.EMPTY_STRING;
URL mUrl=null;
HttpURLConnection mConnection=null;
String message="";
JSONObject myObject1 = new JSONObject();
JSONObject myObject2 = new JSONObject();
JSONObject myObject3 = new JSONObject();
JSONArray myArray = new JSONArray();
JSONObject mySentObject = new JSONObject();
try {
myObject1.put("id","01");
myObject1.put("name","Ali Jibran");
myObject1.put("date","2016-04-01");
myArray.put(myObject1);
myObject2.put("id","02");
myObject2.put("name","Imran Raja");
myObject2.put("date","2016-05-03");
myArray.put(myObject2);
myObject3.put("id","03");
myObject3.put("name","M.Quddus Raja");
myObject3.put("date","2015-06-01");
myArray.put(myObject3);
//mySentObject.put("data",myArray.toString());
//message = mySentObject.toString();
message = myArray.toString();
} catch (JSONException e) {
e.printStackTrace();
}
//String mQuery = Constants.APP_TOKEN_KEY
// + Constants.EQUALS + token + Constants.AMPERSAND + "posted=" + message;
String mQuery = "posted=" + message;
Log.d(Constants.APP_TAG,"================== Checking =================" );
Log.d(Constants.APP_TAG, "check -> Query is : " + mQuery);
mUrl = new URL(Constants.APP_URL + "info?" + mQuery);
mConnection = (HttpURLConnection) mUrl.openConnection();
mConnection.setDoInput(true);
mConnection.setDoOutput(true);
//mConnection.setFixedLengthStreamingMode(message.getBytes().length);
mConnection.setConnectTimeout(5000);
mConnection.setInstanceFollowRedirects(false);
mConnection.setRequestMethod(Constants.POST);
mConnection.setRequestProperty("Content-type", "application/json");
mConnection.setRequestProperty("charset", "utf-8");
//Write Post Data
DataOutputStream wr = new DataOutputStream(mConnection.getOutputStream());
wr.writeUTF(message.getBytes().toString());
wr.flush();
wr.close();
flag = mConnection.getResponseCode();
if (flag != 200) {
Log.d(Constants.APP_TAG,"Failure " + flag + " " + mConnection.getResponseMessage());
}
if (flag == 200){
response = readData(mConnection);
try
{
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.has("reply"))
Log.d(Constants.APP_TAG,"Reply received -> " + jsonObject.getString("reply"));
if(jsonObject.has("newmercs"))
Log.d(Constants.APP_TAG,"Data received -> " + jsonObject.getString("newmercs"));
if(jsonObject.has("count"))
Log.d(Constants.APP_TAG,"Count received -> " + jsonObject.getString("count"));
} catch (JSONException e)
{
e.printStackTrace();
}
}
return flag;
}
Laravel 5.0
Route::post('info',function(){
//$newmercs = json_decode(Input::get('posted'),true);
$newmercs = json_decode(Input::get('posted'));
$reply = "";
$count = 0;
foreach ($newmercs as $newmerc){
$count++;
}
if ($count > 0){
$reply = 'Success';
}else {
$reply = 'Failure';
}
return response()->json(compact('newmercs','reply','count'));
});
This is what i should get (HttpRequester also returns the same)
{
"newmercs":
[
{
"date": "2016-04-01",
"id": "01",
"name": "Ali Jibran"
},
{
"date": "2016-05-03",
"id": "02",
"name": "Imran Raja"
},
{
"date": "2015-06-01",
"id": "03",
"name": "M.Quddus Raja"
}
],
"reply": "Success",
"count": ​3
}
You can use Retrofit Lib to communicate with your API, it's so much easier.
Retrofit doc : http://square.github.io/retrofit/
Have a great day

How to get complex JSON from URL?

My json is like this
{
"results": [{
"syllabus": "CBSE",
"grade": "5",
"subject": "Kannada",
"topic": "Grammar Level 1",
"id": 28
}]
}
Using Volley
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
System.out.println(person.toString());
String syllabus = person.getString("syllabus");
String grade= person.getString("grade");
jsonResponse += "Name: " + syllabus + "\n\n";
jsonResponse += "Email: " + grade + "\n\n";
}
Your Json have an object and then array.. try like this
JsonObjectRequest req = new JsonObjectRequest(urlJsonArry,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONOArray array = response.getJSONArray("results")
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < array.length(); i++) {
JSONObject person = (JSONObject) array
.get(i);
System.out.println(person.toString());
String syllabus = person.getString("syllabus");
String grade= person.getString("grade");
jsonResponse += "Name: " + syllabus + "\n\n";
jsonResponse += "Email: " + grade + "\n\n";
}
if (!result.equalsIgnoreCase("")) {
try {
JSONObject jsonObject = new JSONObject(result); //result is what you get responce
JSONArray jsonArray = jsonObject.optJSONArray("results");
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjects = jsonArray.optJSONObject(i);
String syllabus = jsonObjects.optString("syllabus");
Int grade = jsonObjects.optInt("grade");
String subject = jsonObjects.optString("subject");
String topic = jsonObjects.optString("topic");
Int id = jsonObjects.optInt("id");
}
} else {
Log.e("", "error parse json", "--->" + e.getMessage());
}
} catch (Exception e) {
Log.e("", "error parse json", "--->" + e.getMessage());
}
} else {
Log.e("", "error parse json", "--->" + e.getMessage());
}

Categories

Resources