【问题标题】:fetch data and update UI views in android AsyncTask在 android AsyncTask 中获取数据并更新 UI 视图
【发布时间】:2014-06-12 05:49:02
【问题描述】:

我正在尝试从服务器读取一些数据并根据获取的数据更改 UI 视图。 我必须在后台执行此操作。 当我在创建(主线程)中放入相同的代码时,它运行良好。但是当我将代码粘贴到一些 AsyncTask 中时,它说 “不幸的是......停止了”

private class DataFetch extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {


            //TextView tvv= (TextView) rootView.findViewById(R.id.textView);
            //tvv.setText("AAAAAA");

            //ViewFlipper flipper = (ViewFlipper) rootView.findViewById(R.id.viewFlipper1);
            //flipper.startFlipping();

            // Array of Image IDs to Show In ImageSwitcher 


            //ImageSwitcher imageSwitcher= (ImageSwitcher) rootView.findViewById(R.id.imageSwitcher1);



            //IMS.setImageResource(R.drawable.image1);

            //AnimationDrawable animation = new AnimationDrawable();
            //animation.addFrame(getResources().getDrawable(R.drawable.image1), 4000);
            //animation.addFrame(getResources().getDrawable(R.drawable.image2), 5000);
            //animation.addFrame(getResources().getDrawable(R.drawable.image3), 4000);
            //animation.setOneShot(false);
            //animation.setChangingConfigurations(BIND_ADJUST_WITH_ACTIVITY);

            //imageAnim.setImageDrawable(R.drawable.slider);
            imageAnim.setScaleType(ScaleType.FIT_XY);

            // start the animation!
            //animation.start();



            JSONObject jsonObject = new JSONObject();
            String result = "";
            String json = "";
            String json_base64 = "";

            WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            int lim= display.getWidth()/80;


            //make Json and decode to base64
                try {
                    Time today = new Time("UTC");
                    today.setToNow();
                    jsonObject.put("language", "fa");
                    jsonObject.put("start", 0);
                    jsonObject.put("limit", lim);
                    JSONObject filter = new JSONObject();
                    JSONObject flags = new JSONObject();
                    //flags.put("my_app", "no");
                    //flags.put("favorite", "all");
                    //filter.put("flags", flags);
                    filter.put("my_apps", false);
                    JSONArray JA=new JSONArray();
                    JA.put(1);
                    filter.put("any_os",JA);
                    jsonObject.put("time_stamp", today.format("%Y-%m-%dT%H:%M:%SZ"));
                    json = jsonObject.toString();
                    byte[] json_bytes = json.getBytes("UTF-8");
                    json_base64 = Base64.encodeToString(json_bytes, Base64.DEFAULT);

                } catch (Exception e) {

                }

                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("request", json_base64));
                InputStream is = null;

                // Send the HTTP POST request.
                try {
                    HttpParams params = new BasicHttpParams();
                    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);


                    HttpParams httpParameters = new BasicHttpParams();
                        // Set the timeout in milliseconds until a connection is established.
                        // The default value is zero, that means the timeout is not used. 
                    int timeoutConnection = 40000;
                    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                        // Set the default socket timeout (SO_TIMEOUT) 
                        // in milliseconds which is the timeout for waiting for data.
                    int timeoutSocket = 60000;
                    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
                    HttpConnectionParams.setTcpNoDelay(params, true);

                    httpParameters.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);


                    HttpClient httpclient = new DefaultHttpClient(httpParameters);


                    HttpPost httppost = new HttpPost(base_url+"/service/list/app/");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                } catch (Exception ex) {

                    Toast.makeText(getActivity(), "Your connection timedout", 10000).show();
                }

                // Read the data into a string.
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null)
                        sb.append(line + "\n");
                    is.close();
                    result = sb.toString();
                    next_res=result;

                } catch (Exception ex) {
                }



          return null;
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                JSONObject jsonObj = new JSONObject(result);
                // Getting JSON Array node
                JSONArray contacts = jsonObj.getJSONArray("result");                    

                spinner.setVisibility(View.GONE);
                for (int ind = 0; ind <Math.min(3,contacts.length()) /*contacts.length()*/; ind++) {
                    JSONObject c = contacts.getJSONObject(ind);
                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value

                    map.put(KEY_ID, c.getString("uid"));
                    ID_Extra = c.getInt("uid");
                    map.put(KEY_TITLE, c.getString("title"));
                    map.put(KEY_DESC, c.getString("os"));
                    map.put(KEY_COST, c.getString("price"));
                    map.put(KEY_THUMB_URL, c.getString("icon"));
                    map.put(KEY_apk, c.getString("os"));

                    Bitmap lazy= getBitmapFromURL(base_url+c.getString("icon"));
                    //Bitmap lazy= BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_launcher);
                    gridArray.add(new Item(lazy,c.getString("title")));

                    // adding HashList to ArrayList
                    appList.add(map);
                }


                customGridAdapter = new CustomGridViewAdapter(getActivity(), R.layout.row_grid, gridArray);
                gridView.setAdapter(customGridAdapter);

            }

            catch (Exception e) {           

                for (int ind = 0; ind < 3 /*contacts.length()*/; ind++) {

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(KEY_ID, Integer.toString(ind));
                    map.put(KEY_TITLE,"اپلیکیشن نمونه ی "+Integer.toString(ind));
                    map.put(KEY_DESC, "توضیحات نمونه"+Integer.toString(ind));
                    map.put(KEY_COST, "رایگان");
                    map.put(KEY_THUMB_URL,"");
                    map.put(KEY_apk,"");

                    //Bitmap lazy= getBitmapFromURL("http://vorujack.ir:8008"+c.getString("icon"));
                    //Bitmap lazy= BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.dummy_icon);
                    //gridArray.add(new Item(lazy,"اپلیکیشن نمونه ی "+Integer.toString(ind)));

                    // adding HashList to ArrayList
                    appList.add(map);
                }


                customGridAdapter = new CustomGridViewAdapter(getActivity(), R.layout.row_grid, gridArray);
                gridView.setAdapter(customGridAdapter);

            }


            try
            {
                customGridAdapter = new CustomGridViewAdapter(getActivity(), R.layout.row_grid, gridArray);
                gridView2.setAdapter(customGridAdapter);
            }catch(Exception E){}
        }
      }

解决办法是什么?

【问题讨论】:

  • 显示你的 logcat 和 json 数组

标签: java android multithreading android-asynctask


【解决方案1】:

我认为您正在 doInBackground 中执行 UI 操作。不要那样做。只有创建了 UI 的线程才能更新 UI。否则会给出calledfromwrongthread异常。

例如:您在 doInBackground 中设置 scaletype。

imageAnim.setScaleType(ScaleType.FIT_XY);

在 onpreexecute 或 onPostExecute 中执行 UI 相关操作。

【讨论】:

    【解决方案2】:

    doInBackground 中发生了多个 UI 线程操作。这些是不允许的。 你做不到

    imageAnim.setScaleType(ScaleType.FIT_XY);
    

    甚至

    Toast.makeText(getActivity(), "Your connection timedout", 10000).show();
    

    在doInBackground()中;

    将这些行移动到 onPreExecute 或 onPostExecute,它们分别在 doInBackground 运行之前和之后在 UIThread 上运行。如果在 doInBackground 中不可避免地必须访问 UIThread,请使用:

    runOnUiThread(new Runnable() {
    
        @Override
        public void run() {
            //YOUR UI CODE HERE          
        }
    });
    

    【讨论】:

      【解决方案3】:

      1.)第一件事是doInBackground 中的声明太多,请移动所有内容并在受保护的 void onPreExecute() 方法中声明它,这是您尚未在代码中声明的方法。喜欢你这种类型的操作。

              imageAnim.setScaleType(ScaleType.FIT_XY);           
      
              JSONObject jsonObject = new JSONObject();
              String result = "";
              String json = "";
              String json_base64 = "";
      
              WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
              Display display = wm.getDefaultDisplay();
              int lim= display.getWidth()/80;
      
      
          //make Json and decode to base64
              try {
                  Time today = new Time("UTC");
                  today.setToNow();
                  jsonObject.put("language", "fa");
                  jsonObject.put("start", 0);
                  jsonObject.put("limit", lim);
                  JSONObject filter = new JSONObject();
                  JSONObject flags = new JSONObject();
                  //flags.put("my_app", "no");
                  //flags.put("favorite", "all");
                  //filter.put("flags", flags);
                  filter.put("my_apps", false);
                  JSONArray JA=new JSONArray();
                  JA.put(1);
                  filter.put("any_os",JA);
                  jsonObject.put("time_stamp", today.format("%Y-%m-%dT%H:%M:%SZ"));
                  json = jsonObject.toString();
                  byte[] json_bytes = json.getBytes("UTF-8");
                  json_base64 = Base64.encodeToString(json_bytes, Base64.DEFAULT);
      
              } catch (Exception e) {
      
              }
      
              ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
              nameValuePairs.add(new BasicNameValuePair("request", json_base64));
              InputStream is = null;
      

      2.) 仅在doInBackground 中声明了HTTP 操作Like......

       // Send the HTTP POST request.
                      try {
                          HttpParams params = new BasicHttpParams();
                          params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
      
      
                          HttpParams httpParameters = new BasicHttpParams();
                              // Set the timeout in milliseconds until a connection is established.
                              // The default value is zero, that means the timeout is not used. 
                          int timeoutConnection = 40000;
                          HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                              // Set the default socket timeout (SO_TIMEOUT) 
                              // in milliseconds which is the timeout for waiting for data.
                          int timeoutSocket = 60000;
                          HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
                          HttpConnectionParams.setTcpNoDelay(params, true);
      
                          httpParameters.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
      
      
                          HttpClient httpclient = new DefaultHttpClient(httpParameters);
      
      
                          HttpPost httppost = new HttpPost(base_url+"/service/list/app/");
                          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                          HttpResponse response = httpclient.execute(httppost);
                          HttpEntity entity = response.getEntity();
                          is = entity.getContent();
                      } catch (Exception ex) {
      
                          Toast.makeText(getActivity(), "Your connection timedout", 10000).show();
                      }
      

      3.) doInBakground 方法中有返回类型,但您在 onPostExecute 方法中传递了null 值 您必须在返回值中传递您的 json 响应,因为您会从您的 post 方法参数中获取所有 json 字符串。

      【讨论】:

        【解决方案4】:

        如果你想从一个线程更新一个视图,你需要调用主线程

            runOnUiThread(new Runnable() {
        
            @Override
            public void run() {
                      imageAnim.setImageDrawable(R.drawable.slider);
                      imageAnim.setScaleType(ScaleType.FIT_XY);
            }
        });
        

        您正在尝试更新一个线程中的 ImageView,这将为您提供CalledFromWrongThreadException

        永远不要在线程中更新视图总是调用Main Thread

        【讨论】:

          猜你喜欢
          • 2011-03-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-22
          • 1970-01-01
          • 2019-05-23
          相关资源
          最近更新 更多