删除某些项目后无法更新列表视图

时间:2016-04-23 08:14:10

标签: java android listview arraylist

我必须在优化正在运行的应用程序后更新列表....

   m_optimizeBtn.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
        launchProgressRing(OptimizationActivity.this);
            listAdaptor.notifyDataSetChanged();
        }
    });
}

在单独的线程中杀死正在运行的进程....

    public void launchProgressRing(Context ctx){
    final ProgressDialog opt_proDialog=new ProgressDialog(ctx);
    opt_proDialog.setTitle("Please wait...");
    opt_proDialog.setMessage("Optimizing power draining apps...");
    opt_proDialog.setIndeterminate(true);
    opt_proDialog.show();
    opt_proDialog.setCancelable(false);
    new Thread(new Runnable()
    {
        @Override
        public void run()
        {
            //TODO: optimize apps
            m_cPowerDrainingApps.killBgRunningProcesses(runningAppsList);
            try
            {
                Thread.sleep(1500);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    opt_proDialog.dismiss();
                }
            });
        }
    }).start();
}

listAdaptor.notifyDataSetChanged()不能正常工作,不知道为什么???

2 个答案:

答案 0 :(得分:0)

使用Handler及其postDelayed方法使列表的适配器无效,如下所示:

final Handler handler = new Handler()
handler.postDelayed( new Runnable() {

    @Override
    public void run() {
        adapter.notifyDataSetChanged();
        handler.postDelayed( this, 60 * 1000 );
    }
}, 60 * 1000 );

您必须只更新主(UI)线程中的UI。

答案 1 :(得分:0)

我建议使用AsyncTask来完成这项工作。 AsyncTask有两个很好的方法:

  • doInBackground:您可以将大部分后台任务放在那里
  • onPostExecute:你可以把后台任务完成工作时需要做的事情的逻辑放在哪里。

所以你的代码应该是这样的:

$array_holder = array();

foreach(MongoGetLevel1Cats as $parent){
  $parent['sub'] = array();

   foreach(MongoGetLevel2Cats as $child){
      $child['sub'] = array();

      foreach(MongoGetLevel3Cats as $child_child){
          $child_child['sub'] = array();

          ...
          ...

          array_push($child['sub'], $child_child);
        }

      array_push($parent['sub'], $child);
    }

  array_push($array_holder, $parent);
}

Return $array_holder;

然后运行:

public class BackgroundTask extends AsyncTask<Void,Void,Void>{

   private ListAdapter mAdapter;

   public BackgroundTask(ListAdapter adapter)
   {
      mAdapter = adapter
   }

   public Void doInBackground (Void... params)
   {
      //define m_cPowerDrainingApps somewhere
      m_cPowerDrainingApps.killBgRunningProcesses(runningAppsList);
      try
      {
           Thread.sleep(1500);
      } catch (InterruptedException e)
      {
           e.printStackTrace();
      }
   }

   public Void onPostExecute (Void... params)
   {
      //do your UI things
      mAdapter.notifyDataSetChanged();
   }
}
相关问题