我正在嘗試將遠程 URL 中的字符串分配給變量。當我在運行遠程 URL 代碼后檢查該變量時,它是空的。首先我聲明了空字符串,然后從 URL 中獲取字符串并嘗試將其分配給變量。字符串被提取但未分配給變量。下面是代碼public class MainActivity extends Activity {static String channel_uri = "";@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new DownloadWebPageTask().execute(); if(channel_uri.isEmpty()){ Log.i("channel_text", "Empty"); }}private static class DownloadWebPageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { final OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("http://yeshuaatv.com/channel/streamingurl/adaptive.txt") .build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Headers responseHeaders = response.headers(); channel_uri = response.body().string(); return channel_uri; } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { //tvdata.setText(channel); // you will get data in url string super.onPostExecute(s); }}}
2 回答

www說
TA貢獻1775條經驗 獲得超8個贊
問題是該execute()方法在新線程中啟動任務并異步執行此操作。這意味著當 HTTP 請求發生時,您的代碼onCreate會繼續運行,并且您的if檢查會在請求完成之前進行。
要解決此問題,您必須等待請求完成并在那里執行您的代碼。為此,AsyncTask您可以覆蓋onPostExecute在任務完成后在 UI 線程上運行的內容。
您的代碼將如下所示:
@Override
protected void onPostExecute(String channel_uri) {
if(channel_uri.isEmpty()){
Log.i("channel_text", "Empty");
}
}
這也應該刪除對 channel_uri 的類成員的使用。因為那被傳遞到onPostExecute

泛舟湖上清波郎朗
TA貢獻1818條經驗 獲得超3個贊
“onCreate”和“doInBackground”在不同的線程中運行。所以這段代碼
if(channel_uri.isEmpty()){
Log.i("channel_text", "Empty");
}
在您收到 AsyncTask 中的響應之前執行。
這就是它被稱為 AsyncTask 的原因。當您收到響應時,您需要在 doInBackground 中記錄 channel_uri。
添加回答
舉報
0/150
提交
取消