Search code examples
androidjsonandroid-asynctaskandroid-runonuithread

Error on ruOnUiThread inside asychtask


I am trying to parse some data from server and compare the data with the data in the database... Everything seems working fine... except I am getting only same value even the comparing data change... I'll explain it with the code...

In the below code, there is textviews tv3 and tv4... even the comparing data ie, shopid changed, it shows the value from the first array of the json...

when i tried to debug, i found the the run() inside the runOnUithread is calling after 2-3 loops... i donno whats happening here... Please somone help ,e to sort out the issue...

Edit: while debugging when i skip to each line it not showing any error... But when i try to skip to the breakpoints using F9 it shows the error...

Edit: 2: Since the code is litle bit long, i juz deleted som unwanted part...

private Bitmap downloadBitmap(String url) {
    HttpURLConnection urlConnection = null;
    try {
        URL uri = new URL(url);
        urlConnection = (HttpURLConnection) uri.openConnection();

        int statusCode = urlConnection.getResponseCode();
        if (statusCode != HttpStatus.SC_OK) {
            return null;
        }

        InputStream inputStream = urlConnection.getInputStream();
        if (inputStream != null) {
            bitmap = BitmapFactory.decodeStream(inputStream);
            return bitmap;
        }
    } catch (Exception e) {
        urlConnection.disconnect();
        Log.w("ImageDownloader", "Error downloading image from " + url);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    return null;
}

@Override
public void onResume() {
    mapView.onResume();
    super.onResume();
}

@Override
public void onDestroy() {
    super.onDestroy();
    mapView.onDestroy();
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    mapView.onLowMemory();
}

private class GetJsondata extends AsyncTask<Void, Void, String> {

    @Override
    protected void onPreExecute() {
        dialog = ProgressDialog.show(getActivity(), "", getActivity().getResources().getString(R.string.pleasewait), true);
    }

    @Override
    protected String doInBackground(Void... arg0) {
        // Creating service handler class instance
        ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        activeNetwork = conMgr.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnected()) {
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    jsonObj = new JSONObject(jsonStr);
                    ObjectOutput out = new ObjectOutputStream(new FileOutputStream
                            (new File(getActivity().getCacheDir(), "") + File.separator + "cacheFile.srl"));
                    out.writeObject(jsonObj.toString());
                    out.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }
        } else {
            try {
                ObjectInputStream in = new ObjectInputStream(new FileInputStream
                        (new File(getActivity().getCacheDir() + File.separator + "cacheFile.srl")));
                jsonObj = new JSONObject((String) in.readObject());
                in.close();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (OptionalDataException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (StreamCorruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (jsonObj != null) {
            try {
                ofrList = new ArrayList<ArrayList<String>>();
                // Getting JSON Array node
                jsonArray = jsonObj.getJSONArray("offers");

                shoplistarray = new ArrayList<ArrayList<String>>();


                // looping through All Contacts
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject c = jsonArray.getJSONObject(i);

                    url1 = c.getString("url");
                    if (userPrefs.getString("locale", null) == null || userPrefs.getString("locale", null).equals("en")) {
                        desc = c.getString("desc");
                    } else {
                        desc = c.getString("desc_ar");
                    }
                    expdate = c.getString("expdate");
                    ofrdate = c.getString("date");
                    shopsarray = c.getJSONArray("shops");
                    for (int n = 0; n < shopsarray.length(); n++) {
                        JSONObject jobj = shopsarray.getJSONObject(n);
                        shopid = jobj.getString("shopid");
                        if (shopid.equals(id) && tv3.getText().toString().equals("") ) {
                            downloadBitmap(url1);
                            finalI = i;
                                getActivity().runOnUiThread(new Runnable() {
                                    public void run() {
                                        if (activeNetwork != null && activeNetwork.isConnected()) {
                                            image.setImageBitmap(bitmap);
                                            saveFileInCache(String.valueOf(finalI), bitmap);
                                        } else {
                                            getFileOutOfCache(String.valueOf(finalI));
                                            image.setImageBitmap(bitmap);
                                        }
                                        tv3.setText(desc);
                                        tv4.setText(getActivity().getResources().getString(R.string.validtill) + expdate);
                                    }
                                });
                        }
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.urnotconnected), Toast.LENGTH_LONG).show();
                }
            });
        }

            return desc;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        dialog.dismiss();
    }
}


