0

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();
    }
}

}

Rishad Appat
  • 1,786
  • 1
  • 15
  • 30
  • Try to minimize the code. It will be more clear and easy to understand. This way it is more likely to get the correct answer. – Kiril Aleksandrov May 12 '15 at 11:39
  • I juz edited it.. please check it out... – Rishad Appat May 12 '15 at 11:46
  • 2
    Why are you doing it this way? Why not return from doInBackground and do the UI stuff in onPostExecute.... ? That's how it's done. – ElDuderino May 12 '15 at 11:48
  • But as u can see... there is two for loop which is comparing the json data with the data from the database... i have to make changes in the UI according to it... – Rishad Appat May 12 '15 at 11:52
  • The approach you are following is wrong. In specific situation, you also can do JSON parsing inside your onPostExecute() method as in most of the case it will not take more than few milliseconds and can be negligible. – Bhavesh Patadiya May 12 '15 at 12:04

2 Answers2

0
 ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
new GetJsondata().execute()
}else{
//show toast
}

Write the above code in the place where you are calling the asynctask.Remove it from the asynctask itself.

kgandroid
  • 5,507
  • 5
  • 39
  • 69
  • Thanks for your reply... But the problem is not there... It is above it which am trying to update the text of textviews... – Rishad Appat May 12 '15 at 11:52
0
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....

Rishad Appat
  • 1,786
  • 1
  • 15
  • 30
Angad Tiwari
  • 1,738
  • 1
  • 12
  • 23