简体   繁体   中英

Android activity life cycle with asynctask

I have been doing some research on activity life cycles and how they free usable space so my application can run smoother. Its just that I would like to use these methods for one of my activities because when my PDialog launches it takes quite some time for my data to load. I have been look at my code to see where I can place these method, so when my activity is executing my asynctask, That will be the only thing I want to be running at that point of time.my code below will clear things up.

    public class ListView extends ListActivity {    


        ArrayList<HashMap<String, String>> questionList;        

         final String TAG_RESULTS = "results";
         final String TAG_QUESTION_SUBJECT = "Subject";
         final String TAG_QUESTION_NUMANSWERS = "NumAnswers";
         final String TAG_QUESTION = "question";
         final String TAG_QUESTION_CONTENT = "Content";
         final String TAG_QUESTION_CHOSENANSWER = "ChosenAnswer";
         final String TAG_ANSWERS = "Answers";
         final String TAG_ANSWER = "Answer";    
         final String TAG_ANSWERS_CONTENT = "content";      
         final String TAG_QUERY = "query";

                JSONArray question = null;          
                android.widget.ListView lv;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState); 
            //setContentView(R.layout.listview);        

        questionList = new ArrayList<HashMap<String, String>>(); 


        new LoadAllData().execute();

            }


        @Override   
        protected void onListItemClick(android.widget.ListView l, View v, int pos, long id) {
             super.onListItemClick(l, v, pos, id);  

              HashMap<String, String> item = questionList.get(pos);

              Intent i = new Intent(ListView.this, SingleListItem.class);
              i.putExtra(TAG_QUESTION_SUBJECT, item.get(TAG_QUESTION_SUBJECT));
              i.putExtra(TAG_QUESTION_CONTENT, item.get(TAG_QUESTION_CONTENT));
              i.putExtra(TAG_QUESTION_CHOSENANSWER, item.get(TAG_QUESTION_CHOSENANSWER));
              startActivity(i);

                }     

        class LoadAllData extends AsyncTask<String, String, String> {


            private Dialog pDialog;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                ProgressDialog pDialog; 
                pDialog = new ProgressDialog(ListView.this);
                pDialog.setMessage("Loading Data. Please wait...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(false);
                pDialog.show();
            }

            protected String doInBackground(String... args) {

                try {
                    Intent in = getIntent();
                    String searchTerm = in.getStringExtra("TAG_SEARCH");
                    String query = URLEncoder.encode(searchTerm, "utf-8");
                    String URL = "http://example.com";
                    JSONParsser jParser = new JSONParsser();
                    JSONObject json = jParser.readJSONFeed(URL);
                    try {

                        JSONArray questions = json.getJSONObject("all").getJSONArray("questions");

                        for(int i = 0; i < questions.length(); i++) {
                            JSONObject question = questions.getJSONObject(i);


                        String Subject = question.getString(TAG_QUESTION_SUBJECT);
                        String NumAnswers = question.getString(TAG_QUESTION_NUMANSWERS);
                        String ChosenAnswer = question.getString(TAG_QUESTION_CHOSENANSWER);
                        String Content = question.getString(TAG_QUESTION_CONTENT);

                        //JSONArray Answers = question.getJSONObject(TAG_ANSWERS).getJSONArray(TAG_ANSWER);


                        //JSONObject Answer = Answers.getJSONObject(0);

                        //String Content = Answer.getString(TAG_ANSWERS_CONTENT);

                                   HashMap<String, String> map = new HashMap<String, String>();

                                   map.put(TAG_QUESTION_SUBJECT, Subject);
                                   map.put(TAG_QUESTION_NUMANSWERS, NumAnswers);
                                   map.put(TAG_QUESTION_CONTENT, Content);
                                   map.put(TAG_QUESTION_CHOSENANSWER, ChosenAnswer);

                                   questionList.add(map);


                        }


                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                    return TAG_QUESTION ;           

            }

            @Override
            protected void onPostExecute(String file_URL) {
                if (pDialog != null && pDialog.isShowing()) pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(getBaseContext(), questionList,
                            R.layout.listelements,
                            new String[] { TAG_QUESTION_SUBJECT, TAG_QUESTION_NUMANSWERS }, new int[] {
                            R.id.Subject, R.id.NumAnswers, });

                    setListAdapter(adapter); 


            }

        }

        @Override
        protected void onStop() {
            // TODO Auto-generated method stub
            super.onStop();
        }

    }

In my previous class I have already put onStop to free up some space. But I hope now you can see more of what I mean when I say that I just want to PDialog and my asynctask to be running at that point of time so that my PDialog doesn't slow down the process.

For me is not actually clear what is question about. For a reference two important points if some newbee comes here and read.

  1. it takes some time list to load because it is long operation. Purpose of AsyncTask is to keep UI not blocked . It's purpose is not to magicaly speed up things to infinity (btw even if it is light speed is a limit).
  2. onStop() in this code is useless, it does nothing. super.onStop() would be called even if you delete completely your overriden onStop method because base class ListActivity is extended from Activity which has this method and it will be called. You didn't add anything by just calling super.onStop()
  3. Just for records onPreExecuting and onPostExecute are executing on main (UI) thread.. doInBackground is running in separate thread but Android wrapped everything nice for you so these methods execute on appropriate threads one after another.
  4. Seems like you don't know why but your doInBackground method needed to return some string so you returned any that you had ( TAG_QUESTION ).. ;) than onPostExecute accepted that String as parameter but of course you didn't use it. String was required there because you declared AsyncTask with <String,String,String> not knowning what is that for.

Hopefully some material about AsyncTask class can help to someone who landed here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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