简体   繁体   English

每当我更改屏幕方向时,AsyncTasc…doInBacground都会重复

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

Lately I am developing an application in android for a web site. 最近,我正在为网站开发android应用程序。 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. 现在,我正在使用AsyncTasc .... doInBackground ,以便在下载数据时在背景ans显示器中获取数据。

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. 但是我有两个问题:1.每次更改设备的方向时, doInBackground都会重新开始,并且应用程序崩溃。 ( I have put the orientation of the Activity into Portrait Mode but this is not the solution I want. (我已将“ Activity的方向设置为“ Portrait Mode但这不是我想要的解决方案。

  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: 下面是我通常使用的JSonParser.class

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. 为了避免重复下载,您可以做的是将下载的结果缓存在某个地方,例如在Singleton类中。.因此,下次运行AsyncTask时,它将检查是否已经有“缓存的”数据,如果是,它将立即返回,否则它将执行下载。

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. 通常,我们将此逻辑委托给另一个类,就像Singleton一样,不受活动生命周期的影响。因此它不会受到影响。

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. 这个想法是让AsyncTask在单例上调用一个方法,例如:singleton.loadData(),然后它将在内部执行此逻辑检查是否已缓存数据或是否需要下载数据。

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

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