Get JSONObject out of URL and get Integer out of the JSON - java

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];
}

Related

Volley does not return any value, if I use the url in the browser it does return values, android studio

I am using volley to extract the categories and posts from a wordpress site to display them in an android application, first the categories respond well to me, while I am adding the categories to a list, I am trying to extract the posts for another list, but it returns [], I use the url in the browser and it returns the values ok, help me, what am I doing wrong?
public void extractCategories() { String URL = getResources().getString(R.string.categories_url);
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAGC, "onResponse: " + response.toString());
for (int i = 0; i < response.length(); i++) {
try {
Category c = new Category();
JSONObject jsonObjectData = response.getJSONObject(i);
// extract the id
c.setId(jsonObjectData.getInt("id"));
// extract the name
c.setName(jsonObjectData.getString("name"));
//extract the parent
c.setParent(jsonObjectData.getInt("parent"));
//extract the parent
c.setCount(jsonObjectData.getInt("count"));
cat_list.add(c);
extractPosts(i); //here I call the function to extract the posts
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
MySingletonVolley.getInstance(getBaseContext()).addToRequestQueue(request);
}
public void extractPosts(int i) {
int cont = 0;
String URL = getResources().getString(R.string.posts_url);
int cant_post_real = this.cat_list.get(i).getCount();
int page = 0;
while ( cant_post_real > 0) {
page++;
String complete_url = URL + page + "&categories=" + this.cat_list.get(i).getId();
JsonArrayRequest request1 = new JsonArrayRequest(Request.Method.GET, complete_url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse: " + response.toString());
for (int k = 0; k < response.length(); k++) {
try {
Post p = new Post();
JSONObject jsonObjectData = response.getJSONObject(k);
// extract the title
JSONObject titleObject = jsonObjectData.getJSONObject("title");
p.setTitle(titleObject.getString("rendered"));
// extract the content
JSONObject contentObject = jsonObjectData.getJSONObject("content");
p.setContent(contentObject.getString("rendered"));
//extract the excerpt
JSONObject excerptObject = jsonObjectData.getJSONObject("excerpt");
p.setExcerpt(excerptObject.getString("rendered"));
// extract feature image
JSONObject embeddedObject = jsonObjectData.getJSONObject("_embedded");
JSONArray wpfeaturemediaArray = embeddedObject.getJSONArray("wp:featuredmedia");
JSONObject firstElement = wpfeaturemediaArray.getJSONObject(0);
p.setFeature_image(firstElement.getString("source_url"));
posts.add(p);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
cant_post_real = cant_post_real - 10;
MySingletonVolley.getInstance(getBaseContext()).addToRequestQueue(request1);
}
}

I have to show a list of Objects from a JSON array. But i cant seem to print it out

// I've declared everything here, everything looks fine from here. I don't think i have problems here
public class MainActivity extends AppCompatActivity {
private TextView mTextViewResult;
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextViewResult = findViewById(R.id.text_view_result);
Button buttonParse = findViewById(R.id.button_parse);
mQueue = Volley.newRequestQueue(this);
buttonParse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse(){
String url = "https://fetch-hiring.s3.amazonaws.com/hiring.json";
// I don't know what my problem is here, i've declared everything and nothing is showing up, I was thinking i should've declared an array instead of an Object, but im still having difficulties
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject list = jsonArray.getJSONObject(i);
int id = list.getInt("id");
int listId = list.getInt("listId");
String name = list.getString("name");
mTextViewResult.append(String.valueOf(id) + ", " + String.valueOf(listId) + ", " + name + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}
Since the response is a Json Array, you need to use JsonArrayRequest instead of JsonObjectRequest, and receive a JSONArray in onResponse.
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<org.json.JSONArray>() {
#Override
public void onResponse(org.json.JSONArray response) {
try {
for (int i = 0; i < response.length(); i++){
..... etc.
See https://javadoc.io/static/com.android.volley/volley/1.1.1/com/android/volley/toolbox/JsonArrayRequest.html
Try with following code.
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++){
JSONObject list = jsonArray.getJSONObject(i);
int id = list.getInt("id");
int listId = list.getInt("listId");
String name = list.getString("name");
mTextViewResult.append(String.valueOf(id) + ", " + String.valueOf(listId) + ", " + name + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}

Extracting an integer with Volley

Json image link I'm trying to extract an integer from a Json Object using Volley and I can't seem to return the value. I tried to extract it as a String (worked for double values) but it's not working for my int value. The Json response and my code is below. it's the "id" I'm trying to retrieve and use as part of building a URL for another network call.
[json image link][1]
// parse Json using volley to make network call
private String parseMovieJSON(final String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("results");
mMoviesList.clear();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject movie = jsonArray.getJSONObject(i);
//Get json data as strings
int id = movie.optInt("id");
String posterPath = movie.optString("poster_path");
String originalTitle = movie.optString("title");
String overview = movie.getString("overview");
String releaseDate = movie.optString("release_date");
String voteAverage = movie.optString("vote_average");
mMoviesList.add(new Movies(id, posterPath, originalTitle, overview, releaseDate, voteAverage));
}
myMoviesAdapter = new MyMoviesAdapter(MainActivity.this, mMoviesList);
myMoviesAdapter.setOnItemClickListener(MainActivity.this);
mRecyclerView.setAdapter(myMoviesAdapter);
myMoviesAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof NetworkError) {
if (checkConnection()) {
parseMovieJSON(url);
} else if (!checkConnection()) {
Toast.makeText(MainActivity.this, "Check Network Connection", Toast.LENGTH_LONG).show();
mMoviesList = null;
}
}
}
});
mRequestQueue.add(request);
checkConnection();
return url;
}
// network call for Trailers
private void extractTrailer(String s) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, uriBuilder(), null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject results = jsonArray.getJSONObject(i);
//Get json data as strings
int idNumber = results.optInt(KEY_ID);
String movieKey = results.optString(KEY_URL);
String movieName = results.optString(KEY_NAME);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
mRequestQueue.add(request);
}
private String uriBuilder() {
// http://api.themoviedb.org/3/movie/157336/videos?api_key=### (template example)
Uri.Builder builder = Uri.parse(Constants.BASE_URL).buildUpon();
builder.appendPath("movie").
appendPath(String.valueOf(Constants.MOVIE_ID)).
appendPath("videos").
appendQueryParameter("api_key", BuildConfig.ApiKey);
return builder.build().toString();
}

Handle null exception in RecyclerView from PHP URL

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.

Json data array request keeps skipping onResponse

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);
}

Categories

Resources