Java JsonObject使用方法放置问题
非常新,所以请容忍我Java JsonObject使用方法放置问题,java,android,json,class,Java,Android,Json,Class,非常新,所以请容忍我 方法BloodPressure()在MainActivity中调用,获取值并“放入”到jsonObject 方法getBloodPressure()将返回此jsonobject,并在另一个模块中调用。 getBloodPressure()中的jsonobject始终为空{} 我已经试过调试了。所以我可以看到json是准确创建的。但是当我在getBloodPressure中“return jsonObject”时,它只是重置并变成{}。 如何使用血压值调用jsonObject
方法
BloodPressure()
在MainActivity
中调用,获取值并“放入”到jsonObject
方法
getBloodPressure()
将返回此jsonobject,并在另一个模块中调用。getBloodPressure()
中的jsonobject始终为空{}我已经试过调试了。所以我可以看到json是准确创建的。但是当我在getBloodPressure中“return jsonObject”时,它只是重置并变成{}。
如何使用血压值调用jsonObject 主要活动
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
}
}
另一个模块:
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);
}
}
我看到了你的代码,发现你在
getBloodPressure()
之前没有调用BloodPressure()
方法
我认为您应该在getBloodPressure()之前调用BloodPressure()
方法
你的另一个模块代码是这样的
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);
}
}
更新:
我认为您不应该在getHealthData()
方法中创建HealthData
的新实例
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);
}
}
检查我的最新问题。我在main活动中称血压为()。我获取所有数据并“放入”jsonObject。但是当我调用getBloodPressure()时,它返回空{}请查看另一个模块。您创建了healthData的新实例,因此它现在是空的。您不应该在getHealthData()方法中添加新的HealthData()。我已经更新了答案。请看。