private Bitmap getFileOutOfCache(String fileName) {
    final String cachePath = getActivity().getCacheDir().getPath();
    File myDiskCacheFilePath = new File(cachePath);
    File myCachedFile = new File(myDiskCacheFilePath
            + File.separator + fileName);
    if (myCachedFile.exists()) {
        bitmap = BitmapFactory.decodeFile(myCachedFile.toString());
    } else {
        Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.cachedfilenotexist), Toast.LENGTH_LONG).show();

    }
    return bitmap;
}

public void saveFileInCache(String aFileName, Bitmap myImage) {
    final String cachePath = getActivity().getCacheDir().getPath();
    File myDiscCacheFilePath;
    myDiscCacheFilePath = new File(cachePath);
    File myDiscCacheFile = new File(myDiscCacheFilePath + File.separator + aFileName);
    try {
        FileOutputStream out = new FileOutputStream(myDiscCacheFile);
        myImage.compress(Bitmap.CompressFormat.JPEG, 80, out);
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.cachefailed), Toast.LENGTH_SHORT).show();

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

}


Solution

  • private Bitmap downloadBitmap(String url) {
    HttpURLConnection urlConnection = null;
    try {
        URL uri = new URL(url);
        urlConnection = (HttpURLConnection) uri.openConnection();
    
        int statusCode = urlConnection.getResponseCode();
        if (statusCode != HttpStatus.SC_OK) {
            return null;
        }
    
        InputStream inputStream = urlConnection.getInputStream();
        if (inputStream != null) {
            bitmap = BitmapFactory.decodeStream(inputStream);
            return bitmap;
        }
    } catch (Exception e) {
        urlConnection.disconnect();
        Log.w("ImageDownloader", "Error downloading image from " + url);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    return null;
    }
    
    @Override
    public void onResume() {
    mapView.onResume();
    super.onResume();
    }
    
    @Override
    public void onDestroy() {
    super.onDestroy();
    mapView.onDestroy();
    }
    
    @Override
    public void onLowMemory() {
    super.onLowMemory();
    mapView.onLowMemory();
    }
    
    private class GetJsondata extends AsyncTask<Void, Void, String> {
    
    boolean isIfCondition=false;
    @Override
    protected void onPreExecute() {
        dialog = ProgressDialog.show(getActivity(), "", getActivity().getResources().getString(R.string.pleasewait), true);
    }
    
    @Override
    protected String doInBackground(Void... arg0) {
        // Creating service handler class instance
        ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        activeNetwork = conMgr.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnected()) {
            ServiceHandler sh = new ServiceHandler();
    
            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
    
            Log.d("Response: ", "> " + jsonStr);
    
            if (jsonStr != null) {
                try {
                    jsonObj = new JSONObject(jsonStr);
                    ObjectOutput out = new ObjectOutputStream(new FileOutputStream
                            (new File(getActivity().getCacheDir(), "") + File.separator + "cacheFile.srl"));
                    out.writeObject(jsonObj.toString());
                    out.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }
        } else {
            try {
                ObjectInputStream in = new ObjectInputStream(new FileInputStream
                        (new File(getActivity().getCacheDir() + File.separator + "cacheFile.srl")));
                jsonObj = new JSONObject((String) in.readObject());
                in.close();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (OptionalDataException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (StreamCorruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (jsonObj != null) {
            try {
                ofrList = new ArrayList<ArrayList<String>>();
                // Getting JSON Array node
                jsonArray = jsonObj.getJSONArray("offers");
    
                shoplistarray = new ArrayList<ArrayList<String>>();
    
    
                // looping through All Contacts
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject c = jsonArray.getJSONObject(i);
    
                    url1 = c.getString("url");
                    if (userPrefs.getString("locale", null) == null || userPrefs.getString("locale", null).equals("en")) {
                        desc = c.getString("desc");
                    } else {
                        desc = c.getString("desc_ar");
                    }
                    expdate = c.getString("expdate");
                    ofrdate = c.getString("date");
                    shopsarray = c.getJSONArray("shops");
                    for (int n = 0; n < shopsarray.length(); n++) {
                        JSONObject jobj = shopsarray.getJSONObject(n);
                        shopid = jobj.getString("shopid");
                        if (shopid.equals(id) && tv3.getText().toString().equals("") ) {
                            downloadBitmap(url1);
                            finalI = i;
                            //no need to use runonuithread since post execute methods already runs on main ui thread ..rather set isIfCondition=true and do this job on postexecute method
                                isIfCondition=true;
                                desc1=desc;
                                expdate1=expdate;
                                /*getActivity().runOnUiThread(new Runnable() {
                                    public void run() {
                                        if (activeNetwork != null && activeNetwork.isConnected()) {
                                            image.setImageBitmap(bitmap);
                                            saveFileInCache(String.valueOf(finalI), bitmap);
                                        } else {
                                            getFileOutOfCache(String.valueOf(finalI));
                                            image.setImageBitmap(bitmap);
                                        }
                                        tv3.setText(desc);
                                        tv4.setText(getActivity().getResources().getString(R.string.validtill) + expdate);
                                    }
                                });*/
                        }
                    }
                }
    
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
          //no need to use runonuithread since post execute methods already runs on main ui thread
            /*getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.urnotconnected), Toast.LENGTH_LONG).show();
                }
            });*/
        }
    
            return desc;
    }
    
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        dialog.dismiss();
        if(isIfCondition=true)
        {
              if (activeNetwork != null && activeNetwork.isConnected()) {
                                            image.setImageBitmap(bitmap);
                                            saveFileInCache(String.valueOf(finalI), bitmap);
                                        } else {
                                            getFileOutOfCache(String.valueOf(finalI));
                                            image.setImageBitmap(bitmap);
                                        }
                                        tv3.setText(desc1);
                                        tv4.setText(getActivity().getResources().getString(R.string.validtill) + expdate1);
        }
    }
    }
    
    private Bitmap getFileOutOfCache(String fileName) {
    final String cachePath = getActivity().getCacheDir().getPath();
    File myDiskCacheFilePath = new File(cachePath);
    File myCachedFile = new File(myDiskCacheFilePath
            + File.separator + fileName);
    if (myCachedFile.exists()) {
        bitmap = BitmapFactory.decodeFile(myCachedFile.toString());
    } else {
        Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.cachedfilenotexist), Toast.LENGTH_LONG).show();
    
    }
    return bitmap;
    }
    
    public void saveFileInCache(String aFileName, Bitmap myImage) {
    final String cachePath = getActivity().getCacheDir().getPath();
    File myDiscCacheFilePath;
    myDiscCacheFilePath = new File(cachePath);
    File myDiscCacheFile = new File(myDiscCacheFilePath + File.separator + aFileName);
    try {
        FileOutputStream out = new FileOutputStream(myDiscCacheFile);
        myImage.compress(Bitmap.CompressFormat.JPEG, 80, out);
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.cachefailed), Toast.LENGTH_SHORT).show();
    
    } catch (IOException e) {
        e.printStackTrace();
    }
    }
    

    there is not need to use runonuithread or any other thread...because asynctask is already do this for you..doinbackground work run on bgthread and onpostexecute work on mainuithread..

    Just check the code...i haven't check..but it will work for sure....