I am using Volley to make Api call and set data to RecyclerView.I have my first Volley where I get Id field and I use this same Id to make another Api call. I used the response from both api call at same time and set the data to RecyclerView.But the response from second Api call is not set on Recyclerview at same time.Later I manually refresh tab and set data from Database its set.
This is my nested Volley Api call
private void getData() {
final JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, ApiUrls.FirstCall, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
if (response != null) {
for (int i = 0; i < response.length(); i++) {
JSONObject object = response.getJSONObject(i);
CurrentStatusEntry entry = new CurrentStatusEntry();
String Id= object.getString("id");
id_url = ApiUrls.Info+ Id + "/";
JsonObjectRequest foodie_request = new JsonObjectRequest(Request.Method.GET, id_url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String name=response.getString("name");
String address=response.getString("address");
entry.setName(name);
entry.setAddress(address);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
AppController.getInstance().addToRequestQueue(foodie_request, foodie_data_req);
current.add(entry);
if (current.size() > 0) {
adapter = new QueueAdapter(current, getActivity().getApplicationContext());
recyclerView.setAdapter(adapter);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
})
AppController.getInstance().addToRequestQueue(request, restqueue_req);
}
The data from second api call is not set instantly. How to perform this ?
Related
I am fetching data from db and want to set text. Values are getting fetched and displaying in url but setText not working, when I used JSONObject also same problem. Where am I going wrong.? Below is my code and backend output.
{
"status": 200,
"db": {
"test_count": 2539,
"franchise_count": 2,
"patient_count": 1,
"invoice_count": 1,
"total_income": "12140",
"current_income": "12140",
"total_expense": null,
"current_expense": null,
"user_count": 2
}}
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressDialog.dismiss();
try {
JSONObject object = new JSONObject();
u = object.getString("user_count");
user_count.setText(u);
} catch (JSONException e) {
Toast.makeText(getContext(),"No Records Found",Toast.LENGTH_LONG);
Log.e("Error", "Failed" +e.toString());
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.e("Error", "Try Later" +error.toString());
Toast.makeText(getContext(),"No Records Found",Toast.LENGTH_LONG);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(objectRequest);
}
Change your try block contents like below
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressDialog.dismiss();
try {
JSONObject newObject=response.getJSONObject("db");
u = newObject.getString("user_count");
user_count.setText(u);
} catch (JSONException e) {
Toast.makeText(getContext(),"No Records Found",Toast.LENGTH_LONG);
Log.e("Error", "Failed" +e.toString());
e.printStackTrace();
}
}
I want to send and receive data from server. For this I've used Volley. The code is in below. Volley can receive the data in Json format. The Server can send and receive data in Json format. How do I convert this Json data into a user readable JAVA format ?? There are about 10 methods in other class. The below class contains the methods for network calls and also interacts with the MainActivity.
public class Api_Volley {
String data;
String flag;
public void my_volley_post (String url , JSONObject jsonObject , final Context context ) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url , jsonObject , new Response.Listener(){
#Override
public void onResponse(Object response) {
String flag = response.toString();
Toast.makeText( context , flag , Toast.LENGTH_LONG ).show();
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context , "Wrong" , Toast.LENGTH_LONG).show();
error.printStackTrace();
}
});
ApiVolleySingeltonClass.getInstance(context).addToRequestque(jsonObjectRequest);
}
}
Methods in another class:
public void showAllOrderByUserId() {
try {
data_args.put("userId", 2);
} catch (JSONException e) {
e.printStackTrace();
}
try {
data_action.put("action", "showAllOrderByUserId");
data_action.put("args", data_args);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
route = "/order";
new Api_Volley().my_volley_post(addUserUrl + route, data_action, context);
}
Your can use json data like
{"userNodes":[{"id":"1","name":"Enamul Haque"}]}
You can use volley like bellow
private void doLoginAction() {
String url_login = "http://www.lineitopkal.com/android/login.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_login,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//pDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray loginNodes = jsonObject.getJSONArray("userNodes");
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String id = jo.getString("id");
Log.e("id ::",id);
String name = jo.getString("name");
Log.e("name ::",name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try {
if (error instanceof TimeoutError ) {
//Time out error
}else if(error instanceof NoConnectionError){
//net work error
} else if (error instanceof AuthFailureError) {
//error
} else if (error instanceof ServerError) {
//Erroor
} else if (error instanceof NetworkError) {
//Error
} else if (error instanceof ParseError) {
//Error
}else{
//Error
}
//End
} catch (Exception e) {
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
//Post parameter like bellow
params.put("uname", "era#gmail.com");
params.put("pass", "123456");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Create your Response format like this
public class Post {
long id;
Date dateCreated;
String title;
String author;
String url;
String body;
}
After making request like below
public void my_volley_post (String url , JSONObject jsonObject , final Context context ) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url , jsonObject , new Response.Listener(){
#Override
public void onResponse(String response) {
GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
// This will be your Entity
Post post = gson.fromJson(response, Post.class));
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context , "Wrong" , Toast.LENGTH_LONG).show();
error.printStackTrace();
}
});
ApiVolleySingeltonClass.getInstance(context).addToRequestque(jsonObjectRequest);
}
You have to parse JSON and have to show according to need:
By this you can use GSON (Its easy)
Use this Site to convert JSON to pojo classes.
Click here
These are the References site you can use and implement :
http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html
https://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
https://kylewbanks.com/blog/tutorial-parsing-json-on-android-using-gson-and-volley
I need to maintain a session for below REST API call from Android app. I'm able to call these API using volley, But the session is not being maintained.
I first call validateUser API to validate the user and store his email in session.
Then I need to call getDashboardDetails to fetch user details, But email in session object is null
// Spring REST code
#RequestMapping(value = "/validateUser", method = RequestMethod.POST)
#ResponseBody
public ResponseEntity<UserVO> validateUser(#RequestBody UserVO userVO, HttpSession session, HttpServletResponse response) {
HttpStatus httpStatus = HttpStatus.OK;
validatedUserVo = userService.getUserDetails(userVO);
session.setAttribute("email", validatedUserVo.getEmail());
return new ResponseEntity<UserVO>(validatedUserVo, httpStatus);
}
#RequestMapping(value = "/getDashboardDetails", method = RequestMethod.GET)
public ResponseEntity<List<DashBoardVO>> getDashboardDetails(HttpSession session) {
List<DashBoardVO> dashBoardVOList = null;
HttpStatus httpStatus = HttpStatus.OK;
String email = (String)session.getAttribute("email");
if(email!=null){
dashBoardVOList = dashboardService.getDashboardDetails(email);
}
else{
httpStatus = HttpStatus.BAD_REQUEST;
}
return new ResponseEntity<List<DashBoardVO>> (dashBoardVOList, httpStatus);
}
// validateUser call in LoginActivity
json.put("email",username1.getText().toString());
json.put("password",password1.getText().toString());
JsonObjectRequest login_data = new
JsonObjectRequest(Request.Method.POST, url, json,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
StringBuffer s = null;
tv.setText(response.toString());
edit.putBoolean("login_success",true);
edit.commit();
Intent i = new Intent(LoginActivity.this,DashboardActivity.class);
try {
i.putExtra("name",response.getString("name"));
i.putExtra("role",response.getString("role"));
} catch (JSONException e) {
e.printStackTrace();
}
startActivity(i);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tv.setText(error.toString());
}
});
RequestQueue rq = Volley.newRequestQueue(this);
rq.add(login_data)
//sharedPreferences in LoginActivity
boolean b = sharedPreferences.getBoolean("login_success",false);
if(b){
Intent i = new
Intent(LoginActivity.this,DashboardActivity.class);
startActivity(i);
}
// getDashboardDetails call in DashboardActivity
JsonArrayRequest j1 = new JsonArrayRequest(Request.Method.GET, url,
null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONObject temp = response.getJSONObject(1);
tv.setText(temp.getString("id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tv.setText(error.toString());
}
});
RequestQueue rq = Volley.newRequestQueue(this);
rq.add(j1);
How do I use/maintain session between different api calls? in android app
im pretty new to Android Studio and I'm trying to build a Get Request using Volley, the Server response is a JsonObject. I tested the code with breakpoints but I wonder why I don't jump into onResponse or why it won't work.
Here's my Code of the Get Method:
public Account GetJsonObject(String urlExtension, String name, Context context) {
String baseURL = "myurl.com/api";
baseURL += urlExtension + "/" + name;
// url will look like this: myurl.com/api/user/"username"
final Account user = new Account("","");
//Account(name, email)
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.GET, baseURL,null,
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = response.getJSONObject("userObject");
String username = obj.getString("Username");
String email = obj.getString("Email");
user.setUsername(username);
user.setEmail(email);
}
catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObject);
return user;
}
As #GVillavani82 commented your onErrorResponse() method body is empty. Try to log the error like this
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR", "Error occurred ", error);
}
}
Make sure that you have the below permission set in AndroidManifest.xml file and the api URL is proper.
<uses-permission android:name="android.permission.INTERNET"/>
And JsonObjectRequest class returns Asynchronous network call class. Modify your code like below.
// remove Account return type and use void
public void GetJsonObject(String urlExtension, String name, Context context) {
....
.... // other stuffs
....
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.GET, baseURL,null,
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
processResponse(response); // call to method
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR", "Error occurred ", error);
}
});
requestQueue.add(jsonObject);
}
Now create another method like below
private void processResponse(JSONObject response) {
try {
final Account user = new Account("","");
JSONObject obj = response.getJSONObject("userObject");
String username = obj.getString("Username");
String email = obj.getString("Email");
user.setUsername(username);
user.setEmail(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
I am beginning in my journey in Android development so might be doing this all wrong. I am trying to get a set of data using Volley and display it which is ok.
The next step I need to do is use the data to make further requests.
The first request gets a list of sports teams.
I then want to make a request for each team to get the players.
Ideally what I'd like to do is make the first request and return the JSONobject to be used with another class. I have no idea how i would do this.
teamData.getTeams(
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//i want to get this out somehow
JSONObject thing = response;
}//end on response
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Show error or whatever...
}
});
I'm happy to expand on this if need be.
Volley is enqueuing the request so it fires a request after the older one has returned success or error.
So you can enqueue a new request in the success of the older.
Exemple : in your response of your team request you add a new request as you did JSONObject thing = response;
This is an exemple of mine witch imports multiple projects and then imports each project infos:
public void importProjects() {
Response.Listener<JSONArray> jsonArrayResponseListener;
String url = Globals.getApiBaseUrl() + GET_PROJECTS_URL;
jsonArrayResponseListener = new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
ArrayList<Project> projects = MyJsonParser.getInstance().parseProjects(response);
if (projects.size() > 0) {
for (Project p : projects) {
importProject(p); //####### HERE IS THE KEY :: this methode is the same of this one. It calls other volley request.#######//
}
}
} catch (Exception e) {
Log.e("SyncRngine", "THIS IS AN ERROR");
e.printStackTrace();
}
}
};
Response.ErrorListener responseError;
responseError = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
};
url = formatUrl(url, params);
Log.i("URL IMPORT PROJECTS", url);
MyVolleyJsonArrayRequest customRequest = new MyVolleyJsonArrayRequest(Request.Method.GET, url, jsonArrayResponseListener, responseError);
MyVolley.getInstance(activity.getApplicationContext()).addToRequestQueue(customRequest);
}
And now the défénition of importProject(Project p) :
public void importProject(final Project project) {
String url = Globals.getApiBaseUrl() + GET_PROJECT_URL;
Response.Listener<JSONArray> jsonArrayResponseListener;
jsonArrayResponseListener = new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
useProjectInfos(response);
} catch (Exception e) {
e.printStackTrace();
}
}
};
Response.ErrorListener responseError;
responseError = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
};
url = url + "/" + project.getProjectID();
url = formatUrl(url, params);
MyVolleyJsonArrayRequest customRequest = new MyVolleyJsonArrayRequest(Request.Method.GET, url, jsonArrayResponseListener, responseError);
MyVolley.getInstance(activity.getApplicationContext()).addToRequestQueue(customRequest);
}