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

前端 未结 2 1919
爱一瞬间的悲伤
爱一瞬间的悲伤 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:17

    You are not allowed to update GUI elements from a non UI/Main Thread

    txtView.setText(jo.getString("text"));
    

    Handling Expensive Operations in the UI Thread

    Or use

    onPostExecute

    0 讨论(0)
  • 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<Void, String, Void> {
        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;
        }
    
    0 讨论(0)
提交回复
热议问题