简体   繁体   中英

AsyncTasc… doInBacground repeats every time I change orientation of the screen

Lately I am developing an application in android for a web site. For the application I have to get the data from the server. For now I am using AsyncTasc .... doInBackground , in order to get the data in background ans display when they are downloaded.

But I two problems with that: 1. every time I change the orientation of the device the doInBackground starts all over again and the application crashes. ( I have put the orientation of the Activity into Portrait Mode but this is not the solution I want.

  1. The data need to be downloaded all before I display them.

Can U please help me how can I improve this solution, or even to use another solution instead.

If its needed: I have used the code below:

private class GetNewsData extends
        AsyncTask<String, Void, ArrayList<DashBoardModel>> {

    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected ArrayList<DashBoardModel> doInBackground(String... URL) {

        String categories_url = URL[0]; // Creating JSON Parser instance
        JSONNumberParser jParser = new JSONNumberParser(); // getting JSON
                                                            // string from
        // URL
        JSONArray newsItems = jParser.getJSONFromUrl(categories_url);
        Log.e("lsbsfbsfdbsfd", newsItems.toString());
        try {
            for (int i = 0; i < newsItems.length(); i++) {

                JSONObject c = newsItems.getJSONObject(i);

                .....more code over here....

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        .... more code over here...
        return items;
    }

    @Override
    protected void onPostExecute(ArrayList<DashBoardModel> items) {
        customModelAdapter.notifyDataSetChanged();
    }
}

And below is the JSonParser.class that I usually use:

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    JSONArray jArr = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONArray getJSONFromUrl(String url) {

        Log.e("JSON Parser", "U futem tek Jason " );

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);


            HttpResponse httpResponse = httpClient.execute(httpPost);

            HttpEntity httpEntity = httpResponse.getEntity();

            is = httpEntity.getContent();           
            Log.e("JSON Parser", "vajti " );
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is,  "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON Parser", json );
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            JSONTokener jt = new JSONTokener(json);
            Object rootElement = jt.nextValue();
            if (rootElement instanceof JSONObject) {
               // You got an object from the jresponse
                jObj = new JSONObject(json);
            } else if (rootElement instanceof JSONArray) {
                 jArr = new JSONArray(json);
                 Log.e("JSON Parser", "erdhi" );
                 return jArr;
               // You got a JSON array
            }
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jArr;

    }
}

It's standard behavior on the Activity, your should leave it. What you can do to avoid double download is to cache the downloaded result somewhere, for instance in a Singleton class..so next time your AsyncTask runs it would check if there's already a 'cached' data, if so it would return immediately, else it would perform the download.

Usually we delegate this logic to another class, which is like a Singleton that is not influenced by the Activity lifecycle..so it wouldn't be affected.

The idea is to make the AsyncTask call a method on the singleton like: singleton.loadData() then it would internally do this logic of checking if there's already data cached or if it needs to download.

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