0

im trying to use the following code in asynce task cause i want to show asynce task to the user for some reasons.

but this asynce task not working at all...

    AsyncTask task = new AsyncTask() {
        @Override
        protected Object doInBackground(Object[] params) {



            String result = "";
            InputStream isr = null;
            try {


                HttpClient httpclient = new DefaultHttpClient();



                HttpPost httppost = new HttpPost("http://persiancoder.tk/appservice/service.php");
                //conn.setConnectTimeout(7000);
                //YOUR PHP SCRIPT ADDRESS
                Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
                HttpResponse response = httpclient.execute(httppost);

                HttpEntity entity = response.getEntity();
                isr = entity.getContent();
            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection " + e.toString());
            }
            //convert response to string
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "utf-8"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                isr.close();

                result = sb.toString();
            } catch (Exception e) {
                Log.e("log_tag", "Error converting result " + e.toString());
            }

            //parse json data
            try {
                Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
                String n = "";
                String a = "";
                String j = "";

                JSONArray jArray = new JSONArray(result);

                for (int i = 0; i < jArray.length(); i++) {

                    JSONObject json = jArray.getJSONObject(i);
                    if (i == 0) {
                        int j1 = json.getInt("id");
                        if (j1 == 1) {
                        } else if (j1 == 0) {
                            AlertDialog.Builder dlgAlert = new AlertDialog.Builder(Main.this);

                            dlgAlert.setMessage("برنامه توسط تيم از دسترس خارج شده! لطفا بعدا امتحان کنيد");
                            dlgAlert.setTitle("Server Out!");
                            dlgAlert.setCancelable(false);
                            dlgAlert.setNegativeButton("باشه", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    System.exit(0);
                                }
                            });


                            dlgAlert.show();


                        }

                    }


                }


            } catch (Exception e) {

                Log.e("log_tag", "Error Parsing Data " + e.toString());

                AlertDialog.Builder dlgAlert = new AlertDialog.Builder(Main.this);

                dlgAlert.setMessage("مشکلي نامعلوم پيش آمده!اينترنت خود را چک کنيد");
                dlgAlert.setTitle("Unknown Problem!");
                dlgAlert.setCancelable(false);
                dlgAlert.setNegativeButton("باشه", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        System.exit(0);

                    }
                });

            }



            return null;

        }


    };




    task.execute(/* optional params */);

i have tried ways but not working.

whats the problem?

  • 2
    Can you elaborate on "not working"? This can mean many things. One issue is `dlgAlert.show();`. You can't do this on a background thread. It would need to be done in `onPostExecute()` or elsewhere – codeMagic Aug 06 '15 at 19:11
  • activity runs but not showing warning or even the asynce task.. @codeMagic –  Ali Mohamadi Aug 06 '15 at 19:12
  • Have you set a breakpoint or log statement at the top of `doInBackground()` to see if the task runs at all? Are any of your logs in the `catch` blocks showing? Is it crashing? And see the update on my first comment – codeMagic Aug 06 '15 at 19:13
  • well i puted just a alert dialog in doInBackgound and got force close but when deleted dialog application worked. so the doInBack() works.... and can u tell me how to optimize following code ? edit it and make it correct... @codeMagic –  Ali Mohamadi Aug 06 '15 at 19:19
  • So you haven't actually posted the code that isn't working? Because the dialog is still there – codeMagic Aug 06 '15 at 19:20
  • As @codeMagic stated, you can't show an AlertDialog from a background thread (which is what you are trying to do when you call it from doInBackground). Either handle it in a background method like onPostExecute() or explicitly tell it to run on the main UI thread. – zgc7009 Aug 06 '15 at 19:21
  • no i deleted the whole codes in doInback() and just puted a simple alert dialog... @codeMagic –  Ali Mohamadi Aug 06 '15 at 19:21
  • @zgc7009 well how should i make a onpostexecute() and tell it to if the j1==0 (gotted 0 from do in back) alarm the user? –  Ali Mohamadi Aug 06 '15 at 19:23
  • Send the result to `onPostExecute()` and see [How to use AsyncTask](http://stackoverflow.com/questions/18898039/using-asynctask/18898105#18898105) – codeMagic Aug 06 '15 at 19:23
  • @-Override protected void onPostExecute(Void result) { super.onPostExecute(result); } so this code must added after do in back ? and can u give me a example of sending result to it? @codeMagic –  Ali Mohamadi Aug 06 '15 at 19:28
  • Sure, see this answer http://stackoverflow.com/questions/15260855/one-activity-two-views-how-and-where-do-i-inflate-the-second-view/15260998#15260998 – codeMagic Aug 06 '15 at 19:30
  • so in doInback i can say - int j =1; - and then i onpostexecute(); say - if j1==1 alert me... can i do it ??? @codeMagic –  Ali Mohamadi Aug 06 '15 at 19:33
  • Sure, as long as `onPostExecute()` has access to `j` – codeMagic Aug 06 '15 at 19:35
  • well i tried right now but onpostexe(); cant access to j ! what to do now? @codeMagic –  Ali Mohamadi Aug 06 '15 at 19:37
  • Declare it as a class level variable – codeMagic Aug 06 '15 at 20:44

1 Answers1

1

I can't post this kind of answer in a comment or I would, this is AsyncTask 101. In VERY simple terms:

doInBackground is designed to perform background operations

onPostExecute is designed to utilize the background operation results on the main UI thread

onPreExecute is designed to handle any UI requirements prior to running in the background thread

onProgressUpdate is designed to perform quick updates to the UI based on the progress of doInBackground

So if you have an AsyncTask like yours, and you want to show a Toast based on the operations of the network request, do something like this

new NetworkTask().execute("http://persiancoder.tk/appservice/service.php");

Where your NetworkTask class looks like

public class NetworkTask extends AsyncTask<String, Void, String[]>{

    @Override
    public String[] doInBackground(String... urls){
         String url = urls[0];
         // Do the code that you already have BUT whenever you are building/showing your 
         // alert dialog, instead of doing that send a result back as an array with your 
         // title and message and show the alert dialog there

         // i.e.
         ...
         } else if (j1 == 0) 
             return new String[]{"Server Out!", "برنامه توسط تيم از دسترس خارج شده! لطفا بعدا امتحان کنيد"};
         ...

         return null;   // return null on success/no error
    }

    @Override
    public void onPostExecute(String[] results){
        if(results == null)
            return;

        else{
            AlertDialog.Builder dlgAlert = new AlertDialog.Builder(Main.this);

            dlgAlert.setTitle(results[0])
                .setMessage(results[1]);
                .setCancelable(false);
                .setNegativeButton("باشه", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        System.exit(0);
                    }
                });

            dlgAlert.show();
        }
    }
}

This, by all means, is not the best way of doing things, but it works. I would recommend looking into Volley for networking, but this should at least give you a basic idea of how AsyncTasks work.

zgc7009
  • 3,371
  • 5
  • 22
  • 34