我有一個問題來查看我從我的數據庫收到的日期。讓我解釋我在做什麼。我有一個數據庫,其中有一個名爲rate1的表,它由一個名爲value的單列構成,它包含雙數。我的意圖是採取這一列中的所有數據,做平均並將其返回到我的java代碼中。我想要在TextView中顯示平均值。我的問題是,我沒有看到TextView上的任何東西。任何人都可以告訴我我錯在哪裏,如果他能給我解決我的錯誤的辦法嗎?現在我添加代碼: 這是Average.java:將數據從數據庫中恢復到java
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Average extends AppCompatActivity {
private TextView textViewResult;
private ProgressDialog loading;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_average);
textViewResult = (TextView) findViewById(R.id.textViewResult);
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL.toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Average.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name="";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Name:\t"+name);
}
}
這是Config.java:
public class Config {
public static final String DATA_URL = "https://lbstudios.000webhostapp.com/Average.php";
public static final String KEY_NAME = "value";
public static final String JSON_ARRAY = "result";
}
這是Average.php:
<?php
$connect = mysqli_connect("********", "********", "********", "*******");
$response = mysqli_query($connect, 'SELECT AVG(value) AS average FROM rate1');
$result = array();
if ($response) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($response)) {
$result[] = $row;
}
/* free result set */
mysqli_free_result($result);
}
echo json_encode($result);
?>
你能告訴直到什麼時候你可以看到(記錄)正確的數據嗎?答案是否正確? JSONObject的?任何錯誤消息? – Jeff
** 1。** PHP的工作原理是什麼? ** 2。** URLConnection是否有效? ** 3。**解析是否工作。有什麼異常嗎? – AxelH
如何...您從配置中恢復「值」,但在SQL中將其命名爲「平均值」。但我不確定數組將被命名爲'result'。你可以返回一個簡單的Json對象,而不是一個數組,因爲'AVG()'將只返回一行 – AxelH