I want use JsonObjectRequest in onItemSelected spinner when set item spinner get json but JsonObjectRequest not work and not display nothing,how to can use JsonObjectRequest in onItemSelected?please help me
my code
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
JsonObjectRequest jsonObjectr = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("list");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
int id = jsonObject.getInt("id");
int id_category = jsonObject.getInt("id_category");
int id_speaker = jsonObject.getInt("id_speaker");
String name = jsonObject.getString("name");
String image = jsonObject.getString("image");
String category_name = jsonObject.getString("category_name");
String speaker_name = jsonObject.getString("speaker_name");
Item_zakerin_any itemzakeran = new Item_zakerin_any(id, id_category, name, id_speaker, image, speaker_name, category_name);
list_zakeran_any.add(itemzakeran);
az = new adapter_zakeran_any(mcontext, list_zakeran_any);
rv.setAdapter(az);
hidepDialog();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hidepDialog();
}
});
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectr);
}
You are setting your adapter in the loop. Move it out like:
try {
JSONArray jsonArray = response.getJSONArray("list");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
int id = jsonObject.getInt("id");
int id_category = jsonObject.getInt("id_category");
int id_speaker = jsonObject.getInt("id_speaker");
String name = jsonObject.getString("name");
String image = jsonObject.getString("image");
String category_name = jsonObject.getString("category_name");
String speaker_name = jsonObject.getString("speaker_name");
Item_zakerin_any itemzakeran = new Item_zakerin_any(id, id_category, name, id_speaker, image, speaker_name, category_name);
list_zakeran_any.add(itemzakeran);
}
az = new adapter_zakeran_any(mcontext, list_zakeran_any);
rv.setAdapter(az);
hidepDialog();
} catch (JSONException e) {
e.printStackTrace();
hidepDialog();
}
Also don't forget to hide your dialog if it hits exception so they are not permanently blocked.
Related
Hy Friend i have a problem to save id on item selected
i have a table klasis = klasis_id,klasis_name,klasis_kode.
now how i get klasis_id when i click on spinner
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("klasis");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String klasisName = jsonObject.optString("klasis_name");
// String klasisId = jsonObject.optString("klasis_id");
klasisList.add(klasisName);
klasisAdapter = new ArrayAdapter<>(AddGereja.this,
android.R.layout.simple_spinner_item, klasisList);
klasisAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerKlasis.setAdapter(klasisAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
spinnerKlasis.setOnItemSelectedListener(this);
}
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"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);
}
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();
}
I want display info and file object when clicking item in Recyclerview I am using volley and JsonObject request but can not display info and file. When I use toast for zakeran_any_madah display unclear, how to resolve my problem and display info and file for correct positionŲ Is there any other way?
This is my code
final JsonObjectRequest jsonObjectr = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
res = String.valueOf(response);
Log.d("reres", res);
datajson = response;
try {
JSONArray jsonArray = response.getJSONArray("list");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
int id = jsonObject.getInt("id");
int id_category = jsonObject.getInt("id_category");
int id_speaker = jsonObject.getInt("id_speaker");
String name = jsonObject.getString("name");
String image = jsonObject.getString("image");
String category_name = jsonObject.getString("category_name");
String speaker_name = jsonObject.getString("speaker_name");
JSONArray ja = jsonObject.getJSONArray("files");
for (int j = 0; j < ja.length(); j++) {
JSONObject jo = (JSONObject) ja.get(j);
file = jo.getString("file");
info = jo.getString("info");
Item_zakerin_any itemzakeran = new Item_zakerin_any(id, id_category, name, id_speaker, image, speaker_name, category_name, info, file);
list_zakeran_any.add(itemzakeran);
}
}
az = new adapter_zakeran_any(mcontext, list_zakeran_any);
rv.setAdapter(az);
hidepDialog();
} catch (JSONException e) {
e.printStackTrace();
hidepDialog();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hidepDialog();
}
});
jsonObjectr.setRetryPolicy(new DefaultRetryPolicy(15000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectr);
rv.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(zakeran_any_madah.this, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent motionEvent) {
ChildView =rv.findChildViewUnder(motionEvent.getX(),motionEvent.getY());
if (ChildView !=null && gestureDetector.onTouchEvent(motionEvent)){
GetItemPosition =rv.getChildAdapterPosition(ChildView);
Toast.makeText(zakeran_any_madah.this, ""+ list_zakeran_any.get(GetItemPosition), Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});