简体   繁体   English

避免一次又一次地从JSON中获取数据

[英]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. 我正在从MainActivity中的服务器解析JSON数据但是每当我切换到另一个Activity然后再次调用MainActivity时......问题出现了,它再次点击JSON url,再次从JSON获取数据。

WHY? 为什么? Whereas I already downloaded data from JSON 而我已经从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();

        }
    }   
}

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 然后在调用AsyncTask之前检查flag是true还是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. 所以只有当标志为false时才会执行异步任务...希望这会有所帮助。

According to your comment " I am calling MainActivity from SecondActivity using onBackPressed() and also calling MainActivity from ThirdActivity using Intent. " 根据你的评论“ 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. 在SecondActivity onBackPressed():简单地调用finish()将不会重新加载MainActivity,因此它不会重新加载并再次调用Web服务。

Another option is to have a flag, saved in shared preferences . 另一种选择是在shared preferences保存一个标志。

Steps: 脚步:

  1. Save a flag didCallService = true to shared preferences when the service is called first time. 在第一次调用服务时,将标志didCallService = true保存到共享首选项。 Save the json response also in the s hared preference as a string. json响应也作为字符串保存在hared preference中。

  2. When you reach onCreate() on MainActivity from other 2 activities check if didCallService from user defaults is true. 当您从其他2个活动到达MainActivity上的onCreate() ,检查来自用户默认值的didCallService是否为true。 If so do not call the service again. 如果是这样,请不要再次呼叫该服务。

Take one boolean variable and initialize it to true and also save it's state to sharedpreference . 取一个boolean变量并将其初始化为true,并将其状态保存到sharedpreference Now when MainActivity starts, check if this boolean is true or not using sharedpreference . 现在,当MainActivity启动时,使用sharedpreference检查此boolean是否为true。 If it is true, fetch JSON and turn boolean to false and also save state of boolean to sharedpreference . 如果为true,则获取JSON并将boolean为false,并将boolean状态保存为sharedpreference Now after this whenever MainActivity is called, because boolean is false, JSON will not be fetched. 现在,每当调用MainActivity ,因为boolean为false,所以不会获取JSON

you can use "savedInstanceState" varibale for this purpose please check below code 您可以使用“savedInstanceState”varibale来检查以下代码

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. 第一次启动活动时,如果t有值,则savedInstanceState为null,因此在代码中添加上述条件。

Use singleTask 使用singleTask

In your AndroidManifest.xml file add this property to MainActivity , AndroidManifest.xml文件中,将此属性添加到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. 这将重新加载MainActivity的实例,并且不会调用onCreate() ,而是可以在onNewIntent()方法中使用新的intent。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM