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);
}
Related
private void loadCricketPlayer() {
//getting the progressbar
final ProgressBar cricketProgressBar = findViewById(R.id.cricketProgressBar);
//making the progressbar visible
cricketProgressBar.setVisibility(View.VISIBLE);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url_new,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
cricketProgressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
JSONArray jArray = obj.getJSONArray("squad");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
JSONArray bArray = obj.getJSONArray("players");
for (int j = 0; j < bArray.length(); j++){
JSONObject jsonObject1 = bArray.getJSONObject(j);
cricket_Player_POJO cricketPlayer = new cricket_Player_POJO(jsonObject1.getString("name"));
cricketListItem.add(cricketPlayer);
}
}
cricket_Player_List cricketList = new cricket_Player_List(cricketListItem, getApplicationContext());
cricketPLayerlistView.setAdapter(cricketList);
} catch (JSONException e) {
e.printStackTrace();
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
this is my json Array data for fetching the data from the server
This is my JSONARRAY example. For fetching the data:
{
"squad": [
{
"name": "Australia",
"players": [
{
"pid": 7252,
"name": "Tim Paine"
},
{
"pid": 489889,
"name": "Pat Cummins"
},
{
"pid": 5334,
"name": "Aaron Finch"
},
]
}]
}
How can I Fetch this code Help me How can I do it I am using volley for this and I want to fetch this data in the listview android
How can I Fetch this code Help me How can I do it I am using volley for this and I want to fetch this data in the listview android
replace with this code
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
JSONArray jArray = obj.getJSONArray("squad");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
JSONArray bArray = jsonObject.getJSONArray("players");
for (int j = 0; j < bArray.length(); j++){
JSONObject jsonObject1 = bArray.getJSONObject(j);
cricket_Player_POJO cricketPlayer = new cricket_Player_POJO(jsonObject1.getString("name"));
cricketListItem.add(cricketPlayer);
}
}
cricket_Player_List cricketList = new cricket_Player_List(cricketListItem, getApplicationContext());
cricketPLayerlistView.setAdapter(cricketList);
} catch (JSONException e) {
e.printStackTrace();
}
I'm trying to parse this JSON:
{
"data": [{
"name": "Griya Legita",
"is_broken": false,
"is_repaired": false,
"is_ok": true,
"asset_parent": null
},
{
"name": "4th Floor",
"is_broken": true,
"is_repaired": false,
"is_ok": false,
"asset_parent": {
"name": "Buni Building",
"is_broken": true,
"is_repaired": false,
"is_ok": false
}
}]
}
This JSON has a JSON object in a JSON array. But when I call the JSON object it says that it cannot be converted.
This is the code that I've tried:
class daftarAset extends AsyncTask < String, String, String > {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("LOADING...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String...params) {
String link_url = "https://example.com/api/assets";
HttpHandler sh = new HttpHandler();
String json = sh.makeServiceCall(link_url);
Log.e(TAG, "Response from url: " + json);
if (json != null) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject ar = data.getJSONObject(i);
String aset = ar.getString("name");
JSONObject parent = ar.getJSONObject("asset_parent");
String nama = parent.getString("name");
HashMap map = new HashMap();
map.put(in_aset, aset);
map.put(in_ruang, nama);
data_map.add(map);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
list = (ListView) getView().findViewById(R.id.baik_list);
adapter = new AssetsAdapter(getActivity(), data_map);
list.setAdapter(adapter);
setListViewHeightBasedOnChildren(list);
}
});
}
return null;
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
}
I don't know what's gone wrong in my code. I'm following this tutorial and I feel like it must be correct but it has an error because the JSON cannot be converted.
This is my error:
W/System.err: org.json.JSONException: Value null at asset_parent of type org.json.JSONObject$1 cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:100)
at org.json.JSONObject.getJSONObject(JSONObject.java:613)
at com.mqa.android.monas.Fragment.BaikFragment$daftarAset.doInBackground(BaikFragment.java:188)
at com.mqa.android.monas.Fragment.BaikFragment$daftarAset.doInBackground(BaikFragment.java:162)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
First make sure JSONObject contains asset_parent key and corresponding key value is not null. Then retrieve value from JSONObject.
Use this code :
JSONObject jsonObject = new JSONObject(json);
JSONArray data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject ar = data.getJSONObject(i);
String aset = ar.getString("name");
HashMap map = new HashMap();
map.put(in_aset, aset);
if(ar.has("asset_parent") && !ar.isNull("asset_parent") ){
JSONObject parent = ar.getJSONObject("asset_parent");
String name = parent.getString("name");
map.put(in_ruang, name );
}else{
map.put(in_ruang, null );
}
Log.i("Test", "Map: " + map.toString());
data_map.add(map);
................
.............
}
Hope it will solve your problem.
Let me know if your problem is solved.
Try This
if(mJsonObject.has("Data") && !mJsonObject.isNull("Data") ) {
// code here
}
Make a check whether the object is available or not like below
if(ar.optJSONObject("asset_parent")) {
if(ar.getJSONObject("asset_parent") != null) {
//process the object
}
}
public void get_user_details(){
StringRequest stringRequest = new StringRequest( Request.Method.GET,User_Details_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.e("Response",""+response);
JSONObject obj = new JSONObject(response);
JSONArray user_holder = obj.getJSONArray("User_holder");
JSONObject user = user_holder.getJSONObject(0);
user_id=user.getString("id");
user_name=user.getString("user_name");
user_password=user.getString("user_password");
user_emailid=user.getString("user_email");
PreferenceUtils.saveEmail(user_emailid,Register_Page.this);
PreferenceUtils.saveUsername(user_name,Register_Page.this);
PreferenceUtils.savePassword(user_password,Register_Page.this);
PreferenceUtils.saveUserid(user_id, Register_Page.this);
PreferenceUtils.saveLocalValue(localValue, Register_Page.this);
sharedPreferences.writeLginStastu(true);
if(PreferenceUtils.getEmail(Register_Page.this)!=null || !PreferenceUtils.getEmail(Register_Page.this).equals("")){
startActivity(new Intent(Register_Page.this, CongoCoin.class));
sharedPreferences.writeLginStastu(true);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("User_json",""+e.toString());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
i'm trying to parse this json
{
"data": [
{ "name": "4th Floor",
"is_broken": true,
"is_repaired": false,
"is_ok": false,
"asset_parent": {
"name": "Buni Building",
"is_broken": true,
"is_repaired": false,
"is_ok": false
}
}
]
}
with this code
class daftarAset extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Sedang menampilkan...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
String link_url = "https://example.com/api/assets";
HttpHandler sh = new HttpHandler();
String json = sh.makeServiceCall(link_url);
Log.e(TAG, "Response from url: " + json);
if (json != null) {
try {
JSONObject jsonObject = new JSONObject();
JSONArray data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject ar = data.getJSONObject(i);
String aset = ar.getString("name");
JSONObject parent = ar.getJSONObject("asset_parent");
String nama = parent.getString("name");
HashMap map = new HashMap();
map.put(in_aset, aset);
map.put(in_ruang, nama);
data_map.add(map);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
list = (ListView) getView().findViewById(R.id.baik_list);
adapter = new AssetsAdapter(getActivity(), data_map);
list.setAdapter(adapter);
setListViewHeightBasedOnChildren(list);
}
});
}
return null;
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
}
and it says error that no value for data. i dont know why the data said no value where i already call it before with JSONArray. it must be nothing to do with the listview where i have to put the value.
please help why it says has no value for data but it actualy has
You're getting error because you aren't passing the json string to your json object.
it should be
JSONObject jsonObject = new JSONObject(json);
instead of
JSONObject jsonObject = new JSONObject(); //json is missing here
My app supposedly to send a source and a destination as parameters to get the fastest bus route and then send them back as an array.
I want to make a list from a json array using volley. Here is an example of my array output.
{
"arrayrute":[
"Halte LIK",
"Halte Kampoeng Semarang",
"Halte Kaligawe 2",
"Halte Pasar Kobong",
"Halte Kota Lama"
]
}
How am I supposedly to make a list from it? Usually a json array from a database would have it's row name before the variable so I just have to use list.set_id(jsonobject.getString("id")) or list.set_id(jsonobject.optString("id"))
Here's my java code to get the array
private void getData() {
//Creating a string request
asal = spin_dari.getSelectedItem().toString().trim();
tujuan = spin_ke.getSelectedItem().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.GET, DIRECTION_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
results = j.getJSONArray("arrayrute");
//Calling method getStudents to get the students from the JSON Array
getdireksi(results);
//dirlist.add(results .toString());
} catch (JSONException e) {
e.printStackTrace();
}
adaptdir.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_ASAL,asal);
params.put(KEY_TUJUAN,tujuan);
return params;
}
};
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getdireksi(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
dirlist.add(json.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Please Try with this way. Below is DEMO
String url = "{ \n" +
" \"arrayrute\":[ \n" +
" \"Halte LIK\",\n" +
" \"Halte Kampoeng Semarang\",\n" +
" \"Halte Kaligawe 2\",\n" +
" \"Halte Pasar Kobong\",\n" +
" \"Halte Kota Lama\"\n" +
" ]\n" +
"}";
try {
JSONObject jobject= new JSONObject(url);
JSONArray jarray=jobject.getJSONArray("arrayrute");
for(int k=0;k<jarray.length();k++)
{
String getValue=(jarray.getString(k));
System.out.println("Intellij_Amiyo"+getValue);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
Final
private void getdireksi(JSONArray j)
{
//Traversing through all the items in the json array
for(int k=0;k<j.length();k++)
try {
String getValue=(j.getString(k));
System.out.println("Intellij_Amiyo"+getValue);
dirlist.add(json);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Your getdireksi() method is wrong. Put following code instead of yours.
private void getdireksi(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
String json = j.getString(i);
//Adding the name of the student to array list
dirlist.add(json);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I'm posting "id" value (which i pass to this activity via getintent)
Uid = getIntent().getStringExtra("id");
to server and retrieving the corresponding jsonobjects.
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
When my jsonarray is empty, my app crashes. I want to toast"Error" when jsonarray is empty. How can I fix this?
Here is my code:
public class kill extends FragmentActivity {
GridView grid1;
CustomGrid_Album adapter;
private ProgressDialog pDialog;
String Uid,Disp;
public String category;
public String selected;
public static String imagename;
Button Alb_sel;
ArrayList<Item_album> gridArray = new ArrayList<Item_album>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.album_display);
grid1 = (GridView) findViewById(R.id.gridView2);
Uid = getIntent().getStringExtra("id");
Disp = getIntent().getStringExtra("disp");
Alb_sel=(Button)findViewById(R.id.album_to_select);
pDialog = new ProgressDialog(kill.this);
pDialog.setMessage("Loading...");
pDialog.show();
//fetching JSONArray
final RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
queue.add(stringRequest);
}
}
apply the check in onResponse
if(response.length()==0){
// error message
}else{
// your rest of the code
}
This looks problematic.
Datas.imageIds = new String[response.length()];
You don't want an array with the size of the string. You want an array of the size of the JSONArray within the response.
public void onResponse(String response) {
JSONArray arr = null;
try {
arr = new JSONArray(response);
Datas.imageIds = new String[arr.length()];
} catch (JSONException e1) {
e1.printStackTrace();
}
However, your code is going to continue on if an exception is thrown there, then you'll end up with a NullPointerException, so you should move the for-loop into the try-catch as well.
Realistically, though, you should just use a JSONArrayRequest if you're going to be expecting a JSONArray.
i want to toast"Error" when jsonarray is empty
Simple enough.
arr = new JSONArray(response);
if (arr.length() == 0) {
// TODO: Toast
}
I would simply add two checks to your onResponse method:
...
public void onResponse(String response) {
// Check if the response itself is an empty string or null
if(TextUtils.isEmpty(response)) {
// Show your user feedback
return;
}
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
// Check if your JSON has no elements in it
if(arr.length == 0) {
// Show your user feedback
return;
}
} catch (JSONException e1) {
e1.printStackTrace();
}
...
You have declared JSONArray arr = null;
After that you assign the server's JSON to that JSONArray.
Add a line after getting that
if(arr==null)
{
//toast
}
else
{
//whatever you want to do with JSON
}
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.length()==0){
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
else{
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
if(arr.length()>0){
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
}else{
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
}
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
Use the below code to check whether response is null or not and in object check whether it is having key or data with key is not null
if(response!=null){
try {
Datas.imageIds = new String[response.length()];
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
if(obj!=null){
if(obj.has("category_name") && !obj.isNull("category_name"){
category = obj.getString("category_name");
}
if(obj.has("album_id") && !obj.isNull("album_id"){
selected = obj.getString("album_id");
}
if(obj.has("org_image_name") && !obj.isNull("org_image_name"){
imagename = obj.getString("org_image_name");
}
if(obj.has("album_image") && !obj.isNull("album_image"){
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
} catch (JSONException e1) {
e1.printStackTrace();
}
}
You are using StringRequest, instead of that use JsonArrayRequest to make request as below, so you will get response in onResponse methode when there is a valid JSONArray in response, and if there is no data then you will get response in onError method
JsonArrayRequest rReq = new JsonArrayRequest(Request.Method.GET,"url", new JSONObject(), new Response.Listener() {
#Override
public void onResponse(JSONArray response) {
Log.e(TAG, "onResponse: "+response.toString() );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: "+error.getMessage() );
}
})