簡體   English   中英

我如何從網頁中獲取價值並在主要課程中使用它? Android應用

[英]How can i get a value from webpage and use it on main class ? Android app

我正在嘗試閱讀網頁上的內容並將其存儲在稱為“ finalresult”的var中。 我閱讀了文本,使用了HttpURLConnection,並在AsyncTask的doInBacgorund中做到了。

我將向您展示我的代碼:

public class MainActivity extends AppCompatActivity {
public String finalresult = "";



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

class MyRemote extends AsyncTask<Void, Void, String> {

        URL url;
        HttpURLConnection connection = null;

        @Override
        protected String doInBackground(Void... params) {
            try
            {
                //Create connection
                url = new URL("My url bla bla");
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Language", "en-US");

                connection.setUseCaches(false);
                connection.setDoInput(true);
                connection.setDoOutput(true);

                //Send request
                DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
                wr.flush();
                wr.close();

                //Get Response
                InputStream is = connection.getInputStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(is));
                String line;
                StringBuffer response = new StringBuffer();
                while ((line = rd.readLine()) != null) {
                    response.append(line);
                    response.append('\r');
                }
                rd.close();

                finalresult = response.toString();



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

            } finally
            {
                if (connection != null) {
                    connection.disconnect();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {

            super.onPostExecute(result);

        }
    }

當我想在Main Activity Class中使用“ finalresult” var時,我不能,因為它是空的。 我如何獲得主要活動課程的成績?

Txh。 順便說一句,我是一個初學者。

請查看Android的AsyncTask文檔。 另外,我不確定您是否缺少括號或其他內容,但是請注意MyRemote類聲明不能位於onCreate()方法內。

finalResult變量為空的原因是,您從未真正使用過實現的MyRemote類。

所以你需要

new MyRemote().execute();

在您的onCreate()方法中。 另外,請記住,因為這個請求是異步這將是有意義的使用finalResult變量在onPostExecute()方法。

此外,用您的方式對URL進行硬編碼不是一個好主意。

url = new URL("My url bla bla");

相反,應將其作為參數傳遞給execute()方法。 同樣,請看一下文檔,它應該變得更加清晰。

暫無
暫無

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

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