我正在尝试将远程 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
提交
取消
