#Override
public void onResponse(String response, int id) {
try {
JSONObject pollresult = new JSONObject(response);
List<OrderInfo> info = new Gson().fromJson(pollresult.getString("data"), new TypeToken<ArrayList<OrderInfo>>() {
}.getType());
orderId = info.get(0).getOrderID();
} catch (JSONException e) {
e.printStackTrace();
}
}
info.get(0) returns null and i get NullPointerException
Related
I am struggling with something that really p*sses me off for several hours.
My android app manages to connect to a websoket, and receives json data which for now has worked perfectly, and here is the code for this:
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingPositionFromSensor = new JSONObject( (String) args[0]);
double the_position = incomingPositionFromSensor.getDouble("position");
CalculateValue(the_position);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
This code above as I said works perfectly, and i get the data in everytime. HOWEVER, HOWEVER, HOWEVER: If i try to receive 2 json-objects at the sametime through this emittener, it does not work!!!!
Here is example when i try to receive multiple JSON objects, and NONE of them works!
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingTargetFromSensor = new JSONObject( (String) args[0]);
int targetNum = incomingTargetFromSensor.getInt("target_number_count");
showTargetRep(targetNum); //NOT WORKING!
JSONObject incomingPositionFromSensor = new JSONObject( (String) args[0]);
double the_position = incomingPositionFromSensor.getDouble("position");
CalculateValue(the_position); //NOT WORKING!
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
In the first example I could receive the position data, and the code is exactly similar as the example above, but for some reasons it can not recevice data when i try to receive another JSON object.
Another example of why I always disliked JSON object.
Any help plz?
The solution at the end was to add multiple try/catches like this:
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingTargetRepFromSensor = new JSONObject((String ) args[0]);
int target_rep = incomingTargetRepFromSensor.getInt("target_repetition_count");
showTargetRep(target_rep);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingDataFromSensor = new JSONObject((String ) args[0]);
double the_position = incomingDataFromSensor.getDouble("position");
CalculateValue(the_position);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingTargetSetFromSensor = new JSONObject((String ) args[0]);
int target_set = incomingTargetSetFromSensor.getInt("target_set_count");
showTargetSet(target_set);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingRepsFromSensor = new JSONObject((String ) args[0]);
int the_repetitions = incomingRepsFromSensor.getInt("repetitions");
showCurrentReps(the_repetitions);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingSetsFromSensor = new JSONObject((String ) args[0]);
int the_sets = incomingSetsFromSensor.getInt("sets");
showCurrentSets(the_sets);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
I am getting a org.json.JSON.typeMismatch(JSON.java:111) error while trying to create a JSON array. The received data looks like this:
{
"result":[
{
"#type":"d",
"#rid":"#-2:0",
"#version":0,
"a_adres":"kepez merkez geliyor herkez",
"takipkodu":"464664",
"agirlik":50
},
{
"#type":"d",
"#rid":"#-2:1",
"#version":0,
"a_adres":"merkez mahallesi 4 sok",
"takipkodu":"sd4fs654f64",
"agirlik":60
}
]
}
Code:
protected String doInBackground(String... urls) {
try {
String getResponse = get("http://178.18.206.128:2480/command/nakliye/sql/select a_adres,takipkodu,agirlik from yukilan");
return getResponse;
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(String getResponse) {
ListView liste=(ListView)findViewById(R.id.list_view);
try {
JSONArray yukilanarray = new JSONArray(getResponse);
List<Yukilan> yukilanlar = new ArrayList<>();
//Populate the EmployeeDetails list from response
for (int i = 0; i<yukilanarray.length();i++){
Yukilan yeniilan = new Yukilan();
JSONObject yukilanobject = yukilanarray.getJSONObject(i);
yeniilan.setAdres(yukilanobject.getString(KEY_ADRES));
yeniilan.setAgirlik(yukilanobject.getString(KEY_AGIRLIK));
yeniilan.setTakip_kod(yukilanobject.getString(KEY_TAKIPKODU));
yukilanlar.add(yeniilan);
}
//Create an adapter with the EmployeeDetails List and set it to the LstView
yukilanadapter = new Yukilanadapter(yukilanlar,getApplicationContext());
liste.setAdapter(yukilanadapter);
} catch (JSONException e) {
e.printStackTrace();
}
// System.out.println(getResponse);
}
Please help.
I think you made a mistake in reading the json. the first element would be a JSONObject not a JSONArray.Below is the revised code.
protected String doInBackground(String... urls) {
try {
String getResponse = get("http://178.18.206.128:2480/command/nakliye/sql/select a_adres,takipkodu,agirlik from yukilan");
return getResponse;
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(String getResponse) {
ListView liste=(ListView)findViewById(R.id.list_view);
try {
JSONObject jsonObject = new JSONObject(getResponse);
JSONArray yukilanarray = jsonObject.getJSONArray("result");
List<Yukilan> yukilanlar = new ArrayList<>();
//Populate the EmployeeDetails list from response
for (int i = 0; i<yukilanarray.length();i++){
Yukilan yeniilan = new Yukilan();
JSONObject yukilanobject = yukilanarray.getJSONObject(i);
yeniilan.setAdres(yukilanobject.getString(KEY_ADRES));
yeniilan.setAgirlik(yukilanobject.getString(KEY_AGIRLIK));
yeniilan.setTakip_kod(yukilanobject.getString(KEY_TAKIPKODU));
yukilanlar.add(yeniilan);
}
//Create an adapter with the EmployeeDetails List and set it to the LstView
yukilanadapter = new Yukilanadapter(yukilanlar,getApplicationContext());
liste.setAdapter(yukilanadapter);
} catch (JSONException e) {
e.printStackTrace();
}
// System.out.println(getResponse);
}
I have json data from webservice that should be stored in two lists, String list and Integer List. the one for strings stores the data fine but the one for the integers doesn't. it prompts error saying java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
here is the complete code
public class Setup extends AppCompatActivity {
Button save;
EditText schoolPK;
String schoolname, classname, cityname, school_id,class_id;
ImageView logout;
GridView grid;
String cityid,classid;
int schoolid;
ArrayList<String> CityName, CityId;
private List<Integer> classID=new ArrayList<Integer>();
private List<String> listschools = new ArrayList<String>();
private List<String> listclasses = new ArrayList<String>();
Spinner schoolspinner;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String classnames = "classname";
public static final String schoolnames = "schoolname";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;
String saved_letter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setup2);
CityName=new ArrayList<>();
CityId = new ArrayList<>();
//classID = new ArrayList<>();
// schoolID = new ArrayList<>();
schoolPK = (EditText) findViewById(R.id.schoolPK);
final Spinner city = (Spinner) findViewById(R.id.city);
final Spinner classspinner = (Spinner) findViewById(R.id.classname);
String URL_countries="http://192.168.0.148/Election/api/school";
JsonArrayRequest items = new JsonArrayRequest(URL_countries, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0;i<response.length();i++){
try {
JSONObject obj = response.getJSONObject(i);
String country=obj.getString("name_Ar");
String cityid = obj.getString("pK_ID");
CityId.add(cityid);
CityName.add(country);
}
catch (JSONException e) {
e.printStackTrace();
}
city.setAdapter(new ArrayAdapter<String>(Setup.this, android.R.layout.select_dialog_item, CityName));
}
//to get me the
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder add = new AlertDialog.Builder(Setup.this);
add.setMessage(error.getMessage()).setCancelable(true);
AlertDialog alert = add.create();
alert.setTitle("error");
alert.show();
}
} );
Controller.getInstance(Setup.this).addToRequestque(items);
city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
cityname = parent.getItemAtPosition(position).toString();
cityid = CityId.get(position).toString();
//CityId.clear();
listclasses.clear();
getclasses();
} // to close the onItemSelected
public void onNothingSelected(AdapterView<?> parent) {
}
});
classspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
classname = parent.getItemAtPosition(position).toString();
class_id = classID.get(position).toString();
}
// to close the onItemSelected
public void onNothingSelected(AdapterView<?> parent) {
}
});
save = (Button) findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedpreferences = getSharedPreferences("Settings", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
Intent intent = new Intent(getApplicationContext(), Vote.class);
editor.putString("schoolname", cityname);
editor.putString("schoolid", cityid);
editor.putString("classname", classname);
editor.putString("classid", class_id);
editor.apply();
}
});
}
public void getschools(){
try {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String URL = "http://192.168.0.148/Election/api/School";
JSONObject jsonBody = new JSONObject();
// jsonBody.put("tblRegisteredUsers_nickName", username.getText().toString().trim());
jsonBody.put("cityFK_ID", cityid);
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//my response later should be changed
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
})
{
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString;
String json = null;
try {
json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
responseString = String.valueOf(json).trim();
ArrayList<Schoolresponse> list_response = new ArrayList<Schoolresponse>();
Type listType = new TypeToken<List<Schoolresponse>>() {}.getType();
list_response = new Gson().fromJson(responseString, listType);
// schoolID= new ArrayList<>();
for (int i = 0; i < list_response.size(); i++) {
School listItemData = new School();
listItemData.setName(list_response.get(i).getNameAr());
listItemData.setId(list_response.get(i).getPKID());
//schoolID.add(listItemData.getId());
listschools.add(listItemData.getName());
}
// i should have this piece of code for methods that are running in the background
runOnUiThread(new Runnable() {
#Override
public void run() {
schoolspinner.setAdapter(new ArrayAdapter<String>(Setup.this, android.R.layout.select_dialog_item, listschools));
}
});
return Response.success(list_response.toString(), HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
public void getclasses(){
final Spinner classspinner = (Spinner) findViewById(R.id.classname);
try {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String URL = "http://192.168.0.148/Election/api/classes";
JSONObject jsonBody = new JSONObject();
// jsonBody.put("tblRegisteredUsers_nickName", username.getText().toString().trim());
jsonBody.put("SchoolFK_ID", cityid);
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//my response later should be changed
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
})
{
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString;
String json = null;
try {
json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
responseString = String.valueOf(json).trim();
ArrayList<ClassResponse> list_response = new ArrayList<ClassResponse>();
Type listType = new TypeToken<List<ClassResponse>>() {}.getType();
list_response = new Gson().fromJson(responseString, listType);
for (int i = 0; i < list_response.size(); i++) {
School listItemData = new School();
listItemData.setName(list_response.get(i).getNameAr());
listItemData.setId(list_response.get(i).getPKID());
classID.add(listItemData.getId());
listclasses.add(listItemData.getName());
}
// i should have this piece of code for methods that are running in the background
runOnUiThread(new Runnable() {
#Override
public void run() {
classspinner.setAdapter(new ArrayAdapter<String>(Setup.this, android.R.layout.select_dialog_item, listclasses));
}
});
// String Check = yourModel.getMessagetitle();
return Response.success(list_response.toString(), HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
and here is the area I'm talking about
where only the string list (listclasses) is storing data while the integer (classID) list does not
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString;
String json = null;
try {
json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
responseString = String.valueOf(json).trim();
ArrayList<ClassResponse> list_response = new ArrayList<ClassResponse>();
Type listType = new TypeToken<List<ClassResponse>>() {}.getType();
list_response = new Gson().fromJson(responseString, listType);
for (int i = 0; i < list_response.size(); i++) {
School listItemData = new School();
listItemData.setName(list_response.get(i).getNameAr());
listItemData.setId(list_response.get(i).getPKID());
classID.add(listItemData.getId());
listclasses.add(listItemData.getName());
}
// i should have this piece of code for methods that are running in the background
runOnUiThread(new Runnable() {
#Override
public void run() {
classspinner.setAdapter(new ArrayAdapter<String>(Setup.this, android.R.layout.select_dialog_item, listclasses));
}
});
// String Check = yourModel.getMessagetitle();
return Response.success(list_response.toString(), HttpHeaderParser.parseCacheHeaders(response));
}
};
hope I get right answer
thanks in advance
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
means that your Array is empty and you are trying to access array element from an empty array.
You can put a condition to check if array length is more than 0 and then proceed using it like:
if(array != null && array.length > 0){
// do parsing
}
Make sure your class School contains variable with name pK_ID. Look carefully on the upper/lower cases in the variable name.
If the variable name is not matching with JSON tag then this will result in empty fetching from JSON, even if you are getting valid JSON from URL as per your comment.
I'm using retrofit to POST a json array to server. Data is something like this:
{something:
{somethings:
[
{"param1":"value", "param2":value},
{"param1":"value", "param2":value}
]
}
}
however, my server forces me to MUST include the indices in the array like:
{something:
{somethings:
{
"0":{"param1":"value", "param2":value},
"1":{"param1":"value", "param2":value}
}
}
}
In other words cannot send parameters like this:
something[somethings][][param1]
something[somethings][][param2]
I must include indices:
something[somethings][0][param1]
something[somethings][0][param2]
How to do this using retrofit?
My interface looks like this:
interface ApiService {
#POST("endpoint")
public Callback<Something> postSomething (#Body Something something);
}
My classes look like following:
public class PostSomething {
private MapOfSomething something = new MapOfSomething();
public MapOfSomething getSomething() {
return portfolio;
}
public void setSomething(MapOfSomething something) {
this.something = something;
}
}
public class MapOfSomething {
private JSONObject somethings = new JSONObject();
public JSONObject getPortfolios() {
return somethings;
}
public void setSomethings(List<Something> somethingList) {
for (int i = 0; i<somethingList.size(); i++) {
try {
somethings.put(String.valueOf(i).toString(), somethingList.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
and calling the method like:
PostSomethings something = new PostSomethings();
MapOfSomething map = new mapOfSomething();
map.setSomethings(listofSomething);
something.setSomethings(map);
apiService.postSomething(something);
One way to solve your problem is to put json directly into body , so your interface will look like this
interface ApiService {
#POST("endpoint")
public Callback<Something> postSomething (#Body JSONObject jsonObject);
}
Now you need to create the JSONObject , here is how I have created your desired JSONObject
JSONObject mainJson = new JSONObject();
JSONArray list = new JSONArray();
JSONObject singleElement1 = new JSONObject();
try {
singleElement1.put("param1","value1");
singleElement1.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElementSet1 = new JSONObject();
try {
singleElementSet1.put("1",singleElement1);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElement2 = new JSONObject();
try {
singleElement2.put("param1","value1");
singleElement2.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElementSet2 = new JSONObject();
try {
singleElementSet2.put("2",singleElement2);
} catch (JSONException e) {
e.printStackTrace();
}
list.put(singleElementSet1);
list.put(singleElementSet2);
JSONObject subJson = new JSONObject();
try {
subJson.put("something",list);
mainJson.put("something",subJson);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("json",""+mainJson.toString());
I am assuming right now you are calling your service like this way
Call<Something> call = instanceOfYourAPIService.postSomething(anInstanceOfSomethingObject);
But now you have to replace this with the following
Call<Something> call = instanceOfYourAPIService.postSomething(mainJson); //mainJson is the JSONObject which is created earlier
Hope it helps
EDIT
JSONObject mainJson = new JSONObject();
JSONObject singleElement1 = new JSONObject();
try {
singleElement1.put("param1","value1");
singleElement1.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElement2 = new JSONObject();
try {
singleElement2.put("param1","value1");
singleElement2.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
ArrayList<JSONObject> jsonObjectArrayList = new ArrayList<JSONObject>();
//hope you can add item to this arraylist via some loop
jsonObjectArrayList.add(singleElement1);
jsonObjectArrayList.add(singleElement2);
JSONArray list = new JSONArray();
for(int i = 0;i<jsonObjectArrayList.size();i++){
JSONObject elementSet = new JSONObject();
try {
elementSet.put(String.valueOf(i).toString(),jsonObjectArrayList.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
list.put(elementSet);
}
JSONObject subJson = new JSONObject();
try {
subJson.put("something",list);
mainJson.put("something",subJson);
} 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() );
}
})