无法从Async类设置TextView中的文本

在我的电脑中,CountryInfoActivity.java我有一个Async Class可从以下网站检索JSON的网址:https : //pt.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal。然后,它将extract节点解析为String,以便可以在TextView中进行设置。问题是,每当我在文本视图中设置文本时,我的应用程序就会崩溃。JSON解析正确,因为它正在检索我想要的所有信息...


这些是我用来检索数据的类,在上一个中,我尝试将数据设置textoSobrePais到TextView中。顺便说一句,在我的onCreate方法中,我以此方式调用了该类。new DownloadTask().execute(url);


public class DownloadTask extends AsyncTask<String,Integer,Void>{

@Override

protected Void doInBackground(String... params) {

    String url = params[0];

    getJSONFromURL(url);

    return null;

}

}




public String getJSONFromURL(String url){

    String json_string = null;

    try{

        URL obj = new URL(url);

        HttpURLConnection http = (HttpURLConnection) obj.openConnection();

        http.setRequestMethod("GET");

        int response = http.getResponseCode();

        Log.i("response",Integer.toString(response));

        BufferedReader reader  = new BufferedReader(new InputStreamReader(http.getInputStream()));

        StringBuilder sb = new StringBuilder();

        String line = null;

        while ((line = reader.readLine())!= null){

            sb.append(line+"\n");

        }

        reader.close();


        json_string = sb.toString();

        Log.i("json_string",json_string);

    } catch (UnsupportedEncodingException e){

        e.printStackTrace();

    } catch (ClientProtocolException e){

        e.printStackTrace();

    } catch (IOException e){

        e.printStackTrace();

    }

    ParseJson(json_string);

    return null;



}



public void ParseJson (String json){


JSONObject obj = null;

try {

    obj = new JSONObject(json);

} catch (JSONException e) {

    e.printStackTrace();

}


这是崩溃时给我的错误:https : //pastebin.com/PJh5r36u

有人可以帮忙吗?


POPMUISE
浏览 121回答 2
2回答

猛跑小猪

您无法通过非UI线程更新UI组件。运行TextViewon UI线程的更新,如下所示:&nbsp;runOnUiThread(new Runnable() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void run() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; txtInfoPais.setText(textoSobrePais);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;});

天涯尽头无女友

我们无法从后台线程更新UI。您必须在主线程上设置文本像这样在主线程上运行runOnUiThread(new Runnable() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void run() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; txtInfo.setText(textoPais);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java