我正在使用achartengine饼图从我的数据库服务器获取值。我想在每个细分中显示学生的平均分数。但我在logcat中收到错误:
W/System.err: org.json.JSONException: Value [] at count of type org.json.JSONArray cannot be converted to double
这是我的java代码的一部分:
public class c_marks extends AppCompatActivity {
private GraphicalView mChart;
private String[] code;
double value1, value2, value3, value4, value5, value6;
ProgressDialog progressDialog;
JSONParser jsonParser = new JSONParser();
String COUNT_URL_1 = "http://fypesystem.com/marks_test1.php";
String COUNT_URL_2 = "http://fypesystem.com/marks_test2.php";
String COUNT_URL_3 = "http://fypesystem.com/marks_test3.php";
private static final String TAG_COUNT = "count";
JSONObject json;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_c_marks);
new Count().execute();
}
class Count extends AsyncTask<String,String ,String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... args) {
try {
json = jsonParser.getJSONFromUrl(COUNT_URL_1);
value1 = json.getDouble(TAG_COUNT);
json = jsonParser.getJSONFromUrl(COUNT_URL_2);
value2 = json.getDouble(TAG_COUNT);
json = jsonParser.getJSONFromUrl(COUNT_URL_3);
value3 = json.getDouble(TAG_COUNT);
}catch (JSONException e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String file_url) {
progressDialog.dismiss();
openChart();
}
}
问题可能是因为我的PHP编码,因为我认为有问题,但我不知道如何解决它。
marks_test3.php
require("config1.php");
$query="SELECT totalmarks, COUNT(*) FROM marks WHERE totalmarks <=30";
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if ($rows){
$response["success"]=1;
$response["message"]=" Available";
$response["count"]= array();
array_push($response["count"]);
echo json_encode($response);
}else {
$response["success"] = 0;
$response["message"] = "No Available!";
die(json_encode($response));
}
?>
真的很感激,如果你能告诉我这个问题。
答案 0 :(得分:0)
这不是访问JSON数据的正确方法 可能是您的数据是JSONArray格式,并且您直接将其分配给float,因此请使用以下方法
try(){
JSONArray jarray=new JSONArray(your_data_from_url);
for(int i =0; i<jarray. length();i++){
JSONObject jobject=jarray.getJSONObject(i);
value1 = jobject.getDouble(TAG_COUNT);
}
}catch(Exception e){
e.printStackTrace();
}
答案 1 :(得分:0)
count
是一个JSON数组,但您尝试引用它,就像它是一个浮点数一样。
您需要:
$response["count"] = count($rows);
在这种情况下,使用json.getInt()
而不是json.getDouble()
或
count
作为JSONArray
,然后检查其大小:json.getJSONArray("count").length()