AsyncTask为任务提供延迟

时间:2015-08-10 13:27:48

标签: android android-asynctask

我的项目是将数据从数据库中获取到我项目中的listview。它获取数据但是当我关闭并运行应用程序多次时它会产生滞后(数据被隐藏但是当我滚动列表视图时它会显示出来)

我的代码是

    private class SendfeedbackJob extends AsyncTask<String, Void, String> {
    String page="";

    protected String doInBackground(String...params) {
        // do above Server call here
        BufferedReader in = null;
        try {
        HttpClient client = new DefaultHttpClient();
        HttpPost request = new HttpPost(
        "http://192.168.43.16/marche/category_display.php");    
        HttpResponse response = client.execute(request);
        in = new BufferedReader(
        new InputStreamReader(
        response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
        sb.append(line + NL);
        }
        in.close();
         page = sb.toString();



                     String [] s= page.split(System.getProperty("line.separator"));
                     for(int i=0;i<s.length;i++){
                         Cat_Name[i]=s[i];
                     }

        } catch (Exception e) {
        e.printStackTrace();
        } finally {
        if (in != null) {
        try {
        in.close();
        } catch (IOException e) {
        e.printStackTrace();
        }
        }
        }

        return page;

            }

    @Override
    protected void onPostExecute(String message) {
        //process message
        Log.d("MyAsyncTask", "Received result: " + message);
    }


}

和oncreate方法

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    SendfeedbackJob pro=new SendfeedbackJob();
    pro.execute();
 }

2 个答案:

答案 0 :(得分:0)

隐藏数据。因为,显然你不会等到doInBackground完成处理才能刷新适配器(Cats数组仍为空)。当您在几秒钟后向下滚动时,列表视图将向适配器询问底部单元格中的数据,并在列表视图之前向上滚动,询问顶部单元格并显示它们。

  

您必须设置适配器或调用notifyDataSetChanged   onPostExecute方法。

答案 1 :(得分:0)

  • 获取所有数据后,在UI线程中调用notifydatasetchanged方法
  • 在获取数据时显示进度条,以避免在流程耗费大量时间时出现一些糟糕的UI体验