Can't access to static variable android - java

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

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

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 handle non-existent data in JSONParser in Java

I have a JSONParser method like this :
public ArrayList<Meaning> parseMeaning (JSONObject object)
{
ArrayList<Meaning> arrayList = new ArrayList<Meaning>();
try
{
JSONObject value = object.getJSONObject("Value");
JSONArray meaningArray = value.getJSONArray("Meanings");
JSONObject meaningobj = null;
for(int i = 0; i < meaningArray.length(); i++) {
meaningobj = meaningArray.getJSONObject(i);
Meaning myMeaning = new Meaning();
myMeaning.MeaningID = meaningobj.getInt("MeaningID");
myMeaning.Type1 = meaningobj.getInt("Type1");
myMeaning.Type2= meaningobj.getInt("Type2");
arrayList.add(myMeaning);
}
}
catch (JSONException e)
{
Log.d("JSONParser=>parseMeaning", e.getMessage());
}
return arrayList;
}
My meaning class is like this :
public class Meaning {
public int MeaningID;
public Integer Type1;
public Integer Type2;
}
When I run the code, some JSON Objects don't have Type2 value (because they were null in the database). So I get this exception :
D/JSONParser=>parseMeaning﹕ No value for Type2
Can you tell me how I should handle such situations when there is no value for a field? Thanks.
You can use has method of JSONObject.
E.g. :
if(meaningobj.has("Type2")){
myMeaning.Type2= meaningobj.getInt("Type2");
}

How to gather data from a JSON URL and display it

I am trying to write an automated Java test where the code will go to a specified URL, read the JSON data and print it up.
Here is the JSON I am trying to access;
{
"status": "success",
"records": [
{
"timestamp": 1381222871868,
"deviceId": "288",
"temperature": 17
},
{
"timestamp": 1381222901868,
"deviceId": "288",
"temperature": 17
},
{
"timestamp": 1381222931868,
"deviceId": "288",
"temperature": 17
},
]}
As you can see I only have 3 elements, Timestamp, DeviceId and Temperature.
What I am ultimately aiming for it to be able to get 2 Timestamp values and take one value away from the other, if that is possible.
Anyway I have been trying to do this all day and am having no luck whatsoever. I was recommended to use Gson and I have included the jar files into my classpath.
If anyone knows anything or can help me in any way it would be much appreciated as I have exhausted Google and myself trying to work this out.
Here is the code I have to display the full list, but I do not fully understand it and so far can't manipulate it to my advantage;
public static void main(String[] args) throws Exception
{
String jsonString = callURL("http://localhost:8000/eem/api/v1/metrics/temperature/288");
System.out.println("\n\njsonString: " + jsonString);
// Replace this try catch block for all below subsequent examples
/*try
{
JSONArray jsonArray = new JSONArray(jsonString);
System.out.println("\n\njsonArray: " + jsonArray);
}
catch (JSONException e)
{
e.printStackTrace();
}*/
try
{
JSONArray jsonArray = new JSONArray(jsonString);
int count = jsonArray.length(); // get totalCount of all jsonObjects
for(int i=0 ; i< count; i++)
{ // iterate through jsonArray
JSONObject jsonObject = jsonArray.getJSONObject(i); // get jsonObject # i position
System.out.println("jsonObject " + i + ": " + jsonObject);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
public static String callURL(String myURL)
{
//System.out.println("Requested URL:" + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try
{
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null)
{
urlConn.setReadTimeout(60 * 1000);
}
if (urlConn != null && urlConn.getInputStream() != null)
{
in = new InputStreamReader(urlConn.getInputStream(),
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null)
{
int cp;
while ((cp = bufferedReader.read()) != -1)
{
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
}
catch (Exception e)
{
throw new RuntimeException("Exception while calling URL:"+ myURL, e);
}
return sb.toString();
}
Cheers
I had read the values from file but you can read from URL, the extracting process code is present inside extractJson() method.
public static void main(String [] args)
{
try
{
FileInputStream fis=new FileInputStream("testjson.json");
int b=0;
String val="";
while((b=fis.read())!=-1)
{
val=val+(char)b;
}
extractJson(val);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void extractJson(String json)
{
try
{
JSONObject jobject=new JSONObject(json);
System.out.println("Json object Length: "+jobject.length());
System.out.println("Status: "+jobject.getString("status"));
JSONArray jarray=new JSONArray(jobject.getString("records"));
System.out.println("Json array Length: "+jarray.length());
for(int j=0;j<jarray.length();j++)
{
JSONObject tempObject=jarray.getJSONObject(j);
System.out.println("Timestamp: "+tempObject.getString("timestamp"));
System.out.println("Device Id: "+tempObject.getString("deviceId"));
System.out.println("Temperature: "+tempObject.getString("temperature"));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
You could use ArrayList to store the values which will be available inside for loop. From your question you need to pass jsonString this variable to the extractJson() method. Use org.json jar file to process json. If you could alter this for gson then it'll be good for your requirement.
here's how to do it via Google-Gson
class MyRecord
{
private long timestamp;
private String deviceId;
private Integer temperature;
//Getters & setters
}
public static void main(String... args){
String myJsonString=callUrl("http://mydomain.com/x.json");
JsonParser jp = new JsonParser();
JsonElement ele = jp.parse(myJsonString);
Gson gg = new Gson();
Type type = new TypeToken<List<MyRecord>>() {
}.getType();
List<MyRecord> lst= gg.fromJson(ele.getAsJsonObject().get("records"), type);
//Now the json is parsed in a List of MyRecord, do whatever you want to with it
}
An "high-level" Gson parsing answer:
package stackoverflow.questions.q19252374;
import java.util.List;
import com.google.gson.Gson;
public class Q19252374 {
class Record {
Long timestamp;
String deviceId;
Long temperature;
}
class Container {
List<Record> records;
}
public static void main(String[] args) {
String json = "{ \"status\": \"success\", \"records\": [{\"timestamp\": 1381222871868,\"deviceId\": \"288\",\"temperature\": 17 },{\"timestamp\": 1381222901868,\"deviceId\": \"288\",\"temperature\": 17 },{\"timestamp\": 1381222931868,\"deviceId\": \"288\",\"temperature\": 17 } ]} ";
Gson g = new Gson();
Container c = g.fromJson(json, Container.class);
for (Record r : c.records)
System.out.println(r.timestamp);
}
}
Of course this is the result:
1381222871868
1381222901868
1381222931868

Categories

Resources