java - 在 android AsyncTask 中获取数据并更新 UI View

标签 java android multithreading android-asynctask

<分区>

我正在尝试从服务器读取一些数据并根据获取的数据更改 UI View 。 我必须在后台执行此操作。 当我在 on-create(main thread) 中放置相同的代码时,它运行良好。但是当我将代码粘贴到一些 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){}
        }
      }

解决方案是什么?

最佳答案

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

例如:您正在 doInBackground 中设置 scaletype。

imageAnim.setScaleType(ScaleType.FIT_XY);

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

关于java - 在 android AsyncTask 中获取数据并更新 UI View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24177275/

相关文章:

c++ - 在 Python 中扩展的 C++ 类中的段错误回调问题

java - 套接字数组

java - 使用列表填充 jTable

java - 有没有办法在测试中模拟连接超时?

java - 同步块(synchronized block)是否会触发数组的完整内存栅栏?

android - 适用于 Android 的 MSAL 无法执行 B2C 登录

android - 如何使用带有 header token android的截击上传图像

java - 在 JTable 中搜索 - 未获得正确的输出

android - Admob : Ad serving is limited - The number of ads you can show has been limited. 详情请访问政策中心

python - 适用于DataFrame操作/功能的Python多重处理