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) {
}
});
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"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);
}
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.
My issue is i have a list of products on my listview, when i select one of the values from my spinner i save it and send it to retrieve different values from my mysql database, The problem i have is that my listview wont update after i perform the onclick event on my spinner, what am I doing wrong? I dont know if i managed to explain correctly what i want to say, thank you for your help
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected (AdapterView < ? > parent, View view,int pos, long id)
{
filtracat();
}
private void filtracat() {
cat = spinner.getSelectedItemPosition()+1;
valor = String.valueOf(cat);
Toast.makeText(getApplicationContext(),valor,Toast.LENGTH_SHORT).show();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(JSON_CAT, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
hideDialog();
//parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Anuncios item = new Anuncios();
item.setKey(obj.getString("key"));
item.setTitulo(obj.getString("titulo"));
item.setImageID(obj.getString("imageID"));
item.setModelo(obj.getString("modelo"));
item.setPreco(obj.getString("preco"));
//gonna set category here
// item.setCategoria(obj.getString("categoria"));
//add to array
array2.add(item);
} catch (JSONException ex) {
ex.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("valor", valor);
return params;
}
};
AppController.getmInstance().addToRequesQueue(jsonArrayRequest);
}
the original data from my listview comes from
private void sendRequest() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(JSON_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
hideDialog();
//parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Anuncios item = new Anuncios();
item.setKey(obj.getString("key"));
item.setTitulo(obj.getString("titulo"));
item.setImageID(obj.getString("imageID"));
item.setModelo(obj.getString("modelo"));
item.setPreco(obj.getString("preco"));
//gonna set category here
// item.setCategoria(obj.getString("categoria"));
//add to array
array.add(item);
} catch (JSONException ex) {
ex.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getmInstance().addToRequesQueue(jsonArrayRequest);
}
should i be using the same array to update the data?
You can try
Create Two object
ArrayList<MobileKeyModel> dropDownModels = new ArrayList<MobileKeyModel>();
ArrayList<Object> addList = new ArrayList<Object>();
You can get response from database
private void filtracat() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray loginNodes = jsonObject.getJSONArray("parentnodesList");
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String key = jo.getString("key");
String titulo = jo.getString("titulo");
addList.add(key);
addList.add(titulo);
}
pupulateDropDownList();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try {
//Respose Error
} catch (Exception e) {
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
populate value to listview
void pupulateDropDownList() {
if (addList != null) {
for (Iterator<Object> i = addList.iterator(); i.hasNext(); ) {
MobileKeyModel menuModel = new MobileKeyModel(i.next().toString(), i.next().toString());
dropDownModels.add(menuModel);
}
ArrayAdapter adapter = new ArrayAdapter(this, R.layout.spinner_text, dropDownModels);
adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown);
listView.setAdapter(adapter);
}
}
Model is also here
public class MobileKeyModel {
public String key = "";
public String titulo = "";
public MobileKeyModel(String key, String titulo) {
this.key = key;
this.titulo = titulo;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
}
Note Your json must be look like
{"parentnodesList":[{"key":"your key value here","titulo":"Your title"}]}