I am using volley library and I want to pass data from a JSON API url with the GET method. What exactly I need is to get the user ID == CurrentUserId. Here is my full code:
RequestQueue queue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, JSON_URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject usersObject = response.getJSONObject(i);
Toast.makeText(getContext(), "Name: "+usersObject, Toast.LENGTH_LONG).show();
String ID = usersObject.getString("ID");
if (ID.equalsIgnoreCase(CurrentUser)) {
String fullName = usersObject.getString("fullName");
String userName = usersObject.getString("username");
fullname.setText(fullName);
username.setText(userName);
} else {
fullname.setText("No Name");
}
Toast.makeText(getContext(), "Name: "+CurrentUser, Toast.LENGTH_SHORT).show();
Toast.makeText(getContext(), "Name: "+ID, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
Log.d("CATCH", e.getMessage());
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(jsonArrayRequest);
The downside is that when I use the for loop the code continues to read every item of the JSON. On the other hand when I don't use the for loop I have to set an array index here JSONObject usersObject = response.getJSONObject(i);. So, what index should I set in order to make the code read every item and stop to what is ID == CurrentUserId?
Related
I got a function where Im making an arrayrequest with the purpose to get the quantity of the registers from de callback; but, Im trying to return that number for the function.
I´m declaring a variable that gets the lenght or size of the temporal ArrayList, which it´s filled whith the response of the api request using the volley library.
public int Contar(int position){
final int[] Cant = new int[1];
ArrayList<Entidad_Decision> listaO = new ArrayList<>();
if (position == 0){
RequestQueue requestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET, "http:My Api IP", null,
new Response.Listener<JSONArray>() {
#SuppressLint("SetTextI18n")
#Override
public void onResponse(JSONArray jsonArray) {
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String numero_de_decision = jsonObject.getString("NUMERO_DE_DECISION");
listaO.add(new Entidad_Decision(numero_de_decision,"","responsables","fecha" + " - " + "plazo", "observaciones", "procede", "status"));
}
//buscar.setText(listaO.size() + "");
Cant[0] = listaO.size();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
arrayRequest.setRetryPolicy(new DefaultRetryPolicy(MY_DEFAULT_TIMEOUT4,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(arrayRequest);
}else if (position == 1){
RequestQueue requestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET, "http:My API IP", null,
new Response.Listener<JSONArray>() {
#SuppressLint("SetTextI18n")
#Override
public void onResponse(JSONArray jsonArray) {
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String numero_de_decision = jsonObject.getString("NUMERO_DE_DECISION");
listaO.add(new Entidad_Decision(numero_de_decision,"","responsables","fecha" + " - " + "plazo", "observaciones", "procede", "status"));
}
//buscar.setText(listaO.size() + "");
Cant[0] = listaO.size();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
arrayRequest.setRetryPolicy(new DefaultRetryPolicy(MY_DEFAULT_TIMEOUT,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(arrayRequest);
}
return Cant[0];
}
When I´m calling that variable, the value is 0.
How can I solve this??
I have a method that call a api and fill a ArrayList with data. The method is in a fragment, when I open the App it adds data to the arrayList, but when I go to another fragment or activity and come back it doesnt show any in the recyclerview from the ArrayList as if nothing is there, but when I toast the size of array, it returns the number of elements that should be there
but it doesnt show/populate the recyclerview with the elements.
I call the method in onCreateView()
CALLING API
private void getDataFromUAPI(String gist_json_url){
requestQueue = MySingleton.getInstance(this.getContext()).getRequestQueue();
request = new JsonArrayRequest(Method.GET, gist_json_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0; i < response.length(); i ++){
try {
jsonObject = response.getJSONObject(i);
User user = new User();
// if this user Id is not user Id of the user and
// if user are already been followed, than don't add
if (!jsonObject.getString("id").equals(firebaseUser.getUid()) && !sharedPreferences.contains(jsonObject.getString("id"))) {
user.setPhoto(jsonObject.getString("photo"));
user.setName(jsonObject.getString("name"));
user.setFnumber(jsonObject.getString("fnumber"));
user.setId(jsonObject.getString("id"));
responseList.add(user);
}
//Toast.makeText(getContext(), user.getId(), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getContext(), String.valueOf(responseList.size()), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "ERROR \n" + error.toString(), Toast.LENGTH_LONG).show();
}
});
requestQueue.add(request);
I build an app, that it load markers in a map, the markers I get it for volley JSON file, but I need that first to load volley, and after continue executing the code, because the other way show me error with latLng null, this parameter is not loaded fast, and another method execute first and show me null.
My volley code for load markers
public void getMarkers(){
requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray saagTracker = response.getJSONArray("saagMRK");
for (int i = 0; i < saagTracker.length(); i++) {
JSONObject object = saagTracker.getJSONObject(i);
title = object.getString(TITLE);
snnipet = object.getString(SNNIP);
latLng = new LatLng(Double.parseDouble(object.getString(LAT)), Double.parseDouble(object.getString(LNG)));
coor = coor + "|" + object.getString(LAT) + "," + object.getString(LNG); // Menambah data marker untuk di tampilkan ke google map
addMarker(latLng, title, snnipet);
}
} catch (JSONException e) {
e.printStackTrace();
}
//JSONArray array = new JSONArray(response.body().string());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Ocurrio un error", Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonObjectRequest);
}
onCreate it need latLng first for it to can load my geofire parameter
geoQuery = geofire.queryAtLocation(new GeoLocation(latLng.latitude, latLng.longitude),0.1f); // latLng it coming null
You would need to implement a call back for the volley response. A very simple way to do this would be the following.
Step 1: Create this interface
public interface VolleyCallBack {
void onSuccess();
}
Step 2: change your getMarkers() method to this:
public void getMarkers(final VolleyCallBack callBack){
requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray saagTracker = response.getJSONArray("saagMRK");
for (int i = 0; i < saagTracker.length(); i++) {
JSONObject object = saagTracker.getJSONObject(i);
title = object.getString(TITLE);
snnipet = object.getString(SNNIP);
latLng = new LatLng(Double.parseDouble(object.getString(LAT)), Double.parseDouble(object.getString(LNG)));
coor = coor + "|" + object.getString(LAT) + "," + object.getString(LNG); // Menambah data marker untuk di tampilkan ke google map
addMarker(latLng, title, snnipet);
callback.onSuccess();
}
} catch (JSONException e) {
e.printStackTrace();
}
//JSONArray array = new JSONArray(response.body().string());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Ocurrio un error", Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonObjectRequest);
}
Step 3: Call your getMarkers() method like this:
getMarkers(new VolleyCallBack() {
#Override
public void onSuccess() {
// this is where you will call the geofire, here you have the response from the volley.
geoQuery = geofire.queryAtLocation(new GeoLocation(latLng.latitude, latLng.longitude),0.1f);
});
I'm using Volley to get information from an SQL database, from server, and I get it in a JSONArray. When I extract values from the JSONArray so I can save values to an ArrayList, in the return statement I get null in my ArrayList. Can anyone help with the return statement?
#Override
public List<WorkItem> getWorkItem() {
final String url = "http://10.0.2.2:8080/items/all/items";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("Response", response.toString());
try {
arrayList = new ArrayList<>();
response = new JSONArray(response.toString());
for (int i = 0; i < response.length(); i++) {
JSONObject jsonobject = response.getJSONObject(i);
String title = jsonobject.getString("title");
String description = jsonobject.getString("description");
String state = jsonobject.getString("status");
String assignee = jsonobject.getString("assignee");
arrayList.add(new WorkItem(title, description, state, assignee));
arrayList.size();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
}
});
jsonArrayRequest.setTag(REQUEST_TAG);
mQueue.add(jsonArrayRequest);
return arrayList;
}
I have a button and when the button is clicked, I would like it to automatically update the text, the catch is that the text is coming from a server and I am parsing it via JSON. My question is how can I automatically update the text when the button is clicked without a complete refresh?
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);
}
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");
String selectedId = currentQuestions.getString("selected");
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);
blogs.setSelected(selectedId);
System.out.print(Answerid);
listblogs.add(blogs);
}
System.out.println(data.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
The only thing I have tried it recalling the jsonarray in my listener
public void OnDown(View view) {
CharSequence IdDownVote = ((TextView) ((RelativeLayout) view.getParent()).getChildAt(1)).getText();
final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
final String PUT_VOTE_DOWN = "someURL";
StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_DOWN, 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");
}
public void ClickCardAnswer(View view) {
System.out.println("YOU CLICKED THE CARD");
}
}
Your question is a little ambiguous, but I'll try to answer the two possible problems you might have:
You have updated the item in the adapter but it won't display the new content: use notifyItemChanged(int position) of the adapter class
You want to update the item in the adapter. Apart from the setBloglist() of the adapter class you need to make a method to update a certain item in the dataset (either by position in list or looking it up via id - I usually use the ID version). After update, see point 1 above.