1

I am parsing JSON data from server in MainActivity but whenever I switch to another Activity and then again calling MainActivity... here comes the problem, it again hitting the JSON url, again fetching the data from JSON.

WHY? Whereas I already downloaded data from JSON

public class MainActivity extends Activity {

    ArrayList<Actors> actorsList;

    ActorAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        actorsList = new ArrayList<Actors>();
        new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");

        ListView listview = (ListView)findViewById(R.id.list);
        adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);

        listview.setAdapter(adapter);

        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                    long id) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), actorsList.get(position).getName(), Toast.LENGTH_LONG).show();              
            }
        });
    }


    class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setMessage("Loading, please wait");
            dialog.setTitle("Connecting server");
            dialog.show();
            dialog.setCancelable(false);
        }

        @Override
        protected Boolean doInBackground(String... urls) {
            try {

                //------------------>>
                HttpGet httppost = new HttpGet(urls[0]);
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httppost);

                // StatusLine stat = response.getStatusLine();
                int status = response.getStatusLine().getStatusCode();

                if (status == 200) {
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);


                    JSONObject jsono = new JSONObject(data);
                    JSONArray jarray = jsono.getJSONArray("actors");

                    for (int i = 0; i < jarray.length(); i++) {
                        JSONObject object = jarray.getJSONObject(i);

                        Actors actor = new Actors();

                        actor.setName(object.getString("name"));
                        actor.setDescription(object.getString("description"));
                        actor.setDob(object.getString("dob"));
                        actor.setCountry(object.getString("country"));
                        actor.setHeight(object.getString("height"));
                        actor.setSpouse(object.getString("spouse"));
                        actor.setChildren(object.getString("children"));
                        actor.setImage(object.getString("image"));

                        actorsList.add(actor);
                    }
                    return true;
                }

                //------------------>>

            } catch (ParseException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return false;
        }

        protected void onPostExecute(Boolean result) {
            dialog.cancel();
            adapter.notifyDataSetChanged();
            if(result == false)
                Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();

        }
    }   
}
Oreo
  • 2,586
  • 8
  • 38
  • 63

5 Answers5

2

Try using a static variable

 static boolean flag=false;
 static ArrayList<Actors> actorsList;

Then before calling the AsyncTask check if flag is true or false

if(!flag){
 actorsList = new ArrayList<Actors>(); //use this inside if statement
 new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
flag=true;
}

so only if the flag is false the async task is executed... Hope this helps.

Benedict
  • 458
  • 2
  • 13
  • Yes now its not hitting JSON api again, but even not showing existing data into ListView... what could be the reasons ? – Oreo Apr 07 '16 at 05:31
  • @Oreo Its Not hitting the api then How could you get the Data in your List view because you arraylist is populaing you asynch task .. You should use singleton Approach to save the data you got by calling your api for the firstime. – Adeel Turk Apr 07 '16 at 05:37
  • is there an exception being called? – Benedict Apr 07 '16 at 05:44
  • @Ben no but not getting existing data into ListView (data i got when I hit the json very first time) – Oreo Apr 07 '16 at 05:49
  • try making the actorList as static – Benedict Apr 07 '16 at 05:50
  • here is the tutorial which I am following and Oreo too: http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/ I just added a second activity and then coming back from that activity to MainActivity. Let's try at your end.. I am also trying to resolve this issue... – Sophie Apr 07 '16 at 06:23
  • Thank you so much Sophie.. for your work, I hope @Ben will also try at his end... – Oreo Apr 07 '16 at 06:25
  • device's back button "finish()" – Oreo Apr 07 '16 at 06:26
  • :) but I am trying with Intent, as you wrote you need solution for the both the cases – Sophie Apr 07 '16 at 06:27
  • @Ben did you find any solution ? – Oreo Apr 07 '16 at 07:14
  • Every time actorsList = new ArrayList(); is called the arrayList becomes null...so i used it inside the if statement.. – Benedict Apr 07 '16 at 07:28
  • getting : NPE, listview.setAdapter(adapter); please check sample at your end... http://pastebin.com/BvBSFXfK – Oreo Apr 07 '16 at 07:49
  • use static ArrayList actorsList; – Benedict Apr 07 '16 at 08:08
  • @Ben still facing same issue when I am coming back from Activity C to Activity A... – Oreo Apr 21 '16 at 06:49
1

According to your comment "I am calling MainActivity from SecondActivity using onBackPressed() and also calling MainActivity from ThirdActivity using Intent."

At SecondActivity onBackPressed() : simply calling finish() will not reload the MainActivity, hence it will not reload and call web service again.

Another option is to have a flag, saved in shared preferences.

Steps:

  1. Save a flag didCallService = true to shared preferences when the service is called first time. Save the json response also in the shared preference as a string.

  2. When you reach onCreate() on MainActivity from other 2 activities check if didCallService from user defaults is true. If so do not call the service again.

TharakaNirmana
  • 10,237
  • 8
  • 50
  • 69
0

Take one boolean variable and initialize it to true and also save it's state to sharedpreference. Now when MainActivity starts, check if this boolean is true or not using sharedpreference. If it is true, fetch JSON and turn boolean to false and also save state of boolean to sharedpreference. Now after this whenever MainActivity is called, because boolean is false, JSON will not be fetched.

Parsania Hardik
  • 4,593
  • 1
  • 33
  • 33
0

you can use "savedInstanceState" varibale for this purpose please check below code

if(savedInstanceState==null)
{
     new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
}

first time when you start activity its savedInstanceState is null next time t has value so add above condition in your code.

Ashish Pandya
  • 167
  • 10
  • is it helpful to you reply in comment? – Ashish Pandya Apr 07 '16 at 06:26
  • Tried this : http://pastebin.com/fCLZDXK4 and please let me know what I am missing ? – Oreo Apr 07 '16 at 08:06
  • YES getting NPE - listview.setAdapter(adapter); I am getting NPE when coming from SecondActivity to MainActivity – Oreo Apr 07 '16 at 08:17
  • please debug it I think many time json calling issue is solved for null pointer I think apater object has null value debug and check value for adapter and also check many time json calling issue solved or not – Ashish Pandya Apr 07 '16 at 08:22
0

Use singleTask

In your AndroidManifest.xml file add this property to MainActivity,

<activity ..
      android:launchMode= "singleTask" />

This will reload the instance of MainActivity and onCreate() won't be called, instead new intent will be available to use in onNewIntent() method.

MKJParekh
  • 34,073
  • 11
  • 87
  • 98
  • tried still hitting JSON api, when i am coming from SecondActivity to MainActivity – Oreo Apr 07 '16 at 07:15
  • I don't believe this, you have code to fetch in only onCreate() and still fetching with singleTask, MAGICAL.! – MKJParekh Apr 07 '16 at 07:17
  • actually what's happening, for the first showing progressdialog > fetching data > populating listview then I moved to second activity, now I tapped on back (what i saw) again showing progress dialog > fetching data > populating listview – Oreo Apr 07 '16 at 07:22
  • I am not using finish anywhere in MainActivity, calling SecondActivity like this: listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView> arg0, View arg1, int position, long id) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), actorsList.get(position).getName(), Toast.LENGTH_LONG).show(); Intent intent = new Intent(MainActivity.this, SecondActivity.class); startActivity(intent); } }); – Oreo Apr 07 '16 at 07:23
  • use [this answer](http://stackoverflow.com/a/19216471/903469) , put your code to execute task in null condition. – MKJParekh Apr 07 '16 at 07:43
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/108484/discussion-between-oreo-and-mkjparekh). – Oreo Apr 07 '16 at 07:50