2012-08-01 34 views
0

網格視圖在我的Android應用程序,我有一個顯示圖像作爲項目的網格。當我點擊一個按鈕的項目應該改變他們的立場。我通過遊標適配器填充這個網格。以前它工作正常,但需要一些時間來改變圖像的位置並再次刷新網格。爲此,我實現了一個進度對話框,以便用戶能夠理解正在發生的事情。處理程序不刷新android系統

這是我的代碼到目前爲止。

我的處理程序

public void handleMessage(Message msg) { 
switch (msg.what) { 
    case PROGRESS_DIALOG_HANDLER_ID: 
     progressDialog.dismiss(); //ProgressDialog 
     DBAdapter adapter = new DBAdapter(SplittedImageActivity.this); 
     adapter.open(); 
     Cursor cursor = adapter.getAllImages(); 
     adapter.close(); 
     startManagingCursor(cursor); 
     cursorAdapter.changeCursor(cursor); //My cursor adapter 
     gridView.setAdapter(cursorAdapter); 
     cursor.close(); 

我的onclick方法

progressDialog = ProgressDialog.show(SplittedImageActivity.this, "", "Please wait..."); 
new Thread(){ 
     public void run() { 
     Random random = new Random(); 
     DBAdapter adapter = new DBAdapter(getApplicationContext()); 
     adapter.open(); 
     int childs = gridView.getChildCount(), oldPosition, newPotision; 
     newPotision = childs-1; 
     for(int i=0 ; i<childs ; i++){ 
      oldPosition = random.nextInt(m_cGridView.getChildCount()); 
      adapter.updatePosition(oldPosition, newPotision); //updates the position of the images in database 
      newPotision = oldPosition; 
     } 
     adapter.close(); 
     handler.sendEmptyMessage(PROGRESS_DIALOG_HANDLER_ID); 
    }; 
}.start(); 

問題:

進度對話框顯示eprfectly,位置也都在數據庫中更改。但是gridview並不令人耳目一新。我的意思是在完成所有工作後,進度對話框消失,屏幕變爲空白。

請幫我哪裏做錯了嗎?

回答

0

我認爲問題是,你分配在處理一個新的適配器,但在主線程上不打電話來NotifyDataSetChanged(),這也許是爲什麼不更新的網格。

而且,爲什麼不使用AsyncTasks?

public class LoadAsyncTask extends AsyncTask<Void, Void, Boolean> { 
    Context context; 

    public LoadAsyncTask(Context context) { 
     this.context = context;   
    } 

    protected void onPreExecute() { 
    } 

    protected Boolean doInBackground(Void... v) { 
     DBAdapter adapter = new DBAdapter(context); 
     adapter.open(); 
     int childs = gridView.getChildCount(), oldPosition, newPotision; 
     newPotision = childs-1; 
     for(int i=0 ; i<childs ; i++){ 
        oldPosition = random.nextInt(m_cGridView.getChildCount()); 
        adapter.updatePosition(oldPosition, newPotision); //updates the position of the images in database 
        newPotision = oldPosition; 
     } 
     adapter.close(); 

     DBAdapter adapter = new DBAdapter(context); 
     adapter.open(); 
     Cursor cursor = adapter.getAllImages(); 
     adapter.close(); 
     startManagingCursor(cursor); 
     cursorAdapter.changeCursor(cursor); //My cursor adapter 
     gridView.setAdapter(cursorAdapter); 
     cursor.close();     
     return true; 
    } 

    protected void onPostExecute(Boolean success) { 
     if (success) { 
      //This will be executed on the main activity thread 
      cursorAdapter.notifyDataSetChanged(); 
     } else { 
      showError(); 
     } 
    } 

}