Why Volley Request Future get() method running forever - java

I am trying to make a synchronous Volley networking request. I tried to use request future to do the work. So What I am trying to do is request a JSON array, and parse it to an Array List, then use this list to set up a list view layout.
Here is the Logic code:
public void getFriendList() throws JSONException {
final String url = "http://ip/users/"+ LoginLogic.hold.getId() +"/friends";
JSONArray jsonArray = new JSONArray();
serverRequest.sendToServer(url, jsonArray, "POST");
}
#Override
public void onSuccess(JSONArray arr) throws JSONException {
for(int i = 0; i < arr.length(); i++){
JSONObject temp = arr.getJSONObject(i);
Integer id = temp.getInt("id");
String email = temp.getString("email");
String firstName = temp.getString("firstName");
String lastName = temp.getString("lastName");
friendList.add(new Friends(id, email, firstName, lastName, "null"));
}
}
#Override
public void sendToServer(String url, JSONArray newUserArray, String methodType) throws JSONException {
int method = Request.Method.GET;
if(methodType.equals("POST")){
method = Request.Method.POST;
}
RequestFuture<JSONArray> future = RequestFuture.newFuture();
JsonArrayRequest request = new JsonArrayRequest(method, url, newUserArray, future, future);
AppController.getInstance().addToRequestQueue(request, tag_json_obj);
try{
JSONArray response = future.get(5, TimeUnit.SECONDS);
I.onSuccess(response);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
I am not really familiar with volley request future, so how can I set up this property? What mistake did I make right here?

Related

JsonObject put issue with method

Very new so bear with me.
The method BloodPressure() is called in MainActivity and the values are fetched and "put" into the jsonObject.
Method getBloodPressure() will return this jsonobject and is called in another module.
The jsonobject in getBloodPressure() is always empty {}.
I have try to debug. So I can see the json is created exactly. But when I "return jsonObject" in getBloodPressure it just resets and becomes {}.
How do I call the jsonObject with bloodPressure values?
MainActivity
private static void dumpDataSet(DataSet dataSet) {
.
.
.
healthdata.BloodPressure(type, systolic, diastolic, sdate, edate );
//printed this and it works perfectly fine
}
HealthData.java
public class HealthData {
private String steps,heartRate,systolic, diastolic, bloodGlucose,bodyTemperature,age, startDate, endDate, dataType;
JSONObject jsonObject = new JSONObject();
public HealthData(){
super();
}
public void BloodPressure(String type, String sys, String dia, String sdate, String edate) {
dataType = type;
systolic = sys;
diastolic = dia;
startDate = sdate;
endDate = edate;
try {
jsonObject.put("dataType", dataType);
jsonObject.put("SystolicValue", systolic);
jsonObject.put("DiastolicValue", diastolic);
jsonObject.put("startDate", startDate);
jsonObject.put("endDate", endDate);
Log.v("json:", String.valueOf(this.jsonObject)); //prints json successfully
} catch (Exception e) {
Log.v(e.toString(), null);
}
}
public JSONObject getBloodPressure() throws JSONException {
return jsonObject; //trying to return json but its empty
}
}
AnotherModule:
public void getHealthData(Callback cb) {
try {
HealthData healthData = new HealthData();
JSONObject json = healthData.getBloodPressure(); ///calling it here
cb.invoke(null, json);
} catch (Exception e){
cb.invoke(e.toString(), null);
}
}
I saw your code and found you didn't call BloodPressure() method before getBloodPressure().
I think that you should call BloodPressure() method before getBloodPressure()
So your another module code like this.
public void getHealthData(Callback cb) {
try{
HealthData healthData = new HealthData();
healthData.BloodPressure("type", "sys", "dia", "sdate", "edate") // you must call this method.
JSONObject json = healthData.getBloodPressure(); ///calling it here
cb.invoke(null, json);
} catch (Exception e) {
cb.invoke(e.toString(), null);
}
}
Update:
I think you should not create new instance of HealthData in getHealthData() method.
public void getHealthData(Callback cb) {
try{
//HealthData healthData = new HealthData(); // this line is wrong. So I removed this line.
JSONObject json = healthData.getBloodPressure(); ///calling it here
cb.invoke(null, json);
} catch (Exception e) {
cb.invoke(e.toString(), null);
}
}

Android Volley get request, my onResponse never gets called

I know this question has been asked a few times and i have tried all the solutions however, nothing seems to work. My method:
public static LocationGeoData getLocationGeoData(Location location){
RequestQueue requestQueue = Volley.newRequestQueue(MyApplication.getAppContext());
Date dateNow = new Date();
SimpleDateFormat fmt = new SimpleDateFormat("yyyy.MM.dd");
String url = "MYCORRECTURL";
Log.d("geoData", "In getGeoData " + url); // this is called and logs
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("geoData", "inside the response");// this never gets called
try {
JSONObject jsonObject = response.getJSONObject("data");
for(int i = 0; i <jsonObject.length(); i++){
JSONObject heading = jsonObject;
if(heading.getString("field-value").equals("field-value")){
JSONObject totIntensity = heading.getJSONObject("total-intensity");
JSONObject declination = heading.getJSONObject("declination");
JSONObject inclination = heading.getJSONObject("inclination");
int totalIntensity = totIntensity.getInt("value");
double declinationValue = declination.getDouble("value");
double inclinationValue = inclination.getDouble("value");
locationGeoData = new LocationGeoData(totalIntensity, declinationValue, inclinationValue);
}
}
} catch (JSONException e) {
Log.d("geoData", "Error recorded");//never called
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("geoData", "Error recorded");// never called
}
});
requestQueue.add(request);
return locationGeoData;
}
The second Log message inside the response never gets called, i get no error messages, my url works and i can see the JsonOBject in the browser when tested, but the response is never called in my method. Can anyone advise me what i am doing wrong?

