为了账号安全,请及时绑定邮箱和手机立即绑定

将从远程 url 返回的字符串分配给变量

将从远程 url 返回的字符串分配给变量

呼唤远方 2022-07-14 09:23:31
我正在尝试将远程 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


查看完整回答
反对 回复 2022-07-14
?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

“onCreate”和“doInBackground”在不同的线程中运行。所以这段代码


 if(channel_uri.isEmpty()){

    Log.i("channel_text", "Empty");

}

在您收到 AsyncTask 中的响应之前执行。


这就是它被称为 AsyncTask 的原因。当您收到响应时,您需要在 doInBackground 中记录 channel_uri。


查看完整回答
反对 回复 2022-07-14
  • 2 回答
  • 0 关注
  • 177 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号