我正在尝试使用php从mysql从我的域服务器到android应用程序中的数据获取数据

时间:2018-09-06 11:02:34

标签: php android mysql mysqli

尝试使用PHP将我的域服务器中的MySQL数据显示到android应用,并将我的数据显示为祝酒消息。每当我运行该应用程序时,我都会吐司。此外,我将使用列表视图来显示数据。代码中没有错误。下面是我的AsychTask的代码:

class Connection extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... params) {
            String result = "";
            String host = "http://prasaurus.com/conn.php";

            try {
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet();
                request.setURI(new URI(host));
                HttpResponse response = client.execute(request);
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuffer stringBuffer = new StringBuffer("");

                String line = "";

                while ((line = reader.readLine()) != null ){
                    stringBuffer.append(line);
                    break;
                }

                reader.close();
                result = stringBuffer.toString();

            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result){
            Toast.makeText(getApplicationContext(),result,Toast.LENGTH_SHORT).show();
        }

    }

这是服务器端的PHP代码:

<?php

$db_name = "prasauru_FAND_DB";
$mysql_username = "###########"; #database name on server end
$mysql_password = "###########"; #database password
$server_name = "prasaurus.com"; 

$conn = mysqli_connect($server_name, $mysql_username, $mysql_password, $db_name);

if(!$conn){
    die("Error in connection"  . mysqli_connect_error());
}

$response = array();

$query = "SELECT * FROM `under8_club_league` ORDER BY `points` DESC";
$result = mysqli_query($conn, $query);

if(mysqli_num_rows($result) > 0){
    while ($row = mysqli_fetch_assoc($result)){
        array_push($response , $row);
    }
}
else {
    $response['success'] = 0;
    $response['message'] = 'No data';
}

echo json_encode($response);    
mysqli_close($conn);

?>

2 个答案:

答案 0 :(得分:5)

首先,您必须在清单文件中添加Internet权限

<uses-permission android:name="android.permission.INTERNET" />

然后是Java代码

public static JSONObject getJSONObjectFromURL(String urlString) throws IOException, JSONException {
    HttpURLConnection urlConnection = null;
    URL url = new URL(urlString);
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setReadTimeout(10000 /* milliseconds */ );
    urlConnection.setConnectTimeout(15000 /* milliseconds */ );
    urlConnection.setDoOutput(true);
    urlConnection.connect();

    BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
    StringBuilder sb = new StringBuilder();

    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line + "\n");
    }
    br.close();

    String jsonString = sb.toString();
    System.out.println("JSON: " + jsonString);

    return new JSONObject(jsonString);
}

然后使用如下功能

try{
      JSONObject jsonObject = getJSONObjectFromURL(urlString);
 // here you can use Jsonobject or Jsonarray as per your requirement.
        } catch (IOException e) {
              e.printStackTrace();
        } catch (JSONException e) {
              e.printStackTrace();
        }

答案 1 :(得分:1)

您的代码不起作用。首先,您不需要在while循环中使用break。

第二,如果要在onPostExecute方法中获得结果,则应返回结果,而不是返回null。

有固定的代码:

 class Connection extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... params) {
            String result = "";
            String host = "http://prasaurus.com/conn.php";

            try {
                URL url = new URL(host);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuffer stringBuffer = new StringBuffer("");

                String line = "";

                while ((line = reader.readLine()) != null ){
                    stringBuffer.append(line);
                }

                reader.close();
                result = stringBuffer.toString();

            } catch (IOException e) {
                e.printStackTrace();
            }

            return result;
        }

注意:由于我在代码中对此进行了更改,因此新的Android版本不再支持HttpClient。

希望对您有帮助。