[英]How to fetch JSON data from MySQL database using volley?
我正在嘗試從MySQL
數據庫獲取JSON
數據,但這給了我一個錯誤。 我正在使用本地計算機,並且已將端口配置為8080。因此,我看不到錯誤在哪里。
<?php
$username = "root";
$password = "";
$host = "localhost";
$db_name = "user_info";
$conn = mysqli_connect($host,$username,$password,$db_name);
$sql = "select * from users where name like 'Rashmi';";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)>0)
{
$row = mysqli_fetch_assoc($result);
echo json_encode(array("Name"=>$row["name"],"Email"=>$row["email"],"Mobile"=>$row["mobile"]));
}
?>
這是android代碼,可從數據庫中以JSON格式獲取數據。
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, json_url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
name.setText(response.getString("Name"));
email.setText(response.getString("Email"));
mobile.setText(response.getString("Mobile"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_LONG).show();
error.printStackTrace();
}
});
MySingleton.getmInstance(MainActivity.this).addToRequestque(jsonObjectRequest);
}
當您可以使用AsyncTask從MySQL數據庫檢索所有數據時,我將為您提供解決方案。 嘗試以下代碼: PHP腳本:首先將數據庫中的所有元素添加到數組中:
<?php
$con = mysqli_connect("localhost", "db_username", "password", "database_name");
$query = mysqli_query($con, "SELECT username, email FROM users");
if($query)
{
while($row = mysqli_fetch_array($query))
{
$arrRow["username"] = $row["username"];
$arrRow["email"] = $row["email"];
$users[] = $arrRow;
}
print(json_encode($users));
}
mysqli_close($con);
?>您應該在JSON Array中獲得所有結果。 接下來創建AsyncTask:
//Get Http Connection with async
private class RetrieveTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
String strUrl = "your url with php file";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
@Override
protected void onPostExecute(String result) {
ArrayList<HashMap<String, String>> location = null;
try {
JSONArray data = new JSONArray(result);
location = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("username", c.getString("username"));
map.put("email", c.getString("email")
location.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
if (location != null) {
for (int i = 0; i < location.size(); i++) {
username = location.get(i).get("username").toString();
email = location.get(i).get("email").toString();
//Here you can add these values to ArrayList and display it later
}
}
}
}
不要忘記在您的onCreate方法中或要開始下載數據的任何地方對其進行初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.