Force close when trying to parse JSON with AsyncTask in the background

前端 未结 2 1918
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-07 16:01

i\'m new to android development and i\'m playing around with json data. I managed to get the parsing to work. I want to show a ProgressDialog and i read that i need to use A

2条回答
  •  孤街浪徒
    2021-01-07 16:31

    Check the docs for AsyncTask. You can't directly manipulate the UI from within doInBackground. In order to make UI updates, you need to call publishProgress. You will also need to change the signature of your AsyncTask to pass a String. So something like this:

    public class BackgroundAsyncTask extends AsyncTask {
        TextView txtView = (TextView)findViewById(R.id.TextView01);
        ...
        protected void onProgressUpdate(String... message) {
            txtView.setText(message[0]);
        }
        ...
        @Override
        protected Void doInBackground(Void... params) {
             try {
                 URL json = new URL("http://www.corps-marchia.de/jsontest.php");
                 URLConnection tc = json.openConnection();
                 BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
    
                 String line;
                 while ((line = in.readLine()) != null) {
                     JSONArray ja = new JSONArray(line);
                     JSONObject jo = (JSONObject) ja.get(0);
                     publishProgress(jo.getString("text"));
                 }
             } catch (MalformedURLException e) {
                 e.printStackTrace();
             } catch (IOException e) {
                 e.printStackTrace();
             } catch (JSONException e) {
                 e.printStackTrace();
             }
    
        return null;
        }
    

提交回复
热议问题