I am using Volley in my project for handling network requests. Here is a sample JSON my server returns when it has data then fatch otherwise give error
{
"message_status": true,
"data": [
{
"message_id": "88",
"message_text": "hi,",
"message_link": "0",
},
}
{
"message_status": false,
"message": "Message not available!"
}
this is my code
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_msg,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("data") && !jsonObject.isNull("data")) {
String success = jsonObject.getString("message_status");
String message = jsonObject.getString("message");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (success.equals("true")) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
ChatMessage chatMessage = new ChatMessage();
chatMessage.setMessageUser(object.getString("username"));
chatMessage.setMessageTime(object.getString("time"));
chatMessage.setMessageText(object.getString("message_text"));
chatMessage.setUserId(object.getString("user_id"));
chatMessage.setFileName(object.getString("file_name"));
chatMessage.setMessageFile(object.getString("message_link"));
chatMessage.setMessageID(object.getString("message_id"));
chatMessages.add(chatMessage);
}
setupListview();
} else {
// get message using error key
String error = "Response : " + success + " = " + message;
Toast.makeText(ChatActivity.this, error, Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(ChatActivity.this, "data not available", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(ChatActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
when data have no value then show no item message but its give server error
Try this:
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("message_status");
String message = jsonObject.getString("message");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (jsonArray != null || jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
ChatMessage chatMessage = new ChatMessage();
chatMessage.setMessageUser(object.getString("username"));
chatMessage.setMessageTime(object.getString("time"));
chatMessage.setMessageText(object.getString("message_text"));
chatMessage.setUserId(object.getString("user_id"));
chatMessage.setFileName(object.getString("file_name"));
chatMessage.setMessageFile(object.getString("message_link"));
chatMessage.setMessageID(object.getString("message_id"));
chatMessages.add(chatMessage);
//loading.setVisibility(View.GONE);
}
setupListview();
} else {
// get message using error key
Toast.makeText(ChatActivity.this, "error 1" + message + success, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
}
Related
I am using RecyclerView to display data fetched from DB. It's not working.
GETTING AN ERROR E/Volley: [33049] BasicNetwork.performRequest: Unexpected response code 404.
Need to parse below Response:-
[
{
"code":"23232",
"desc":"ddddjdkdkcn",
"price":[
"price"
]
},
{
"code":"de33fd",
"desc":"ddds",
"price":[
"price"
]
}
]
public class Background {
String url = "http://192.168.0.103/android_fetch.php";
Context context;
ArrayList<Data> arrayList = new ArrayList<>();
public Background(Context context) {
this.context = context;
}
public ArrayList<Data> getList() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, (String) null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int count = 0;
while (count < response.length()) {
try {
JSONObject jsonObject = response.getJSONObject(count);
Data data = new Data(jsonObject.getString("code"), jsonObject.getString("desc"), jsonObject.getString("price"));
arrayList.add(data);
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
MySingleton.getInstance(context).addToRequestque(jsonArrayRequest);
return arrayList;
}
}
First check your request in Postman . There is some error at back-end php side. After that your parsing method is also wrong .
There is mistake in this line i think .
Data data = new Data(jsonObject.getString("code"), jsonObject.getString("desc"), jsonObject.getString("price"));
here you try to get all as jsonObject but last price is JSONArray .
Try this way .
#Override
public void onResponse(JSONArray jsonresponse) {
try {
Log.i("get response", "get response" + jsonresponse);
for (int i = 0; i < jsonresponse.length(); i++) {
JSONObject response = jsonresponse.getJSONObject(i);
String code = response.getString("code");
String desc = response.getString("desc");
if (response.getJSONArray("price") != null && response.getJSONArray("price").length() > 0) {
JSONArray priceArray = response.getJSONArray("price");
final int numberOfItemsInResp = priceArray.length();
for (int j = 0; j < numberOfItemsInResp; j++) {
String price = priceArray.getString(j);
}
}
}
} catch (Exception e) {
Common.ProgressDialogDismiss();
e.printStackTrace();
}
}
I am parsing json value into gridView, but somehow its not showing any value in gridView, i am confused in json code as i think i am missing something in this code..kindly check :
private void getData() {
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
String DATA_URL = "http://........nList";
StringRequest stringRequest = new StringRequest(Request.Method.POST, DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONArray json = new JSONArray(response);
for (int i = 0; i < json.length(); i++) {
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = json.getJSONObject(i);
//getting image url and title from json object
pid.add(obj.getInt(String.valueOf(TAG_PID)));
pname.add(obj.getString(TAG_PNAME));
pdetails.add(obj.getString(TAG_PDETAILS));
pmobile.add(obj.getString(TAG_MOBILE));
pemail.add(obj.getString(TAG_EMAIL));
images.add(obj.getString(TAG_IMAGE_URL));
names.add(obj.getString(TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//Creating GridViewAdapter Object
PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);
//Adding adapter to gridview
pmpigeonlistadapter.notifyDataSetChanged();
gridView.setAdapter(pmpigeonlistadapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(PMPigeonListingActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("country", PostCountry);
params.put("strain", PostStrain);
params.put("distance", PostDistance);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
this is my json output:
{
"status_code": 200,
"status": "OK",
"status_message": "Success",
"pigeon_list": [
{
"id": "1",
"pigeon_name": "sofiee",
"auth_token": "58809c7129a5a",
"country_code": "AE",
"strain_id": "75",
"distance": "3",
"pigeon_price": "50.00",
"pigeon_details": "One of the best ",
"image": "http:.98a8ac5.jpeg",
"pedigree_image": "http://...1.jpeg",...
"status": "",
"created": "2017-01-19 16:52:14",
"updated": "0000-00-00 00:00:00",
"strain_name": "Janssen/gaston wowers ",
"usr_mobile": "+971/505040009",
"usr_image": "http://....19a.jpeg",
"usr_email": "...edo#gmail.com"
},
I am getting response in toast also, only json problem is thr ...
this is the php code:
public function searchPigeonList()
{
$data = (array)$this->request->input('json_decode');
$returnArr = $this->resp_arr;
$returnArr['pigeon_list'] = array();
$conn = ConnectionManager::get('default');
$query = "SELECT `pg`.*,`ps`.name as strain_name,`us`.mobile as usr_mobile,`us`.image as usr_image,`us`.email as usr_email FROM
`pigeons` as `pg` INNER JOIN `users` as `us` ON `pg`.`auth_token` = `us`.`uniq_id` INNER JOIN `pigeon_strain` as `ps` ON `ps`.`id` = `pg`.`strain_id` ";
// $query .= "WHERE `pg`.`country_code` = '".$data['country_code']."' ";
$cnt_cd = $data['country_code'];
$str_id = $data['strain_id'];
$dst = $data['distance'];
$conditions = array();
if($cnt_cd !="") {
$conditions[] = "`pg`.country_code='$cnt_cd'";
}
if($str_id !="") {
$conditions[] = "`pg`.strain_id='$str_id'";
}
if($dst !="") {
$conditions[] = "`pg`.distance='$dst'";
}
if (count($conditions) > 0) {
$query .= " WHERE " . implode(' AND ', $conditions);
$query .= " AND `pg`.status='approved'";
}
//echo $query;exit;
$stmt = $conn->execute($query);
$returnArr['status_code'] = 200;
$returnArr['status'] = "OK";
$returnArr['status_message'] = "Success";
$returnArr['pigeon_list'] = $stmt ->fetchAll('assoc');
if ($this->request->is('post')) {
echo json_encode($returnArr);
exit;
}
}
try {
JSONArray json = new JSONObject(response).getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
JSONObject obj = null;
try {
obj = json.getJSONObject(i);
pid.add(obj.getInt("id"));
pname.add(obj.getString("pigeon_name"));
pdetails.add(obj.getString("pigeon_details"));
pmobile.add(obj.getString("usr_mobile"));
pemail.add(obj.getString("usr_email"));
images.add(obj.getString("usr_image"));
names.add(obj.getString("pigeon_name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(JSONException je){
je.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
try replacing with
Try this.
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONObject responseObject=new JSONObject(response);
JSONArray json = responseObject.getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = json.getJSONObject(i);
//getting image url and title from json object
pid.add(obj.getInt(String.valueOf(TAG_PID)));
pname.add(obj.getString(TAG_PNAME));
pdetails.add(obj.getString(TAG_PDETAILS));
pmobile.add(obj.getString(TAG_MOBILE));
pemail.add(obj.getString(TAG_EMAIL));
images.add(obj.getString(TAG_IMAGE_URL));
names.add(obj.getString(TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//Creating GridViewAdapter Object
PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);
//Adding adapter to gridview
pmpigeonlistadapter.notifyDataSetChanged();
gridView.setAdapter(pmpigeonlistadapter);
}
When I'm JSONObject jsonObj = new JSONObject(jsonStr);
I enter in catch because my json is not a array.
How can I get this format ?
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2:8080/PFA/crimes";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray data = jsonObj.getJSONArray("crime");
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String day_week = c.getString("day_week");
String naturecode = c.getString("naturecode");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("day_week", day_week);
contact.put("naturecode", naturecode);
// adding contact to contact list
List.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
JSON:
{
"crime": {
"compnos": "zerezrerzerezzr",
"day_week": "rtkeertoeirtj ,ertkierj",
"domestic": "false",
"fromdate": "ekrjtner",
"id": "1",
"location": "etritkjrtoijty",
"main_crimecode": "oijereriotjeroi",
"month": "455",
"naturecode": "zetzeeztet",
"reportingarea": "58",
"reptdistrict": "zorigjrgoijtoi",
"shift": "rektenrloj",
"shooting": "true",
"streetname": "kjrtnerkj",
"ucrpart": "irtjeroitejroirj",
"weapontype": "kejfnergkrtnh",
"x": "11",
"xstreetname": "zekjrnetk",
"y": "11",
"year": "45"
}
}
JsonObject crime = jsonObj.getJsonObject("crime");
JsonObject compnos = crime.getJsonObject("compnos");
.
..
...
There is no jsonArray in your json value. Give up to get jsonArray.
Try this:
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jsonMetaObject = jsonMasterObject.getJSONObject("crime");
instead of
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray data = jsonObj.getJSONArray("crime");
Because you get jsonObject in key of crime not JsonArray.
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
}
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());
}