I'm trying to handle this null exception in RecyclerView from PHP URL. I want it to show a Toast message if a null exception occurs: No Result Found.
null exception:
Code
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray(uarray);
for (int i = 0; i < array.length(); i++) {
JSONObject p = array.getJSONObject(i);
Category_Movie item = new Category_Movie(
p.getInt("id"),
p.getString("mTitle"),
p.getString("mDesc"),
p.getInt("mYear"),
);
listItems.add(item);
}
mAdapter = new CategoryListAll_Adapter(listItems, getActivity());
recyclerView.setAdapter(mAdapter);
} catch(JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
EDIT
Create one method to validate your JSONObject
public boolean isJSONValid(String jsonStr) {
try {
new JSONObject(jsonStr);
} catch (JSONException ex) {
return false;
}
return true;
}
Try to edit following code:
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (isJSONValid(response)) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray(uarray);
for (int i = 0; i < array.length(); i++) {
JSONObject p = array.getJSONObject(i);
Category_Movie item = new Category_Movie(
p.getInt("id"),
p.getString("mTitle"),
p.getString("mDesc"),
p.getInt("mYear"),
);
listItems.add(item);
}
mAdapter = new CategoryListAll_Adapter(listItems, getActivity());
recyclerView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
// your Toast Message
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
Returning early ordinary is way to go ...
therefore I'd compare to the known String value of null, in case of no results,
before checking if it possibly could be valid JSON (which can already be out-ruled):
if(! response.equals("null")) {
try ...
}
or improve statement e.printStackTrace() and handle that JSONException accordingly:
try {
...
} catch(JSONException e) {
if(response.equals("null")) {
/* assume no results */
} else {
e.printStackTrace();
}
}
While having access to the PHP code ...better always return a parse-able JSON response:
header("Content-Type: application/json");
die(json_encode((object) array(
"success" => false,
"error" => "no results"
)));
... when the client expects application/json instead of text/plain.
Related
I have this URL with a JSON in it I would like to make a JSONObject of it and store the value in a variable named previousID.
[ { "id": "179" } ]
How can I create that JSONObject and get that int value out of it?
I can't make it work with the JSONObject so I tried it with a JSONArray but for some reason I always get the value 0 as return value.
private int getPreviousID(Context context){
RequestQueue queue = Volley.newRequestQueue(context);
final int[] info = new int[1];
JsonArrayRequest totalListRequest = new JsonArrayRequest(Request.Method.GET, GET_LAST_URL,null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0; i<response.length(); ++i) {
JSONObject o = null;
info[0] = 0;
try {
info[0] += response.getJSONObject(i).getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Unable to communicate with the server", Toast.LENGTH_LONG).show();
}
});
queue.add(totalListRequest);
return info[0];
}
I want to make my own library for getting the weather. I made the same in MainActivity and it works but when a put the same method in an another Class java i get error with Tosts and getApplicationContext methods. How can i fix it
public class WeatherClass {
public static void getCurrentWeather(String location) {
final String[] urlCityGetTemperature = {"https://www.metaweather.com/api/location/"};
String urlCityGetId = "https://www.metaweather.com/api/location/search/?query=";
final String[] finishUrl = new String[1];
String tempUrl = "";
String city = "";
city = location;
if(city.equals("")) {
//тут пишем код, если ползователь ничего не ввел в поле и нажал на кнопку
}
else {
tempUrl = urlCityGetId + city;
String finalCity = city;
StringRequest stringRequest = new StringRequest(Request.Method.GET, tempUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
String output = "";
try {
JSONArray jsonResponce = new JSONArray(response);
if(response.equals("[]")) {
//уведомление о неккоректном вводе названия города
}
JSONObject jsonObjectZeroIndex = jsonResponce.getJSONObject(0);
int woeid = jsonObjectZeroIndex.getInt("woeid");
//tvRes.setText(output);
finishUrl[0] = urlCityGetTemperature[0] + output;
//тут мы будем получат температуру по id города.
StringRequest stringRequestGetTeperatureWithId = new StringRequest(Request.Method.GET, finishUrl[0], new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("finalLink", response);
String outputTemp = "";
String outPutWeather;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("consolidated_weather");
JSONObject jsonObectFromArray = jsonArray.getJSONObject(0);
int woeid = jsonObectFromArray.getInt("the_temp");
outputTemp = String.valueOf(woeid);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext);
requestQueue.add(stringRequestGetTeperatureWithId);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext);
requestQueue.add(stringRequest);
}
}
}
getApplicationContext and Toasts doesn't work.
You can pass second parameter Context to getCurrentWeather, and then pass that context to The Toast.
Here is getCurrentWeather Method inside WeatherClass Like This,
public class WeatherClass {
public static void getCurrentWeather(String location,Context context){
// Here is your fetch whether code
// Your Toast like this
Toast.makeText(context,"Your Message", Toast.LENGTH_SHORT).show();
}
}
When you call this method from MainActivity, call Method like this,
getCurrentWeather(location,getApplicationContext())
I"m populating the listview from online using JSON. It works great...But I wanted to implement method of SwipeRefresh layout such that old data will be replace with new one in every Swipe user make.
Instead of clearing old data with new one, Everytime on SwipeRefresh new data is added at the bottom of old data.
I also set notifysetAdapter; but it doesn't seems to work.
Here is my code
mSwipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
mExampleList.clear();
mExampleAdapter.notifyDataSetChanged();
parseJSON();
}
}
);
}
}
private void parseJSON() {
String url = getIntent().getStringExtra(EXTRA_URL);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
myProgressBar.setVisibility(View.GONE);
try {
JSONArray jsonArray = response.getJSONArray("hits");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String videoTitle = hit.getString("title");
String link = hit.getString("link");
// String notes = hit.getString("notes");
// String question = hit.getString("question");
// String imageUrl = hit.getString("webformatURL");
// int likeCount = hit.getInt("likes");
mExampleList.add(new ExampleItem(videoTitle,link));
mExampleAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
mSwipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
mSwipeRefreshLayout.setRefreshing(false);
}
});
mRequestQueue.add(request);
}
I need help to solve this.
Use setOnRefreshListener
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
parseJSON();
// just on refresh call parseJSON method
}
});
Clear data in parseJSON method before add new data, and set notifyDataSetChanged out for loop.
private void parseJSON() {
String url = getIntent().getStringExtra(EXTRA_URL);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
myProgressBar.setVisibility(View.GONE);
try {
mExampleList.clear();
JSONArray jsonArray = response.getJSONArray("hits");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String videoTitle = hit.getString("title");
String link = hit.getString("link");
// String notes = hit.getString("notes");
// String question = hit.getString("question");
// String imageUrl = hit.getString("webformatURL");
// int likeCount = hit.getInt("likes");
mExampleList.add(new ExampleItem(videoTitle,link));
}
mExampleAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
mSwipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
mSwipeRefreshLayout.setRefreshing(false);
}
});
mRequestQueue.add(request);
}
I keep trying to look up and find a solution for my problem.
I am populating a Spinner with json data from a URL, the Json data is nameless and I'm trying to get the data into an ArrayList so I can populate the Spinner.
Whenever I debug I can see that it skips my onResponse() method after making either StringRequest or JSONArrayRequest, Please look at my code and see what am I doing wrong
yearsp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(ySelect)
{
selectedYear = yearsp.getSelectedItem().toString();
URL1 = URL + "/" + selectedYear;
loadSpinnerDataMake();
adapterMake.clear();
adapterMake.addAll(makesName);
}
else
ySelect = true;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
String URL1 = http://carmakemodeldb.com/vehicle/makes/2011 //this is here for you to see the link
public void loadSpinnerDataMake()
{
makesName = new ArrayList<String>();
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL1, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int x = 0; x < response.length(); x++) {
JSONObject obMake = response.getJSONObject(x);
String nMake = obMake.getString("make");
makesName.add(nMake);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(jsonArrayRequest);
}
here is my json data from URL1
[{"make":"Acura"},{"make":"Aston Martin"},{"make":"Audi"},{"make":"Bentley"},{"make":"BMW"},{"make":"Bugatti"},{"make":"Buick"},{"make":"Cadillac"},{"make":"Chevrolet"},{"make":"Chrysler"}]
Try below function and let me know.
private void parseJSONDataMAke() {
try {
JSONArray dataMakeArray = new JSONArray("[{\"make\":\"Acura\"},{\"make\":\"Aston Martin\"},{\"make\":\"Audi\"},{\"make\":\"Bentley\"},{\"make\":\"BMW\"},{\"make\":\"Bugatti\"},{\"make\":\"Buick\"},{\"make\":\"Cadillac\"},{\"make\":\"Chevrolet\"},{\"make\":\"Chrysler\"}]");
ArrayList<String> stringArrayList = new ArrayList<>();
for (int i = 0; i < dataMakeArray.length(); i++) {
JSONObject jsonObject = dataMakeArray.getJSONObject(i);
stringArrayList.add(jsonObject.getString("make"));
}
//Please set "stringArrayList" array into spinner
} catch (JSONException e) {
e.printStackTrace();
}
}
Your request is async hence you need to notify your spinner adapter when you get response like this.
String URL1 = http://carmakemodeldb.com/vehicle/makes/2011 //this is here for you to see the link
public void loadSpinnerDataMake()
{
makesName = new ArrayList<String>();
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL1, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
makesName.clear(); //To avoid duplication of data
for (int x = 0; x < response.length(); x++) {
JSONObject obMake = response.getJSONObject(x);
String nMake = obMake.getString("make");
makesName.add(nMake);
}
adapterMake.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(jsonArrayRequest);
}
You are not notifying adapter that's why you didn't get your result.
I fixed my issue thank you everyone who has helped but i figured it out by removing where im adding the arraylist to the adapter and placing it in the OnResponse
public void loadSpinnerDataMake()
{
makesName = new ArrayList<String>();
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(URL1, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONArray jsonArray = response;
for (int x = 0; x < jsonArray.length(); x++) {
JSONObject obMake = jsonArray.getJSONObject(x);
String nMake = obMake.getString("make");
makesName.add(nMake);
adapterMake.clear();
adapterMake.addAll(makesName);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(jsonObjectRequest);
}
My RecyclerView adapter is declared as
adapterlist = new AdapterList(getActivity(),getData());
and the getData() function is defined as
public List<Information> getData(){
final List<Information> data = new ArrayList<>();
showpDialog();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, urlfood, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
for (int i = 0; i < 10; i++) {
try {
JSONArray items = jsonObject.getJSONObject("response").getJSONArray("groups").getJSONObject(0).getJSONArray("items");
if (jsonObject.getJSONObject("response").getJSONArray("groups").getJSONObject(0).getJSONArray("items").getJSONObject(i).getJSONObject("venue").has("location")) {
if(jsonObject.getJSONObject("response").getJSONArray("groups").getJSONObject(0).getJSONArray("items").getJSONObject(i).getJSONObject("venue").getJSONObject("location").has("address")){
JSONObject location = jsonObject.getJSONObject("response").getJSONArray("groups").getJSONObject(0).getJSONArray("items").getJSONObject(i).getJSONObject("venue").getJSONObject("location");
Address[i] = location.getString("address");}}
Name[i] = items.getJSONObject(i).getJSONObject("venue").getString("name");
String rtg=items.getJSONObject(i).getJSONObject("venue").getString("rating");
Rating[i]=Float.parseFloat(rtg);
Information current = new Information();
current.name = Name[i];
current.address = Address[i];
current.ratings = Rating[i];
data.add(current);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
recyclerView.setAdapter(adapterlist);
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),
"error:"+error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
}
);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return data;
}
These things are defined in the class that extends fragment.
How can I cache the raw response or the parsed response? Please help.
I already checked many answers on StackOverflow but I am not able to understand how I can integrate them in my fragment class.