0

1st asynchronous Task - fetch the image data from the server and showing it into image Viewer . (check out the code ) 2nd asynchronous- runs all the time. it will check the update from server (ex: the picture is updated or not ) if updated key is true (means update) then it will fetch the data again else it will not do anything . but In the background 2nd asynchronous task will be continuously running . i use this code but its not working . help me out


public class ImageActivity extends AppCompatActivity {
    private ImageView img;
    Bitmap decoded;
    private String pureFile;
    private String data;
    private JSONObject post_dict2;
    private boolean set;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_image);

        img = (ImageView) findViewById(R.id.img);


        post_dict2 = new JSONObject();

        try {
            post_dict2.put("device", "ABCDEFGHIJ");
        } catch (JSONException e) {
            e.printStackTrace();
        }
         if (post_dict2.length() > 0) {
            new jsonTask().execute(String.valueOf(post_dict2));

        }


    }


    public class jsonTask extends AsyncTask<String, String, String> {

        String ext;


        @Override
        protected String doInBackground(String... params) {
            String JsonResponse = null;
            String JsonDATA = params[0];
            HttpURLConnection httpURLConnection = null;
            BufferedReader bufferedReader = null;

            try {
                URL url = new URL("");
                httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setRequestProperty("Content-Type", "application/json");
                httpURLConnection.setRequestProperty("Accept", "application/json");
                httpURLConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");

                Writer writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"));
                writer.write(JsonDATA);

                writer.close();


                InputStream inputStream = httpURLConnection.getInputStream();
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();
                String line = " ";
                while ((line = bufferedReader.readLine()) != null) {


                    stringBuffer.append(line);

                }


                String file = stringBuffer.toString();

                JSONObject filejsonObject = new JSONObject(file);
                JSONObject metaObject = filejsonObject.getJSONObject("meta"); //meta data from JSON file
                data = filejsonObject.getString("data"); //this is the main data key from object
                ext = metaObject.getString("ext");


                return data;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }


            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            String run = "run";

            //s is the image source data
            if (s != null) {
                byte[] decodeString = Base64.decode(s, Base64.DEFAULT);
                try {
                    // Creating a new folder in to the device files storage i.e. media storage
                    File folder = new File(Environment.getExternalStorageDirectory() + "/ImgDownload");
                    boolean success = true;
                    if (!folder.exists()) {
                        success = folder.mkdir();
                    }
                    if (success) {
                        set = true;
                        FileOutputStream out = new FileOutputStream(folder + "/" + ".png");
                        out.write(decodeString);
                        out.flush();
                        out.close();
                        Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ImgDownload/" + ".png");
                        img.setImageURI(uri);

                        Thread.sleep(10000);
                        while(run.equals("run")){

                                    new updateFile().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, String.valueOf(post_dict2));

//
                        }



                    } else {

                        Toast.makeText(ImageActivity.this, "File Saving Failed", Toast.LENGTH_LONG).show();

                    }
                } catch (Exception e) {
                    Log.e("Error", e.toString());
                }
            } else {


                Toast.makeText(ImageActivity.this, "Failed To Download", Toast.LENGTH_LONG).show();
            }


        }


    }


        private class updateFile extends AsyncTask<String, String, String> {


            String ext;
            String media;

            @Override
            protected String doInBackground(String... params) {

                String JsonResponse = null;
                String JsonDATA = params[0];
               // String media = params[1];
                HttpURLConnection httpURLConnection = null;
                BufferedReader bufferedReader = null;

                try {
                    Thread.sleep(10000);
                    URL url = new URL("myurl");
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setRequestProperty("Content-Type", "application/json");
                    httpURLConnection.setRequestProperty("Accept", "application/json");
                    httpURLConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");

                    Writer writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"));
                    writer.write(JsonDATA);

                    writer.close();


                    InputStream inputStream = httpURLConnection.getInputStream();
                    bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuffer stringBuffer = new StringBuffer();
                    String line = " ";
                    while ((line = bufferedReader.readLine()) != null) {


                        stringBuffer.append(line);

                    }


                    String file = stringBuffer.toString();

                    JSONObject filejsonObject = new JSONObject(file);
                    JSONObject metaObject = filejsonObject.getJSONObject("data"); //meta data from JSON file
                    //   data = filejsonObject.getString("data"); //this is the main data key from object
                    ext = metaObject.getString("updated");
                    if (ext.equals("true")) {
                       Intent in = new Intent(ImageActivity.this,MainActivity.class);
                        startActivity(in);

                    }

                    else {

                        Thread.sleep( 1 ); //as the pic is not update and stop this async task 
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


                return null;
            }


        }

            }
  • 1
    Your code has a memory leak. If you rotate or home out of your activity and it gets destroyed, when you return it has to be recreated, but the AsyncTask that was running will not be stopped (from the original activity) and a new one will be spun after you return… forever. – Martin Marconcini May 11 '18 at 21:25
  • manifest screen orientation is landscape fixed . so it will not make any problem – Tasnuva Tavasum oshin May 11 '18 at 21:28
  • @Tasnuvaoshin Orientation is not the only configuration change that can cause an activity restart. – Kevin Krumwiede May 11 '18 at 21:32
  • so what is the other reason ? – Tasnuva Tavasum oshin May 11 '18 at 21:33
  • User pressing Home. You going to another activity. There is a reason why I told you that your code had a memory leak. It has it and it’s not following the correct practices. Simply address that issue by searching for “AsyncTask memory leak” and you will get plenty of material to read upon. E.g.: https://stackoverflow.com/questions/44309241/warning-this-asynctask-class-should-be-static-or-leaks-might-occur/44309450 – Martin Marconcini May 11 '18 at 21:46
  • @Tasnuvaoshin [The docs](https://developer.android.com/guide/topics/resources/runtime-changes) list screen orientation, keyboard availability, and when the user enables multi-window mode as examples, but there may be others now or in the future. – Kevin Krumwiede May 12 '18 at 02:53

1 Answers1

0

From the docs:

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting HONEYCOMB, tasks are back to being executed on a single thread to avoid common application errors caused by parallel execution.

An AsyncTask that runs continuously will hog the single threaded executor and prevent any other AsyncTask from running. If you really want two AsyncTasks to run at the same time, you must execute them with executeOnExecutor and provide your own multi threaded executor. (And even then, whether they actually run simultaneously is up to the thread scheduler.)

Kevin Krumwiede
  • 9,868
  • 4
  • 34
  • 82