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

flvtvl50  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(260)

尝试使用php将域服务器中的mysql数据显示到android应用程序,并将我的数据显示为toast消息。每当我运行应用程序时,我都会得到空的吐司。此外,我将使用列表视图来显示数据。代码中没有错误。下面是我的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);

?>
irtuqstp

irtuqstp1#

你的代码不起作用。首先,你不需要在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;
        }

note:httpclient is 在新的android版本中不再支持了,因此我在代码中修改了这个。
希望对你有帮助。

wfypjpf4

wfypjpf42#

首先,您必须在清单文件中添加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();
        }

相关问题