JsonObject put issue with method - java

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);
}
}

Related

Why Volley Request Future get() method running forever

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?

Java : How to extend a class and use a dot notation on its object

Take for example the class JSONObject.
And say I have the following method.
public JSONObject getObjectOrThrow(String name) {
JSONObject jsonObject = null;
try {
jsonObject = JSON.getJSONObject(name);
} catch (Exception e) {
System.out.println("JSON_ERROR : " + name);
e.printStackTrace();
}
return jsonObject;
}
How do I extend the JSONObject so that I'll end up with a method like.
JSONObject man = new JSONObject("name");
man.getObjectOrThrow("name");
Where "name" is the key to the child node of "man".
Also for reference, what is this called?
Custom Class
public class CustomJSONObjectProvider extends JSONObject {
public JSONObject getObjectOrThrow(String name) {
JSONObject jsonObject = null;
try {
jsonObject = JSON.getJSONObject(name);
} catch (Exception e) {
System.out.println("JSON_ERROR : " + name);
e.printStackTrace();
}
return jsonObject;
}
// all the other custom methods that you want to override
}
And the way you use it
CustomJSONObjectProvider customJSONObjectProvider = new CustomJSONObjectProvider();
JSONObject jsonObject = customJSONObjectProvider.getObjectOrThrow("name");
It can also be static
public class CustomJSONObjectProvider extends JSONObject {
public static JSONObject getObjectOrThrow(String name) {
JSONObject jsonObject = null;
try {
jsonObject = JSON.getJSONObject(name);
} catch (Exception e) {
System.out.println("JSON_ERROR : " + name);
e.printStackTrace();
}
return jsonObject;
}
// all the other custom methods that you want to override
}
Its usage
JSONObject jsonObject = CustomJSONObjectProvider.getObjectOrThrow("name");

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
}
......
}
});

How to get value of jsonObject value in android?

I am building an android application and I am new to json. I am fetching below josn formate -
{
"contact"[
{
"key1": "hey1",
"key2": [
{
"key3": "hey2"
}
]
}
]
}
I am using below code to fetch key1 value. Now problem I am facing is how to fetch key3 value -
jsonString = http.makeServiceCall(url, ServiceHandler.GET, null);
if (jsonString != null) {
try {
JSONObject jsonObj = new JSONObject(jsonString);
// Getting JSON Array node
questions = jsonObj.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < questions.length(); i++) {
temp_obj = questions.getJSONObject(i);
key1Array.add(temp_obj.getString("key1").toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Please help me
If you want to use Gson to parse your json data. Let try it:
First of all, you must modify your json like this:
{
"contact":[
{
"key1": "hey1",
"key2": [
{
"key3": "hey2"
}
]
}
]
}
Second add Gson to your libs and sync build.gradle: download here extract it, and copy/past gson-2.2.4.gson to libs folder.
Third Create some class:
FullContents.java:
public class FullContents {
private List<ObjectKey> contact;
public List<ObjectKey> getContact() {
return contact;
}
public void setContact(List<ObjectKey> contact) {
this.contact = contact;
}
}
ObjectKey.java:
public class ObjectKey {
private String key1;
private List<ObjectKey3> key2;
public List<ObjectKey3> getKey2() {
return key2;
}
public void setKey2(List<ObjectKey3> key2) {
this.key2 = key2;
}
public String getKey1(){
return key1;
}
public void setKey1(String key1){
this.key1 = key1;
}
}
ObjectKey3.java:
public class ObjectKey3 {
private String key3;
public String getKey3(){
return key3;
}
public void setKey3(String key3){
this.key3 = key3;
}
}
And Finally, get data from url:
private class ParseByGson extends AsyncTask<String,Void,FullContents> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected FullContents doInBackground(String... params) {
FullContents fullContents = null;
try {
URL url=new URL(params[0]);
InputStreamReader reader=new InputStreamReader(url.openStream(),"UTF-8");
fullContents=new Gson().fromJson(reader,FullContents.class);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fullContents;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(FullContents results) {
super.onPostExecute(results);
ObjectKey objectKey = results.getContact().get(0);
Log.e(">>",objectKey.getKey1()+"--");
}
}
you can put below code to onCreate:
ParseByGson parseByGson = new ParseByGson();
parseByGson.execute(urlStringHere);
Update: Explain
1st of all: your json appears to be not valid (missing ':' after "content");
After reviewing thins:
You can use the named getters to retrieve many types of results (object, int, string, etc);
JSONObject contact = jsonObj.getJSONObject("contact"); // {"key1":"hey1","key2":[{"key3":"hey2"}]}
or
String key1 = jsonObj.getString("key1"); // hey1
To retrieve key3, you should use:
JSONObject contact = jsonObj.getJSONObject("contact");
JSONObject key2 = contact.getJSONObject("key2");
String key3 = key2.getString("key3");
Adapt the following code to what you are coding
for (int i = 0; i < questions.length(); i++) {
temp_obj = questions.getJSONObject(i);
key1Array.add(temp_obj.getString("key1"));
JSONObject temp_objKey2 = temp_obj.getJSONObject("key2");
Key2Object key2Object = new Key2Object();
key2Object.add(temp_objKey2.getString("key3"));
key1Array.add(key2Object);
}

Can't access to static variable android

Overview; i need to create a json from a List to store in a sqlLite database. When i try to create the json Eclipse gets me an error that the variable List must be static. If this variable changed to static my application shows incorrect results and it's not a good thing. This is the class in which i create the json
public class Soluzione {
public String durata;
public List<Corsa> corse;
public Soluzione() {
corse = new ArrayList<Corsa>();
}
#Override
public String toString() {
StringBuilder str = new StringBuilder();
for (Corsa corsa : corse) {
if (str.length() > 0)
str.append('\n');
str.append(corsa.toString());
}
return str.toString();
}
public static JSONObject CreateJSon(List<Corsa> corse)
{
JSONObject jObj = new JSONObject();
try
{
Corsa prima = Soluzione.corse.get(0);
Corsa ultima = Soluzione.corse.get(corse.size()-1);
jObj.put("oraPartenza", prima.oraPartenza);
jObj.put("oraArrivo", ultima.oraArrivo);
jObj.put("partenza", prima.partenza);
jObj.put("arrivo", ultima.arrivo);
} catch (Exception e) { e.printStackTrace(); }
return jObj;
}
}
It is ambiguous between your field corse and the parameter of your method Create JSON.
Do not make method static and remove parameter
public JSONObject CreateJSon()
{
JSONObject jObj = new JSONObject();
try
{
Corsa prima = Soluzione.corse.get(0);
Corsa ultima = Soluzione.corse.get(corse.size()-1);
jObj.put("oraPartenza", prima.oraPartenza);
jObj.put("oraArrivo", ultima.oraArrivo);
jObj.put("partenza", prima.partenza);
jObj.put("arrivo", ultima.arrivo);
} catch (Exception e) { e.printStackTrace(); }
return jObj;
}
EDIT :
so if you want to keep CreateJSon static, rename the parameter name to avoid ambiguity then :
Soluzione soluzione = new Soluzione();
Soluzione.CreateJSon (soluzione.corse);
OR you want to remove static attribute and you can remove parameter and you do :
Soluzione soluzione = new Soluzione();
soluzione.CreateJSon ();

Categories

Resources