Return JSONObject with JSONArray not working in Amazon Lambda Java function

I created one Java lambda function and deploy that function to Amazon API gateway.
I want to return JSONObject with inner JSONArray.
But I got { } empty JSONObject in response.
If I set jsonobjetc.toString() in response, That will work perfectly.
But if I return JSONObject I will return empty {} JSON response.
Am I missing something?
JSONObject mainJsonObject;
#Override
public Object handleRequest(Object input, Context context) {
inputHashMap = (LinkedHashMap) input;
responseJSON = new ResponseJSON();
mainJsonObject = new JSONObject();
saveDataToDynamoDB(inputHashMap);
return mainJsonObject;
}
public void saveDataToDynamoDB(LinkedHashMap inHashMap){
String login_id = (String) inputHashMap.get("login_id");
String first_name = (String) inputHashMap.get("first_name");
String last_name = (String) inputHashMap.get("last_name");
try{
DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient());
Table tableUserDetails = dynamoDB.getTable(USER_PROFILE_TABLE);
Item userProfileTableItem = new Item().withPrimaryKey("login_id", login_id)
.withString("first_name", first_name).withString("last_name", last_name);
tableUserDetails.putItem(userProfileTableItem);
mainJsonObject.put("status", "Success");
mainJsonObject.put("message", "Profile saved successfully.");
mainJsonObject.put("login_id", login_id);
mainJsonObject.put("first_name", first_name);
mainJsonObject.put("last_name", last_name);
}catch(Exception e){
try {
mainJsonObject.put("status", "Failed");
mainJsonObject.put("message", "Failed to saved profile data.");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
In case you are calling this code from HTTP request of a web service & catch the response result in your application, then your response should be in String format (String representation of JSON object).
After you get the response in String format, then parse the JSON string to JSON Object & do your further logic.

Unable to change the value of variable name?

Can i change the value inside the compare method? Error - variable need to be declared final, but final wont allow me to change.
I want to compare some other variables the JSONarray(like total_transit_time, total_walking_time). i cant think of another solution to do that. could someone teach me an easier way to do it?
public JSONArray findShortest(JSONObject json_object) throws JSONException {
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < json_object.length(); i++) {
int name = i;
JSONObject json_array = json_object.optJSONObject(""+name);
jsonList.add(json_array);
}
System.out.println("jsonList = " + jsonList.toString());
Collections.sort(jsonList, new Comparator<JSONObject>() {
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = String.valueOf(a.get("total_duration"));
valB = String.valueOf(b.get("total_duration"));
} catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
}
});
to this
public JSONArray findShortest(JSONObject json_object, String sortByThisElement) throws JSONException {
......
......
try {
valA = String.valueOf(a.get(sortByThisElement));
valB = String.valueOf(b.get(sortByThisElement));
} catch (JSONException e) {
//do something
}
......
}
});
You can declare your sortByThisElement to be final,then you can use it directly:
public JSONArray findShortest(JSONObject json_object, final String sortByThisElement) throws JSONException {
......
......
try {
valA = String.valueOf(a.get(sortByThisElement));
valB = String.valueOf(b.get(sortByThisElement));
} catch (JSONException e) {
//do something
}
......
}
});
the other way is,create a final variable in your method,then visit it in your compare method:
public JSONArray findShortest(JSONObject json_object, String sortByThisElement) throws JSONException {
......
......
System.out.println("jsonList = " + jsonList.toString());
final String sortByThis = sortByThisElement;//note this should be add before Collections.sort
........
try {
valA = String.valueOf(a.get(sortByThis));
valB = String.valueOf(b.get(sortByThis));
} catch (JSONException e) {
//do something
}
......
}
});

Efficient way of downloading data in Android App from MySQL

