2012年2月18日 星期六

[TQC+ Android] 2-6 資料庫讀取 Use SQLiteDatabase, Custom BaseAdapter





可顯示資料庫內的資料於頁面 , 進行勾選後顯示於表單標題上 , 這題的重點在DataBase的存取 , 還有為了要讓嵌在List RowView內的CheckBox能引發事件 , 我們還要額外去Custom Adapter , 這個做法是去 extends Adapter , 程式碼如下。


package COM.TQC.GDD02;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;


public class GDD02 extends Activity
{
 SQLiteDatabase dataBase;
 Cursor cursor;
 Button exitButton , okButton;
 ListView listview;
 boolean[] CB = new boolean[3];
 
 String DATABASENAME = "MyDB";
 String TABLENAME = "MyTB";
 String FIELD01_ID = "_id";
 String FIELD02_NOTE = "note";
 String FIELD03_CREATED = "created";
 
 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        dataBase =  this.openOrCreateDatabase(DATABASENAME, MODE_PRIVATE, null);
        
        try
        {
         cursor = dataBase.rawQuery("SELECT * FROM "+TABLENAME, null);
            
        }catch(SQLiteException SQLiteException)
        {
         //如果Table MyTB 不存在的話 , 新增Table , 新增資料
         String create = "create table if not exists "+TABLENAME+" ("+FIELD01_ID+" integer primary key autoincrement, "+FIELD02_NOTE+" varchar not null, "+FIELD03_CREATED+" INTEGER)";
            dataBase.execSQL(create);
                
            dataBase.execSQL("INSERT INTO "+TABLENAME+" ("+FIELD02_NOTE+","+FIELD03_CREATED+") values ('BOOK',10)");
            dataBase.execSQL("INSERT INTO "+TABLENAME+" ("+FIELD02_NOTE+","+FIELD03_CREATED+") values ('FOOD',10)");
            dataBase.execSQL("INSERT INTO "+TABLENAME+" ("+FIELD02_NOTE+","+FIELD03_CREATED+") values ('TOOL',10)");
            cursor = dataBase.rawQuery("SELECT * FROM "+TABLENAME, null);
            Log.d("Test", "SQLiteException");         
        }        
                  
        exitButton = (Button) this.findViewById(R.id.button2);
        exitButton.setOnClickListener(BOnClickListener);
        okButton = (Button) this.findViewById(R.id.button1);
        okButton.setOnClickListener(BOnClickListener);
        
        listview = (ListView) this.findViewById(R.id.listView1);
        myAdapter adapter = new myAdapter(cursor , CB);
        listview.setAdapter(adapter);       
    }
    
    public Button.OnClickListener BOnClickListener = new Button.OnClickListener()
    {
  @Override
  public void onClick(View v)
  {
   String temp="";
   int count=0;
   
      switch(v.getId())
      {
       case R.id.button1:
       for(int i=0;i<3;i++)
       {
        if(CB[i])
        {
         count++;
         cursor.moveToPosition(i);
         temp+=cursor.getString(1)+" ";
        }
       }
       if(count>0) GDD02.this.setTitle("{"+temp+"}");
       else GDD02.this.setTitle(R.string.app_name);
       break;
       
       case R.id.button2:
       finish();
       break;
      }
  }     
    };
    
    public class myAdapter extends BaseAdapter
    {        
     Cursor myAdapterCursor;       
     boolean[] myAdapterCB;     
     
     public myAdapter(Cursor c , boolean[] cb)
     {      
      myAdapterCB = cb;
      myAdapterCursor = c;
      myAdapterCursor.moveToFirst();
     }
         
        public View getView(final int position, View convertView, ViewGroup parent)
        {
            View rowview = convertView;
           
            if (rowview == null)
            {
                    LayoutInflater inflater = getLayoutInflater();
                    rowview = inflater.inflate(R.layout.list, parent, false);
                    //為了要把xml所描述的Layout轉變為View , 也就是我們要的rowview
                    //所以必須使用LayoutInflater來轉化 , 而要取得LayoutInflater的Instance方式還包括
                    //LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    //接著再使用inflate (int resource, ViewGroup root, boolean attachToRoot)
                    //傳回我們要的rowview
            }
            
            TextView notes = (TextView) rowview.findViewById(R.id.textView1);
            
            myAdapterCursor.moveToPosition(position);
            notes.setText(myAdapterCursor.getString(1));
            
            CheckBox checkBox = (CheckBox) rowview.findViewById(R.id.checkBox1);
            checkBox.setChecked(false);
            
             /*
         每個list rowview都有擺放一個CheckBox,為了當我們按下CheckBox的時候要做出
         事件反應 , 所以針對每個rowview上的CheckBox我們都將他設定 onClick(View arg0)的事件宣告
             */
            
            checkBox.setOnClickListener(new CheckBox.OnClickListener()
            {             
             @Override
    public void onClick(View arg0)
    {                           
              if(((CheckBox) arg0).isChecked()) myAdapterCB[position]= true;
     else myAdapterCB[position] = false;              
    }             
            });
            return rowview;
        }

  @Override
  public int getCount()
  {
   // TODO Auto-generated method stub   
   return myAdapterCursor.getCount();
  }

  @Override
  public Object getItem(int position) {
   // TODO Auto-generated method stub
    myAdapterCursor.moveToPosition(position);
    return myAdapterCursor.getString(1);
  }

  @Override
  public long getItemId(int position)
  {
   // TODO Auto-generated method stub
   myAdapterCursor.moveToPosition(position);
   return myAdapterCursor.getLong(0);
  }
     }

 @Override
 protected void onDestroy()
 {
  // TODO Auto-generated method stub
  
  if(dataBase.isOpen()) dataBase.close();
  
  super.onDestroy();
 }
    
}



再來是List RowView的 Layout檔

    
    




接著是main.xml檔



    
    
    










P.S. 題目中所要求的Variable和Method皆會保留 , 也會根據題目所要求的流程去實作 , 縱使題目要求繞遠路....



沒有留言:

張貼留言

Google Analytics