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();
}
Related
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 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"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 need to receive the "extract" part of the following Json:
https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=turkey
With my current code i receive the whole Json and dont really know how to go on:
public class MainActivity extends AppCompatActivity {
private Button btnSendRequest;
private TextView tvText;
private RequestQueue mRequestQueue;
private StringRequest stringRequest;
private JsonObjectRequest jsonObjectRequest;
private String url = "https://de.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=ilmenau";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSendRequest = (Button) findViewById(R.id.btnSendRequest);
tvText = (TextView) findViewById(R.id.tvText);
btnSendRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//send request and print the response using volley library
sendRequestAndPrintResponse();
}
});
}
private void sendRequestAndPrintResponse() {
mRequestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
tvText.setText("Response : " + response.toString());
// Log.i(TAG,"Response : " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tvText.setText("Error : " + error.toString());
//Log.i(TAG,"Error : " + error.toString());
}
});
mRequestQueue.add(jsonObjectRequest);
}
}
So currently I am getting the whole Json back, but I only need to get the "extract" part of the Json.
Can anyone help me?
Try this
try {
JSONObject jsonObject = new JSONObject(response.toString());
Iterator < String > keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = jsonObject.getString(key);
Log.v("key", key);
Log.v("value", value);
if (key.equals("query")) {
JSONObject jsonObject1 = new JSONObject(jsonObject.getString(key));
Iterator < String > keysinner = jsonObject1.keys();
while (keysinner.hasNext()) {
String key1 = keysinner.next();
String value1 = jsonObject1.getString(key1);
Log.e("key1", key1);
Log.e("value1", value1);
if (key1.equals("pages")) {
JSONObject jsonObject2 = new JSONObject(jsonObject1.getString(key1));
Iterator < String > keyPagenumber = jsonObject2.keys();
while (keyPagenumber.hasNext()) {
String keyPageNumber = keyPagenumber.next();
String valuePagenumber = jsonObject2.getString(keyPageNumber);
Log.e("Pages key :", keyPageNumber);
Log.e("Pages value :", valuePagenumber);
if (key1.equals("pages")) {
JSONObject jsonObjectPages = new JSONObject(jsonObject2.getString(keyPageNumber));
Iterator < String > keyPages = jsonObjectPages.keys();
while (keyPages.hasNext()) {
String keyPageDetail = keyPages.next();
String valuePageDetail = jsonObjectPages.getString(keyPageDetail);
Log.e("PagesDetail key :", keyPageDetail);
Log.e("PagesDetail value :", valuePageDetail);
}
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
OUTPUT
Use GSON library!
So let's say that you deduce the whole json content of your jsonObjectRequest as a string that i will name theWholeContentOfYourJsonObjectRequestAsAString
JsonParser parser = new JsonParser();
JsonElement jsonTree = parser.parse(theWholeContentOfYourJsonObjectRequestAsAString);
JsonObject jsonObject = jsonTree.getAsJsonObject();
JsonElement f1 = jsonObject.get("extract");
Something like
JSONObject pages = response.getJSONObject("query").getJSONObject("pages");
JSONObject firstPage = pages.getJSONObject(pages.names().get(0));
String extract = firstPage.getString("extract");
should work.
To extract a piece of JSON Object (another JSON Object, Integer, String etc.) you don't have to use any external libraries like GSON.
You can manage it with the following code.
JSONObject jObj = new JSONObject(response);
String InterestString = jObj.getJSONObject("local").getString("interests");
private void sendRequestAndPrintResponse() {
mRequestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject query = response.getJSONObject("query");
JSONObject pages = query.getJSONObject("pages");
JSONObject nos = pages.getJSONObject("11125639");
String extract = nos.getString("extract");
Log.e(TAG, "onResponse: " + extract);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tvText.setText("Error : " + error.toString());
//Log.i(TAG,"Error : " + error.toString());
}
});
mRequestQueue.add(jsonObjectRequest);
}
modify your code add these lines like this you should get extract
I am working on a project and below my code basically takes an array of objects and sets the Id to each object, However, when I click on my objects I would like to get that Id. I tried a local variable and I could only get the Id of the last object, how do I do this? I would like to get the value of String Answerid = currentQuestions.getString("id"); into my OnDown clicklistener.
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_ANSWER, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listblogs = parseJSONResponseQuestion(response);
mAdapterQuestion.setBloglist(listblogs);
System.out.println(response);
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
});
mRequestQueue.add(request);
}
String globalVar = " ";
private ArrayList<Blogs> parseJSONResponseQuestion(JSONArray response) {
if (!response.equals("")) {
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String questionId = currentQuestions.getString("questionId");
String votes = currentQuestions.getString("votes");
String Answerid = currentQuestions.getString("id");
System.out.println(response.length() + "length");
data.append(text + Answerid + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setMtext(text);
blogs.setVotes(votes);
blogs.setId(Answerid);
System.out.print(Answerid);
listblogs.add(blogs);
}
System.out.println(data.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
public void OnDown(View view) {
System.out.println("VOTED Down");
final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
final String PUT_VOTE_UP = "someURL";
StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_UP, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response + "reponse");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println("************Answer" + error + "error");
}
});
mrequestQueue.add(PostVoteUp);
System.out.println("VOTED DOWN");
}
}
Your click listener OnDown(View view) gets a view that was clicked. That's the only way you can identify what was clicked.
You should use View.getTag() to get the id:
Object obj = view.getTag();
The question is where can you add this code to set it:
View view = ...; // new View()?
view.setTag(object);