1

I am trying to read some data from a server and change UI views according to data fetched. I have to do this in background. when I put same code in on-create(main thread) it works well. but when I pasted the code in some AsyncTask it said "unfortunately ...... stopped"

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){}
        }
      }

what is the solution?

chimia
  • 28
  • 4
  • show your logcat and json array – Pragnesh Ghoda シ Jun 12 '14 at 05:49
  • It's very difficult to debug a crash without a stack trace. See [Unfortunately MyApp has stopped. How can I solve this?](/q/23353173) for Android-specific advice, and [What is a stack trace, and how can I use it to debug my application errors?](/q/3988788) for advice on what to do once you have the stack trace. If you still need help, edit your question to include the **complete stack trace**, as well as **which line of your code** the stack trace points to. – Ryan M Mar 28 '23 at 00:33

4 Answers4

1

I think you are performing UI Operations in doInBackground. Don't do that. Only thread that have created UI,can updated the UI. otherwise it will give calledfromwrongthreadexception.

for ex: you are setting scaletype in doInBackground.

imageAnim.setScaleType(ScaleType.FIT_XY);

Perform UI related operations in onpreexecute or in onPostExecute.

Amrut
  • 2,655
  • 3
  • 24
  • 44
1

You have several UI thread operations happening in doInBackground. These are not allowed. You can't do

imageAnim.setScaleType(ScaleType.FIT_XY);

or even

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

in doInBackground();

Either move these lines to onPreExecute or onPostExecute which run on UIThread before and after doInBackground runs respectively. If it is inevitable that you must access UIThread while in doInBackground, use:

runOnUiThread(new Runnable() {

    @Override
    public void run() {
        //YOUR UI CODE HERE          
    }
});
Kartik_Koro
  • 1,277
  • 1
  • 11
  • 23
0

If you want to update a view from a thread you need to call the Main thread

    runOnUiThread(new Runnable() {

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

You are trying to update a ImageView in a thread which will give you CalledFromWrongThreadException

Never update a view in a Thread always call the Main Thread

Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63
0

1.)First thing is that there is too much declarations are in doInBackground move all that and declared it in protected void onPreExecute() method which was you not declared i your code yet. Like this type of your operations.

        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.) Declared only HTTP operation in doInBackground 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.) There is return type in doInBakground method but you pass the null value in onPostExecute method you must have to pass your json response in return value because you get all json sting from your post method params.

GovindRathod
  • 867
  • 1
  • 8
  • 22