I was just wondering if my code is ok in terms of downloading. My app needs a lot of data from a database so quick download times are crucial. The download time is ok but I think it can be programmed more efficient. Can you have a look at this? This class downloads many different companies and when downloaded they are put in a HashMap corresponding to their category. When finished downloading this class return a HashMap which contains multiple Hashmaps(categories) and in these Hashmaps the downloaded data. Dont mind the actual workflow but please concentrate on the way this class downloads data. Is there a way to do this faster?
public class CompanyDAO {
private static Controller delegate;
private static String companyUrl = "http:// URL HERE";
private Map<Object, Object> companyMap = new HashMap<Object, Object>();
private Map<String, Integer> pinMap = new HashMap<String, Integer>();
public CompanyDAO (Controller _delegate, Map<String, Integer> map) {
delegate = _delegate; //reference to controller
pinMap = map;
}
public void getCompanyData(ArrayList<Object> categoriesArray) {
for (int i = 0; i < categoriesArray.size(); i++) {
Map<String, Object> categoriesInMap = new HashMap<String, Object>();
//ArrayList<Object> categoriesInMapArray = new ArrayList<Object>();
companyMap.put(categoriesArray.get(i), categoriesInMap);
}
this.downloadCompanyData();
}
private void downloadCompanyData() {
companyUrl = companyUrl + delegate.ID;
try {
new DownloadCompanyData().execute(companyUrl).get(10000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class DownloadCompanyData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#SuppressWarnings("unchecked")
#Override
protected void onPostExecute(String result) {
JSONArray companyDataArray;
try {
companyDataArray = new JSONArray(result);
for(int i=0;i<companyDataArray.length();i++){
JSONObject id = companyDataArray.getJSONObject(i);
String catName = id.getString(Controller.CAT_NAME);
if (companyMap.get(catName) != null) {
Markers marker = new Markers(new LatLng(id.getDouble("latitude"), id.getDouble("longitude")), id.getString(Controller.CAT_NAME), id.getString(Controller.ID), id.getString(Controller.SUBSCRIPTION), pinMap.get(catName), id.getString(Controller.TITLE), id.getString(Controller.COMPANY_NAME), id.getString(Controller.WWW), id.getString(Controller.STREET), id.getString(Controller.HOUSE_NUMBER), id.getString(Controller.HOUSE_ADD));
((Map<String,Object>) companyMap.get(catName)).put(id.getString(Controller.TITLE), marker.markerInformationMap);
}
}
delegate.setCompanyHashMap(companyMap);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I guess you're missing the point of the AsyncTask
it's supposed to do all the work in doInBackground() and then use the onPostExecute to deliver it to the UI.
But what you're doing is doing the network operation on doInBackground and doing data parsing on onPostExecute.
Furthermore, a JSON object is a raw data that needs further parsing. You should do all the parsing on the background. For example, let's say your companyData is address, phone number, size and name. You could have a class like this (p.s. I'm writing all this without testing, there will be a little mistake here in there, but you'll get the idea):
public class CompanyData{
private String name, address, phone;
private int size;
public CompanyData(JsonObject jo){
name = jo.getString("name");
address = jo.getString("address");
phone = jo.getString("phone");
size = jo.getInt("size");
}
// put a bunch of get methods here...
// getName(), getAddress(), etc.
}
then on your 'protected Map doInBackground(String... urls) ' you complete the network operation, create the JsonArray, create a Map<String,CompanyData>, loop through the array creating CompanyData objects and placing them into the Map and return the map to your protected void onPostExecute(Map<String,CompanyData> result) and inside the post execute it's just pass this result to the UI.
happy coding.
I always doing something like this..
...
private ProgressDialog pDialog;
ArrayList<HashMap<String, String>> CompanyList;
JSONParser jParser = new JSONParser();
JSONArray Company = null;
static String url_all_company = "http://your_site/files.php";
....
private class CompanyData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Load data..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
CompanyList = new ArrayList<HashMap<String, String>>();
// Building Parameters if any.. to fetching all data, don't declare any param
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("uid", uid));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_company, "POST", param);
// Check your log cat for JSON reponse
Log.d("All Company: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// Company found
// Getting Array of Company
Company = json.getJSONArray(TAG_COMPANIES);
// looping through All Company
for (int i = 0; i < Company.length(); i++) {
JSONObject json = Company.getJSONObject(i);
// Storing each json item in variable
String id = json.getString(TAG_GID);
String name = json.getString(TAG_NAME);
String jml = json.getString(TAG_EMPLOYEE);
String deskripsi = json.getString(TAG_DESKRIPSI);
String logo = json.getString(TAG_LOGO);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_GID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMPLOYEE, jml);
map.put(TAG_DESKRIPSI, deskripsi);
map.put(TAG_LOGO, logo);
// adding HashList to ArrayList
CompanyList.add(map);
}
} else {
// no CompanyList found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing data ArrayList
adapter=new LazyAdapter(MainActivity.this, CompanyList);
list.setAdapter(adapter);
pDialog.dismiss();
}
}

Categories

Resources