簡體   English   中英

使用簡單的可運行線程從android studio中的php獲取結果,而無需任何外部庫

[英]Get result from php in android studio using simple runnable threads without any external libraries

因此,我知道這似乎是一個重復的問題,但請耐心等待一下。 在Android Studio中,我計划使用簡單的可運行線程,而不是使用任何外部庫(即,沒有JSON,沒有Volley,沒有翻新,沒有任何外部)。 這些將使用存儲在本地主機上的PHP通過系統使用的WiFi的IP地址獲取數據。

我知道如何發送PHP更新(實際的更新代碼在PHP腳本中),它是這樣完成的:

Runnable runnableToUpdateDb = new Runnable() {
    @Override
    public void run() {
        Log.d("DEBUG","RUNNING RUNNABLE");
        try {
            URL url = new URL("http://192.168.43.242/myapi/php_name.php");
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.connect();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            String response = bufferedReader.readLine();
            Log.d("DEBUG", response);
            httpURLConnection.disconnect();
         }catch (Exception e){
             Log.d("DEBUG",e.toString());
         }
    }
};

然后只需按以下按鈕即可使用線程運行PHP:

Thread threadToUpdateDb = new Thread(runnableToUpdateDb);
threadToUpdateDb.start();

現在,問題在於設置一個TextView,它通過不同的PHP顯示來自數據庫的更新/新數據。

我在布局中為此TextView描述的ID是:

android:id="@+id/getdata"

我需要幫助在MainActivity中實現它。

PHP的輸出形式為:

<br>8<br>

這是使用普通Android對URL執行HTTP GET的方法。 在這種情況下,我選擇一個AsyncTask,以便它將在主線程之外運行請求:

private class TareaGetFromDB extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        String URL = params[0];
        String response = null;

        try {
            // Create an HTTP client
            HttpClient client = new DefaultHttpClient();
            HttpGet post = new HttpGet(URL);
            // Perform the request and check the status code
            HttpResponse response = client.execute(post);
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == 200) {
                // code 200 equals HTTP OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                try {
                    response = IOUtils.toString(content, "utf-8");

                } catch (Exception ex) {
                    // TODO handle exception
                }
            }
        } catch(Exception ex) {
            // TODO handle exception
        }
        return response;
    }
    @Override
    protected void onPostExecute(String response) {
        TextView myTextView = findViewById(R.id.getdata);
        myTextView.setText(response);
    }
}

此AsyncTask將字符串(URL)作為參數,並返回字符串(響應)。

因此,您需要這樣稱呼它:

new TareaGetFromDB().execute("http://url.to/get/data");

在將文本設置為TextView之前,您可能需要進行其他工作才能刪除替代的<br> ,或者可以從服務器響應中刪除它們

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM