Oreo
Oreo

Reputation: 2594

Avoid Fetching Data from JSON again and again

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

        }
    }   
}

Upvotes: 1

Views: 199

Answers (5)

Benedict
Benedict

Reputation: 458

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.

Upvotes: 2

MKJParekh
MKJParekh

Reputation: 34301

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.

Upvotes: 0

TharakaNirmana
TharakaNirmana

Reputation: 10353

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.

Upvotes: 1

Ashish Pandya
Ashish Pandya

Reputation: 167

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.

Upvotes: 0

Parsania Hardik
Parsania Hardik

Reputation: 4623

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.

Upvotes: 0

Related Questions