總網頁瀏覽量

關於我自己

我的相片
人生的必修課是接受無常,人生的選修課是放下執著。
顯示具有 ListView 標籤的文章。 顯示所有文章
顯示具有 ListView 標籤的文章。 顯示所有文章

2015年9月3日 星期四

【Android】 將ListView的分隔線取消

<ListView
            android:id="@+id/listview_gb_level"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="5dp"
            android:layout_marginLeft="5dp"
            android:layout_marginBottom="30dp"
            android:visibility="visible"
            android:divider="@null"    
            ></ListView>

2014年7月16日 星期三

[Android] 動態設定ListView的高度







  

//建立函數將dp轉換為像素
    public int Dp2Px(Context context, float dp) { 
        final float scale = context.getResources().getDisplayMetrics().density; 
        return (int) (dp * scale + 0.5f); 
    }
   

//建立函數動態設定ListView的高度
    public void setListViewHeightBasedOnChildren(ListView listView) {
        //取得ListView的Adapter

        ListAdapter listAdapter = listView.getAdapter();
        //固定每一行的高度
        int itemHeight = 50;
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            totalHeight += Dp2Px(getApplicationContext(),itemHeight)+listView.getDividerHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight;

        listView.setLayoutParams(params);
    }



使用時將ListView傳入
ListView lv_set_meal = (ListView) findViewById (R.id.lv_set_meal);

Adapter_ListView adapter = new Adapter_ListView(context, arraySetMeal_item);                
lv_set_meal.setAdapter(adapter);
setListViewHeightBasedOnChildren(lv_set_meal);// 必須放在setAdapter後面


2014年6月30日 星期一

取得ListView中Button的位置

某extends Activity的class以下列方式呼叫extends DialogFragment的class
InfoDialog dialog = new InfoDialog(context);
Bundle args = new Bundle();
args.putInt(InfoDialog.BUNDLE_KEY_PRIZE, -1);   
dialog.setArguments(args);
dialog.show();


InfoDialog extends DialogFragment內含ListView
Adapter adapter = new Adapter(context, deadlineList);
ListView lv = (ListView) dialog.findViewById(R.id.lv);   
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);//無法work


Adapter extends BaseAdapter其內ListView又含Button的click事件, 為取得click的Button所在位置, 將code改寫成:
    ArrayList<String> adapter_deadline;
    class ViewHolder {
        TextView deadline;
        Button exchange;
    }
    public View getView(int position, View convertView, ViewGroup parent){             
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = View.inflate(context, R.layout.adapter_listview_prize, null);
            holder = new ViewHolder();
            holder.deadline = (TextView)convertView.findViewById(R.id.summary);
            holder.exchange = (Button)convertView.findViewById(R.id.exchange);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.deadline.setText(.get(position).toString());

        OnClick listener = new OnClick(position);
        holder.exchange.setOnClickListener(listener);
        return convertView;
    }
    class OnClick implements OnClickListener {
        private int position;
        public OnClick(int position){
            this.position = position;
        }
        @Override
        public void onClick(View v) {
            Toast.makeText(context, "position "+position, Toast.LENGTH_SHORT).show();
            LayoutInflater factory = LayoutInflater.from(context);
            final View view = factory.inflate(R.layout.layout_questionnaire, null);
            AlertDialog.Builder mAB = new AlertDialog.Builder(context);

            mAB.setView(view);         
            alert = mAB.create();
            alert.show();
        }
    }

2013年7月14日 星期日

ListView 屬性 ( 分隔線顏色 & 手指按著時的背景色)

<ListView
            android:divider="@color/separate_line"
            android:dividerHeight="1dp"
            android:listSelector="@color/itemBackground">
</ListView>

android:divider="@color/separate_line" ←設定分隔線顏色, 可在color.xml中定義<color name="separate_line">#525d66</color>

android:dividerHeight="1dp" ←設定分隔線高度

android:listSelector="@color/itemBackground" ←設定touch到的Item其背景色, 可在color.xml中定義<color name="itemBackground">#3fa0a3</color>

2012年2月9日 星期四

自訂Adapter ~ 多欄位










ListViewActivity.java
package com.tstos.ListView_Adapter;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ListViewActivity extends Activity 
{
 TextView textview1;
 TextView textview2;
 TextView listview_title_column1;
 TextView listview_title_column2;
 TextView listview_title_column3;
 GridView gridview1;
 ListView listview1;
 ImageView imageview1;
 String[] android_version;
 String[] android_level;
 String[] android_code;
 Adapter_ListViewActivity adapter;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      
      textview1 = (TextView)findViewById(R.id.TextView1);
      textview2 = (TextView)findViewById(R.id.TextView2);
      listview_title_column1 = (TextView)findViewById(R.id.ListView_title_column1);
      listview_title_column2 = (TextView)findViewById(R.id.ListView_title_column2);
      listview_title_column3 = (TextView)findViewById(R.id.ListView_title_column3);
      listview1 = (ListView)findViewById(R.id.ListView1);
      imageview1 = (ImageView) findViewById(R.id.ImageView1);
      
      //載入default陣列
      android_version = getResources().getStringArray(R.array.lstview_array_column1);
      android_level = getResources().getStringArray(R.array.lstview_array_column2);
      android_code = getResources().getStringArray(R.array.lstview_array_column3);
      adapter = new Adapter_ListViewActivity(ListViewActivity.this, 
                 R.layout.simple_list_item_1_small, 
                 android_version, 
                 android_level, 
                 android_code);  
      
      listview1.setAdapter(adapter);
      //定義ListView的點擊行為
      listview1.setOnItemClickListener(new GridView.OnItemClickListener()
      {
        public void onItemClick(AdapterView parent, View v, int position, long arg3)
        {
         textview1.setText(android_version[position]);
         switch(position)
         {
         case 0://1.0          
          imageview1.setAlpha(0);//將圖片設為完全透明
          textview2.setText(getResources().getString(R.string.no_code_name));
          break;
         case 1://1.1
          imageview1.setAlpha(0);
          textview2.setText(getResources().getString(R.string.no_code_name));
          break;
         case 2://1.5
          imageview1.setAlpha(255);//將圖片設為不透明
          imageview1.setImageResource(R.drawable.cupcake);
          textview2.setText(getResources().getString(R.string.cupcake));
          break;
         case 3://1.6
          imageview1.setAlpha(255);
          imageview1.setImageResource(R.drawable.donut);
          textview2.setText(getResources().getString(R.string.donut));
          break;
         case 4://2.0
          imageview1.setAlpha(255);
          imageview1.setImageResource(R.drawable.eclair);
          textview2.setText(getResources().getString(R.string.eclair));
          break;
         case 5://2.0.1
          imageview1.setAlpha(255);
          imageview1.setImageResource(R.drawable.eclair);
          textview2.setText(getResources().getString(R.string.eclair));
          break;
         case 6://2.1
          imageview1.setAlpha(255);
          imageview1.setImageResource(R.drawable.eclair);
          textview2.setText(getResources().getString(R.string.eclair));
          break;
         case 7://2.2
          imageview1.setAlpha(255);
          imageview1.setImageResource(R.drawable.froyo);
          textview2.setText(getResources().getString(R.string.froyo));
          break;
         case 8://2.3
          imageview1.setAlpha(255);
          imageview1.setImageResource(R.drawable.gingerbread);
          textview2.setText(getResources().getString(R.string.gingerbread));
          break;
         case 9://2.3.3 - 2.3.4
          imageview1.setAlpha(255);
          imageview1.setImageResource(R.drawable.gingerbread);
          textview2.setText(getResources().getString(R.string.gingerbread));
          break;
         case 10://3.0
          imageview1.setAlpha(255);
          imageview1.setImageResource(R.drawable.honeycomb);
          textview2.setText(getResources().getString(R.string.honeycomb));
          break;
         case 11://3.1
          imageview1.setAlpha(255);
          imageview1.setImageResource(R.drawable.honeycomb);
          textview2.setText(getResources().getString(R.string.honeycomb));
          break;
         }
        }
      });
    }
}

2012年1月6日 星期五

SQLiteOpenHelper ~ 旅遊匯率隨時查(四)











進一步修改setOnItemClickListener的選單事件, 除了「刪除」選項, 再添加「修改內容」讓User更新已輸入過的資料.

首先將.setMessage(R.string.delete)的單一選項修改為.setItems(R.array.array_onitemclick, di_onclick), 使為多選項

Activity_ExchangeRate.java
lv_shopping.setOnItemClickListener(new OnItemClickListener()
     {
   public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) 
   {
    intItemSelected = arg2;
    value_shopping_icon = allarray_shopping_icon.get(arg2);
    value_shopping_item = allarray_shopping_item.get(arg2);
    value_shopping_nt = allarray_shopping_nt.get(arg2);

    new AlertDialog.Builder(context)
    .setTitle(R.string.str_dialog_shopping_title)
    //.setMessage(R.string.delete)
          .setItems(R.array.array_onitemclick, di_onclick)
          .setNegativeButton(R.string.str_button_cancel, new DialogInterface.OnClickListener()
          {
           public void onClick(DialogInterface dialog, int whichButton)
           {
             
           }
          })
          .show();
   }      
     });
    }

在此的di_onclick是一個DialogInterface.OnClickListener物件, 用來實作setOnItemClickListener的選單事件, 故在程式中加入以下片段:

Activity_ExchangeRate.java
DialogInterface.OnClickListener di_onclick = new DialogInterface.OnClickListener()
 {
  public void onClick(DialogInterface dialog, int which)
  {  
   String[] aryShop = getResources().getStringArray(R.array.array_onitemclick);
   switch(which)
   {
    case ID_MODIFY:
     dailog_id_modify();
     break;
    case ID_DELETE:
     dailog_id_delete();                      
     break;
   }
  }
 };

為「修改內容」這個選項新增function, 並於其內載入額外設計的layout, 使之佈局如右

並將User所修改的et_dialog_shopping_modify_item.getText().toString()及

et_dialog_shopping_modify_cash.getText().toString()值
存入資料庫欄位"fn_shopping_item"和
"fn_shopping_nt"











Activity_ExchangeRate.java
public void dailog_id_modify()
 {
  LayoutInflater factory = LayoutInflater.from(context);
  view_shopping_modify = factory.inflate(R.layout.layout_dialog_shopping_modify, null);
  et_dialog_shopping_modify_item = (EditText)view_shopping_modify.findViewById(R.id.et_dialog_shopping_modify_item);
  et_dialog_shopping_modify_cash = (EditText)view_shopping_modify.findViewById(R.id.et_dialog_shopping_modify_cash);
  et_dialog_shopping_modify_item.setText(value_shopping_item);
  et_dialog_shopping_modify_cash.setText(value_shopping_nt);
  new AlertDialog.Builder(context)
  .setView(view_shopping_modify)
  .setPositiveButton(R.string.str_button_save, new DialogInterface.OnClickListener()
        {
         public void onClick(DialogInterface dialog, int whichButton)
         {
          Cursor cursor_sqlite_table_listview_shopping = null;
          try
          { 
           cursor_sqlite_table_listview_shopping = dbHelper.select(tables[3], null, null, null, null, null, null);
           cursor_sqlite_table_listview_shopping.moveToFirst();  
           String[] updateFields = {"fn_shopping_item", "fn_shopping_nt"};
           String[] updateValues = { 
                   et_dialog_shopping_modify_item.getText().toString(), 
                   et_dialog_shopping_modify_cash.getText().toString()
                 };
           String where = "fn_shopping_icon=?";
           String[] whereValue = 
           {
            value_shopping_icon
           };
           System.out.println("et_dialog_shopping_modify_item = "+et_dialog_shopping_modify_item.getText().toString());
           System.out.println("et_dialog_shopping_modify_cash = "+et_dialog_shopping_modify_cash.getText().toString());
           System.out.println("value_shopping_icon = "+value_shopping_icon);
              dbHelper.update(tables[3], updateFields, updateValues, where, whereValue);
              update_listview_shopping();
          }
          catch(Exception e)
          {
           System.out.println("821 Exception : case ID_MODIFY");
          }
          finally
          {
           cursor_sqlite_table_listview_shopping.close();
          }
         }
        })
        .setNegativeButton(R.string.str_button_cancel, new DialogInterface.OnClickListener()
        {
         public void onClick(DialogInterface dialog, int whichButton)
         {
           
         }
        })
  .show();
 }

至於case ID_DELETE:
也記得刪除資料庫資料後在更新一次ListView
新增function:

Activity_ExchangeRate.java
public void dailog_id_delete()
 {
  new AlertDialog.Builder(context)
        .setMessage("刪除資料「 "+value_shopping_item+" 」?")
        .setPositiveButton(R.string.str_button_yes, new DialogInterface.OnClickListener()
        {
         public void onClick(DialogInterface dialog, int whichButton)
         {
             Cursor cursor_sqlite_table_listview_shopping = null;
             try
             {
              cursor_sqlite_table_listview_shopping = dbHelper.select(tables[3], null, null, null, null, null, null);
           String where = "fieldname_id=?";
           cursor_sqlite_table_listview_shopping.moveToPosition(intItemSelected);
           String[] whereValue = 
           {
            cursor_sqlite_table_listview_shopping.getString(0)
           };
        dbHelper.delete(tables[3], where, whereValue);
        update_listview_shopping();
             }
             catch(Exception e)
             {
              
             }
             finally
             {
              cursor_sqlite_table_listview_shopping.close();
             }
         }
        })
        .setNegativeButton(R.string.str_button_cancel, new DialogInterface.OnClickListener()
        {
         public void onClick(DialogInterface dialog, int whichButton)
         {
           
         }
        })
        .show();
 }

2012年1月5日 星期四

SQLiteOpenHelper ~ 旅遊匯率隨時查(三)

這篇新增加一個可以自行輸入購買商品資訊的功能,
讓外出旅遊除了可以隨時計算匯率,
更可以紀錄自己敗了哪些東西啦~







為此,
除了修改layout (layout_exchangerate.xml),
再新增Adapter_ListView_Shopping.java來自訂第2個ListView的樣式, 其載入layout_adapter_listview_shopping.xml 內含三個TextView,
code的架構如下










Adapter_ListView_Shopping.java
package com.tsots.ExchangeRate;

import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class Adapter_ListView_Shopping extends BaseAdapter
{
 private LayoutInflater mInflater;
 List adapter_allarray_shopping_icon;
 List adapter_allarray_shopping_item;
 List adapter_allarray_shopping_nt;
 TextView column_shopping_icon;
 TextView column_shopping_item;
 TextView column_shopping_nt;

 public Adapter_ListView_Shopping
 (
   Context context,
   int simple_list_item_single_choice, 
   List allarray_shopping_icon,
   List allarray_shopping_item, 
   List allarray_shopping_nt
 ) 
 {
  mInflater = LayoutInflater.from(context);
  adapter_allarray_shopping_icon = allarray_shopping_icon;
  adapter_allarray_shopping_item = allarray_shopping_item;
  adapter_allarray_shopping_nt = allarray_shopping_nt;
 }

 public int getCount()
 {
  return adapter_allarray_shopping_item.size();
 }

 public Object getItem(int position)
 {
  return adapter_allarray_shopping_item.size();
 }
  
 public long getItemId(int position)
 {
  return position;
 }
  
 public View getView(int position,View convertView,ViewGroup parent)
 {   
  convertView = mInflater.inflate(R.layout.layout_adapter_listview_shopping,null);
  column_shopping_icon = (TextView)convertView.findViewById(R.id.column_shopping_icon);
  column_shopping_item = (TextView)convertView.findViewById(R.id.column_shopping_item);
  column_shopping_nt = (TextView)convertView.findViewById(R.id.column_shopping_nt);
      column_shopping_icon.setText(adapter_allarray_shopping_icon.get(position).toString());
      column_shopping_item.setText(adapter_allarray_shopping_item.get(position).toString());
      column_shopping_nt.setText(adapter_allarray_shopping_nt.get(position).toString());
     return convertView;
 }
}

在主程式的部份,
新增bt_save button的onClick事件,
將user所輸入的et_item和et_money值存入資料庫並更新到ListView (lv_shopping)

Activity_ExchangeRate.java
bt_save.setOnClickListener(new OnClickListener()
        {
   public void onClick(View v) 
   {
    et_item.getText().toString();
    et_money.getText().toString();
    //存入資料庫
    save_sqlite_table_listview_shopping();
    //另外呼叫function做setAdapter
    update_listview_shopping();
   }
        });

/*
* 更新ListView畫面資料
*/

Activity_ExchangeRate.java
public void update_listview_shopping()
    {
     Log.i(Tag, "設定listview_shopping內容");
     allarray_shopping_icon = new ArrayList();
     allarray_shopping_item = new ArrayList();
     allarray_shopping_nt = new ArrayList();
     Cursor cursor_sqlite_table_listview_shopping = null;
     try
     {
      cursor_sqlite_table_listview_shopping = dbHelper.select(tables[3], null, null, null, null, null, null);
      cursor_sqlite_table_listview_shopping.moveToFirst();
      do
      {
       allarray_shopping_icon.add(cursor_sqlite_table_listview_shopping.getString(0));
       allarray_shopping_item.add(cursor_sqlite_table_listview_shopping.getString(2));
       allarray_shopping_nt.add(cursor_sqlite_table_listview_shopping.getString(3));
      }while(cursor_sqlite_table_listview_shopping.moveToNext());
     }
     catch(Exception e)
     {
      System.out.println("501 Exception : update_listview()");
     }
     finally
     {
      cursor_sqlite_table_listview_shopping.close();
     }

     /*新增購物列表*/
     adapter_listview_shopping = new Adapter_ListView_Shopping
     (
      context, 
      android.R.layout.simple_list_item_1, 
      allarray_shopping_icon, 
      allarray_shopping_item,
      allarray_shopping_nt
     );
     //將ListAdapter的可選(Focusable)選單選項打開
     lv_shopping.setItemsCanFocus(true);
     lv_shopping.setFocusable(true);
     //設定ListView選單選項設為每次只能單一選項
     lv_shopping.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
     lv_shopping.setAdapter(adapter_listview_shopping); 
    }


/*
* 新增tables[3]內的資料
* {"fieldname_id", "fn_shopping_icon", "fn_shopping_item", "fn_shopping_nt"}
*/

Activity_ExchangeRate.java
public void save_sqlite_table_listview_shopping()
    {
     Log.i(Tag, "儲存tables[3]資料ing...");
     Cursor cursor_sqlite_table_listview_shopping = null;
  try
  { 
   cursor_sqlite_table_listview_shopping = dbHelper.select(tables[3], null, null, null, null, null, null);
   cursor_sqlite_table_listview_shopping.moveToFirst();  
   String[] updateFields = {"fn_shopping_icon", "fn_shopping_item", "fn_shopping_nt"};
   String[] updateValues = {"1", et_item.getText().toString(), et_money.getText().toString()};
   dbHelper.insert(tables[3], updateFields, updateValues);
      //dbHelper.update(tables[3], updateFields, updateValues, null, null);      
  }
  catch(Exception e)
  {
   System.out.println("219 Exception : save_sqlite_table_listview_shopping()");
  }
  finally
  {
   cursor_sqlite_table_listview_shopping.close();
  }
    }


最後加入lv_shopping的onItemClick事件,
讓user可以將加入過的資料做刪除

Activity_ExchangeRate.java
lv_shopping.setOnItemClickListener(new OnItemClickListener()
     {
   public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) 
   {
    intItemSelected = arg2;
    new AlertDialog.Builder(context)
          .setMessage("delete item "+arg2+" ?")
          .setPositiveButton("yes",new DialogInterface.OnClickListener()
          {
           public void onClick(DialogInterface dialog, int whichButton)
           {
               Cursor cursor_sqlite_table_listview_shopping = null;
               try
               {
                cursor_sqlite_table_listview_shopping = dbHelper.select(tables[3], null, null, null, null, null, null);
                   String where = "fieldname_id=?";
                   String[] whereValue = 
                   {
                    allarray_shopping_icon.get(intItemSelected)
                   };
                dbHelper.delete(tables[3], where, whereValue);
                update_listview_shopping();
               }
               catch(Exception e)
               {
                
               }
               finally
               {
                cursor_sqlite_table_listview_shopping.close();
               }
           }
          })
          .setNegativeButton("no", new DialogInterface.OnClickListener()
          {
           public void onClick(DialogInterface dialog, int whichButton)
           {
             
           }
          })
          .show();
   }      
     }); 

為使lv_shopping的"fn_shopping_icon"在Activity顯示重新編號, 修改以下部份

public void update_listview_shopping()
    {
    ...
try
{
      cursor_sqlite_table_listview_shopping = dbHelper.select(tables[3], null, null, null, null, null, null);
      cursor_sqlite_table_listview_shopping.moveToFirst(); 
      int count =0;
      do
      { 
       count++;
       //allarray_shopping_icon.add(cursor_sqlite_table_listview_shopping.getString(0)); 
       allarray_shopping_icon.add(String.valueOf(count));
       allarray_shopping_item.add(cursor_sqlite_table_listview_shopping.getString(2));
              allarray_shopping_nt.add(cursor_sqlite_table_listview_shopping.getString(3));
      }while(cursor_sqlite_table_listview_shopping.moveToNext());
     }
     ...
    }

lv_shopping.setOnItemClickListener(new OnItemClickListener()
     {
   public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) 
   {
...
try
               {
                cursor_sqlite_table_listview_shopping = dbHelper.select(tables[3], null, null, null, null, null, null);
                   String where = "fieldname_id=?";
cursor_sqlite_table_listview_shopping.moveToPosition(intItemSelected);
String[] whereValue = 
                   {
                    //allarray_shopping_icon.get(intItemSelected) 
cursor_sqlite_table_listview_shopping.getString(0)
};
                dbHelper.delete(tables[3], where, whereValue);
                update_listview_shopping();
               }
});

2012年1月4日 星期三

onCreateOptionsMenu ~ 旅遊匯率隨時查(二) ~ startActivity; AlertDialog.Builder; Uri











Activity_ExchangeRate.java
package com.tsots.ExchangeRate;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Activity_ExchangeRate extends Activity 
{
 Context context = Activity_ExchangeRate.this;
 final int MENU_ABOUT = Menu.FIRST;
 final int MENU_UPDTAE_EXCHANGERATE = Menu.FIRST + 1;
 final int MENU_SEARCH_EXCHANGERATE = Menu.FIRST + 2;
 private View view_update_exchangerate;
 private EditText /*et_cash_nt,*/ et_cash_peso, et_cash_aud, et_cash_usd;
 String Tag = "Activity_ExchangeRate.java";
 TextView tv_updatedate;
 Spinner spinner_cash;
 ListView lv_exchange;
 EditText et_cash;
 Button bt_exchange;
 
 ArrayAdapter adapter_spinner_country;
 Adapter_ListView_Exchange adapter_listview_exchange;
 java.text.SimpleDateFormat sdf;
 
 String tables[] = {"table_value", "table_listData", "table_exchangerate"};
 String fieldNames[][] =
 {
  { "fieldname_date", "fieldname_country", "fieldname_cash"},
  { "fieldname_id", "fieldname_column_country", "fieldname_column_cash", "fieldname_column_unit"},
  { "fieldname_country1_exchangerate", 
    "fieldname_country2_exchangerate", 
    "fieldname_country3_exchangerate", 
    "fieldname_country4_exchangerate"}
 };
 String fieldTypes[][] =
 {
  { "text", "text", "text"},
  { "INTEGER PRIMARY KEY AUTOINCREMENT", "text", "text", "text"},
  { "text", "text", "text", "text"},
 };
 int version = 1;
 private SQLiteOpenHelper_ExchangeRate dbHelper = new SQLiteOpenHelper_ExchangeRate 
 (
   this,
   "SQLite_ExchangeRate.db",
   null,
   version,    
   tables,
   fieldNames,
   fieldTypes
 );
 
 String selected_country;
 int int_selected_country;
 String[] array_country;
 String[] array_cash;
 String[] array_unit;
 String[] array_deafault_exchangerate;
 List allarray_country = new ArrayList();
 List allarray_cash;
 List final_allarray_cash;
 List allarray_unit = new ArrayList();
 List all_id;
 DecimalFormat nf = new DecimalFormat("0.00000");
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_exchangerate);
        bt_exchange = (Button) findViewById (R.id.bt_exchange);
        et_cash = (EditText) findViewById (R.id.et_cash);
     array_country = getResources().getStringArray(R.array.array_country);
     array_cash = getResources().getStringArray(R.array.array_cash);
     array_unit = getResources().getStringArray(R.array.array_unit);
     array_deafault_exchangerate = getResources().getStringArray(R.array.array_cash);
        tv_updatedate = (TextView) findViewById (R.id.tv_updatedate);
        spinner_cash = (Spinner) findViewById (R.id.spinner_cash);
        lv_exchange = (ListView) findViewById (R.id.lv_exchange);
        
     sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

     default_sqlite_table_listdata();
     update_spinner();
     update_listview();
     
        bt_exchange.setOnClickListener(new OnClickListener()
        {
   public void onClick(View v) 
   {
    Log.i(Tag, "匯率換算ing...");
    //擷取EditText的值, 更新allarray_cash
    System.out.println("116 et_cash.getText().toString() = "+et_cash.getText().toString());
    System.out.println("117 allarray_cash = "+ allarray_cash); 
    if(!et_cash.getText().toString().equals(""))
    {
        save_sqlite_table_value();    
     save_sqlite_table_listData();
     //save_sqlite_table_exchangerate();
     Log.i(Tag, "更新畫面資料");
     update_spinner();
     update_listview();
    }
    else
    {
     Toast.makeText(context, "請輸入正確數字", Toast.LENGTH_SHORT).show();
     allarray_cash = new ArrayList();
     for (int i=0; i<4 ; i++)
     {
      allarray_cash.add("");
     }
     save_sqlite_table_listData();
     update_listview();
    }
   }         
        });
    }

    //AP關閉前執行
 @Override
 protected void onPause() 
 {
  save_sqlite_table_value();
        save_sqlite_table_listData();
  super.onPause();
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item)
 {
  super.onOptionsItemSelected(item);
  switch (item.getItemId())
     { 
   case MENU_ABOUT:
    startActivity(new Intent(this, Menu_About.class));
    break;
      case MENU_UPDTAE_EXCHANGERATE:       
       menu_update_exchangerate();
       break;
      case MENU_SEARCH_EXCHANGERATE:
       //檢查網路狀態
       if (checkInternet() == true)
          {
        //台灣銀行營業時間牌告匯率
        Uri uri = Uri.parse("http://rate.bot.com.tw/Pages/Static/UIP003.zh-TW.htm");
     Intent intent = new Intent(Intent.ACTION_VIEW, uri);
     startActivity(intent);
          }
    else
          {
           Toast.makeText(context, getResources().getString(R.string.str_checkInternet), Toast.LENGTH_SHORT).show();
          }
       break;
     }
     return true;
 }

 /*
  *  加入Menu選單
  */
 @Override
 public boolean onCreateOptionsMenu(Menu menu)
 {
     super.onCreateOptionsMenu(menu);
     menu.add(Menu.NONE, MENU_ABOUT, 0, R.string.str_menu_about)
      .setIcon(R.drawable.icon_menu_about);
     menu.add(Menu.NONE, MENU_UPDTAE_EXCHANGERATE, 0, R.string.str_menu_update_exchangerate)
      .setIcon(R.drawable.icon_menu_update_exchangerate);
     menu.add(Menu.NONE, MENU_SEARCH_EXCHANGERATE, 0, R.string.str_menu_search_exchangerate)
      .setIcon(R.drawable.icon_menu_search_exchangerate);
     return true;
 }
 
 /*
  *  更新tables[0]
  *    TextView更新日期   Spinner所選貨幣   EditText兌換金額
  *  {"fieldname_date", "fieldname_country", "fieldname_cash"}
  */
    public void save_sqlite_table_value()
    {
     Log.i(Tag, "儲存tables[0]資料ing...");
     Cursor cursor_sqlite_table_value = null;
  try
  { 
   cursor_sqlite_table_value = dbHelper.select(tables[0], null, null, null, null, null, null);
   cursor_sqlite_table_value.moveToFirst();  
   String[] updateFields = {"fieldname_date", "fieldname_country", "fieldname_cash"};
   String[] updateValues = {tv_updatedate.getText().toString(), String.valueOf(int_selected_country), et_cash.getText().toString()};
      dbHelper.update(tables[0], updateFields, updateValues, null, null);      
  }
  catch(Exception e)
  {
   System.out.println("219 Exception : save_sqlite_table_value()");
  }
  finally
  {
   cursor_sqlite_table_value.close();
  }
    }

 /*
  *  更新tables[1]
  *   換算後各國幣值List
  *  {"fieldname_column_cash"}
  */
    public void save_sqlite_table_listData()
    {
     Log.i(Tag, "儲存tables[1]資料ing...");
     Cursor cursor_sqlite_table_listdata = null;
  try
  {   
   cursor_sqlite_table_listdata = dbHelper.select(tables[1], null, null, null, null, null, null);
      cursor_sqlite_table_listdata.moveToFirst();
      //更新資料庫
   String[] updateFields = {"fieldname_column_cash"};
   String where = "fieldname_id=?"; 
   int position = 1;
   do
   {
    if(position <= cursor_sqlite_table_listdata.getCount())
    {
     String[] updateValues = {allarray_cash.get(position-1)};
     String[] whereValue = {String.valueOf(position)};
     dbHelper.update(tables[1], updateFields, updateValues, where, whereValue);
     position++;
    }
   }while(cursor_sqlite_table_listdata.moveToNext());
  }
  catch(Exception e)
  {
   System.out.println("257 Exception : save_sqlite_table_listData()");
  }
  finally
  {
   cursor_sqlite_table_listdata.close();
  }
    }    

 /*
  *  更新tables[2]
  *      台幣        菲律賓幣        澳幣        美金 
  *  { "fieldname_country1_exchangerate", "fieldname_country2_exchangerate", "fieldname_country3_exchangerate", "fieldname_country4_exchangerate"}
  */
    public void save_sqlite_table_exchangerate()
    {
     Log.i(Tag, "儲存tables[2]資料ing...");
     Cursor cursor_sqlite_table_exchangerate = null;
  try
  {   
   cursor_sqlite_table_exchangerate = dbHelper.select(tables[2], null, null, null, null, null, null);
      cursor_sqlite_table_exchangerate.moveToFirst();
      //更新資料庫
   String[] updateFields = { "fieldname_country1_exchangerate", "fieldname_country2_exchangerate", "fieldname_country3_exchangerate", "fieldname_country4_exchangerate"};
   String[] updateValues = {allarray_cash.get(0), allarray_cash.get(1), allarray_cash.get(2), allarray_cash.get(3)};
   dbHelper.update(tables[2], updateFields, updateValues, null, null);
  }
  catch(Exception e)
  {
   System.out.println("285 Exception : save_sqlite_table_exchangerate()");
  }
  finally
  {
   cursor_sqlite_table_exchangerate.close();
  }
    }
    
    /*
  *  更新Spinner畫面資料 
  */
    public void update_spinner()
    {
     Log.i(Tag, "設定Spinner選項");
     Cursor cursor_sqlite_table_value = null;
     //try
     //{
      cursor_sqlite_table_value = dbHelper.select(tables[0], null, null, null, null, null, null);
      cursor_sqlite_table_value.moveToFirst();
      tv_updatedate.setText(cursor_sqlite_table_value.getString(0));
      et_cash.setText(cursor_sqlite_table_value.getString(2));     
     //}
     //catch(Exception e)
     //{     
      adapter_spinner_country = new ArrayAdapter(this, android.R.layout.simple_spinner_item, array_country);
      adapter_spinner_country.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      spinner_cash.setAdapter(adapter_spinner_country);
      //從SQLite中擷取資料, 避免spinner item又跳回預設值0
      spinner_cash.setSelection(Integer.valueOf(cursor_sqlite_table_value.getString(1)));
      spinner_cash.setOnItemSelectedListener(new Spinner.OnItemSelectedListener()
      {      
       public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3)
       {
        int_selected_country = arg2;
        //依Spinner的選項更改, 置換ListView的幣值換算結果
        change_selected_country(int_selected_country);
        save_sqlite_table_value();
        save_sqlite_table_listData();
        //save_sqlite_table_exchangerate();
        update_listview();
       } 
    public void onNothingSelected(AdapterView arg0) 
    {
  
    }
      });   
     //}
     //finally
     //{
      cursor_sqlite_table_value.close();
     //}     
    }
    
    /*
  *  更新ListView畫面資料 
  */
    public void update_listview()
    {
     Log.i(Tag, "設定ListView內容");
     Cursor cursor_sqlite_table_listdata = null;
     try
     {
      //在此必須初使化allarray_cash, 否則ListView資料無法更新
      final_allarray_cash = new ArrayList();
      cursor_sqlite_table_listdata = dbHelper.select(tables[1], null, null, null, null, null, null);
      cursor_sqlite_table_listdata.moveToFirst();
      do
      {
       allarray_country.add(cursor_sqlite_table_listdata.getString(1));
       final_allarray_cash.add(cursor_sqlite_table_listdata.getString(2));
       allarray_unit.add(cursor_sqlite_table_listdata.getString(3));
      }while(cursor_sqlite_table_listdata.moveToNext());
     }
     catch(Exception e)
     {
      System.out.println("360 Exception : update_listview()");
     }
     finally
     {
      cursor_sqlite_table_listdata.close();
     }
     
     adapter_listview_exchange = new Adapter_ListView_Exchange
     (
      this, 
      android.R.layout.simple_list_item_1, 
      allarray_country, 
      final_allarray_cash,
      allarray_unit
     );
     lv_exchange.setAdapter(adapter_listview_exchange);    
    }
    
    /*
     *  先將SQLite欄位的預設值填好, 避免之後select時產生Exception
     */
 public void default_sqlite_table_listdata()
 {
  Log.i(Tag, "載入SQLite預設值");
  //insert tables[0]
  Cursor cursor_sqlite_table_value = null;
  try
  {
   cursor_sqlite_table_value = dbHelper.select(tables[0], null, null, null, null, null, null);
   cursor_sqlite_table_value.moveToFirst();
   String[] updateFields = {"fieldname_date", "fieldname_country", "fieldname_cash"};
   if(cursor_sqlite_table_value.getCount() == 0)
   {        
     String[] updateValues = {"2012-01-03", "0", "1"};
     dbHelper.insert(tables[0], updateFields, updateValues);
   }   
  }
     catch(Exception e)
     {
      System.out.println("399 Exception : default_sqlite_table_listdata()");
     }
     finally
     {
      cursor_sqlite_table_value.close();
     }
 
  //insert tables[1]
  Cursor cursor_sqlite_table_listdata = null;
  try
  {
   cursor_sqlite_table_listdata = dbHelper.select(tables[1], null, null, null, null, null, null);
   cursor_sqlite_table_listdata.moveToFirst();
   String[] updateFields = {"fieldname_column_country", "fieldname_column_cash", "fieldname_column_unit"};
   if(cursor_sqlite_table_listdata.getCount() == 0)
   {        
    for(int i=0 ; i();
   cursor_sqlite_table_exchangerate = dbHelper.select(tables[2], null, null, null, null, null, null);
   cursor_sqlite_table_exchangerate.moveToFirst();

      if(int_selected_country == 0)
      {
       allarray_cash.add(et_cash.getText().toString());
       allarray_cash.add(String.valueOf(nf.format(Double.valueOf(cursor_sqlite_table_exchangerate.getString(1))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(String.valueOf(nf.format(Double.valueOf(cursor_sqlite_table_exchangerate.getString(2))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(String.valueOf(nf.format(Double.valueOf(cursor_sqlite_table_exchangerate.getString(3))*Double.valueOf(et_cash.getText().toString()))));
       System.out.println("474 "+allarray_cash);       
      }
      else if(int_selected_country == 1)
      {
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(0))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(1))*Double.valueOf(et_cash.getText().toString()))));
       //allarray_cash.add(String.valueOf(nf.format(Double.valueOf(cursor_sqlite_table_exchangerate.getString(1))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(et_cash.getText().toString());
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(2))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(1))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(3))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(1))*Double.valueOf(et_cash.getText().toString()))));
       System.out.println("483 "+allarray_cash);
      }
      else if(int_selected_country == 2)
      {
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(0))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(2))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(1))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(2))*Double.valueOf(et_cash.getText().toString()))));
       //allarray_cash.add(String.valueOf(nf.format(Double.valueOf(cursor_sqlite_table_exchangerate.getString(2))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(et_cash.getText().toString());
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(3))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(2))*Double.valueOf(et_cash.getText().toString()))));
       System.out.println("491 "+allarray_cash);
      }
      else
      {
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(0))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(3))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(1))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(3))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(2))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(3))*Double.valueOf(et_cash.getText().toString()))));
       //allarray_cash.add(String.valueOf(nf.format(Double.valueOf(cursor_sqlite_table_exchangerate.getString(3))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(et_cash.getText().toString());
       System.out.println("500 "+allarray_cash);
      }
  }
  catch(Exception e)
  {
   System.out.println("506 Exception : change_selected_country(int int_selected_country)");
  }
  finally
  {
   cursor_sqlite_table_exchangerate.close();
  }
    }
    
    /*
     *  MENU_UPDTAE_EXCHANGERATE所要做的事情
     */
    public void menu_update_exchangerate()
    {
  LayoutInflater factory = LayoutInflater.from(context);
  view_update_exchangerate = factory.inflate(R.layout.layout_dialog_update_exchangerate, null);
  //et_cash_nt = (EditText)view_update_exchangerate.findViewById(R.id.et_cash_nt); 
  et_cash_peso = (EditText)view_update_exchangerate.findViewById(R.id.et_cash_peso);
  et_cash_aud = (EditText)view_update_exchangerate.findViewById(R.id.et_cash_aud);
  et_cash_usd = (EditText)view_update_exchangerate.findViewById(R.id.et_cash_us);
  Cursor cursor_sqlite_table_exchangerate = null;
  try
  {   
   cursor_sqlite_table_exchangerate = dbHelper.select(tables[2], null, null, null, null, null, null);
      cursor_sqlite_table_exchangerate.moveToFirst();
      //et_cash_nt.setText(cursor_sqlite_table_exchangerate.getString(0));
      et_cash_peso.setText(String.valueOf(nf.format(1.0/Double.valueOf(cursor_sqlite_table_exchangerate.getString(1)))));
      et_cash_aud.setText(String.valueOf(nf.format(1.0/Double.valueOf(cursor_sqlite_table_exchangerate.getString(2)))));
      et_cash_usd.setText(String.valueOf(nf.format(1.0/Double.valueOf(cursor_sqlite_table_exchangerate.getString(3)))));
      new AlertDialog.Builder(context)
      .setView(view_update_exchangerate)
      .setPositiveButton(R.string.str_button_save, new DialogInterface.OnClickListener()
            {                         
             public void onClick(DialogInterface dialog, int whichButton)
             {
        tv_updatedate.setText(sdf.format(new java.util.Date()));
              Cursor cursor_sqlite_table_exchangerate = null;
        try
        {   
         cursor_sqlite_table_exchangerate = dbHelper.select(tables[2], null, null, null, null, null, null);
                  cursor_sqlite_table_exchangerate.moveToFirst();
               String[] updateFields = {//"fieldname_country1_exchangerate", 
                      "fieldname_country2_exchangerate", 
                      "fieldname_country3_exchangerate", 
                      "fieldname_country4_exchangerate"}; 
               String[] updateValues = {//String.valueOf(nf.format(1.0/Double.valueOf(et_cash_nt.getText().toString()))), 
                      String.valueOf(nf.format(1.0/Double.valueOf(et_cash_peso.getText().toString()))), 
                      String.valueOf(nf.format(1.0/Double.valueOf(et_cash_aud.getText().toString()))), 
                      String.valueOf(nf.format(1.0/Double.valueOf(et_cash_usd.getText().toString())))};
               dbHelper.update(tables[2], updateFields, updateValues, null, null);
               //對應的匯率結果也做修正
         change_selected_country(spinner_cash.getSelectedItemPosition());
         //更新tables[1]
         save_sqlite_table_listData();
         //更新ListView
         update_listview();
        }
        catch(Exception e)
        {
         System.out.println("564 Exception : setPositiveButton{}");
        }
        finally
        {
         cursor_sqlite_table_exchangerate.close();
        }
             }
            })
            .setNegativeButton(R.string.str_button_cancel, new DialogInterface.OnClickListener()
            {                         
             public void onClick(DialogInterface dialog, int whichButton)
             {
          
             }
            })             
   .show();
  }
  catch(Exception e)
  {
   System.out.println("583 Exception : MENU_UPDTAE_EXCHANGERATE");
  }
  finally
  {
   cursor_sqlite_table_exchangerate.close();
  }
    }
    
    /*
     *  檢查網路狀態, 必須加入權限
     *  
     */
 public boolean checkInternet()
 {
  boolean result = false;
  ConnectivityManager connManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
  NetworkInfo info = connManager.getActiveNetworkInfo();
  if (info == null || !info.isConnected())
  {
   result = false;
  }
  else
  {
   if (!info.isAvailable())
    result = false;
   else
    result = true;
  }
  return result;
 }
}
////

2012年1月3日 星期二

SQLiteOpenHelper ~ 旅遊匯率隨時查(一)















Activity_ExchangeRate.java
package com.tsots.ExchangeRate;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Activity_ExchangeRate extends Activity 
{
 Context context = Activity_ExchangeRate.this;
 String Tag = "Activity_ExchangeRate.java";
 TextView tv_updatedate;
 Spinner spinner_cash;
 ListView lv_exchange;
 EditText et_cash;
 Button bt_exchange;
 
 ArrayAdapter adapter_spinner_country;
 Adapter_ListView_Exchange adapter_listview_exchange;
 java.text.SimpleDateFormat sdf;
 
 String tables[] = {"table_value", "table_listData", "table_exchangerate"};
 String fieldNames[][] =
 {
  { "fieldname_date", "fieldname_country", "fieldname_cash"},
  { "fieldname_id", "fieldname_column_country", "fieldname_column_cash", "fieldname_column_unit"},
  { "fieldname_country1_exchangerate", "fieldname_country2_exchangerate", "fieldname_country3_exchangerate", "fieldname_country4_exchangerate"}
 };
 String fieldTypes[][] =
 {
  { "text", "text", "text"},
  { "INTEGER PRIMARY KEY AUTOINCREMENT", "text", "text", "text"},
  { "text", "text", "text", "text"},
 };
 int version = 1;
 private SQLiteOpenHelper_ExchangeRate dbHelper = new SQLiteOpenHelper_ExchangeRate 
 (
   this,
   "SQLite_ExchangeRate.db",
   null,
   version,    
   tables,
   fieldNames,
   fieldTypes
 );
 
 String selected_country;
 int int_selected_country;
 String[] array_country;
 String[] array_cash;
 String[] array_unit;
 String[] array_deafault_exchangerate;
 List allarray_country = new ArrayList();
 List allarray_cash;
 List final_allarray_cash;
 List allarray_unit = new ArrayList();
 List all_id;
 DecimalFormat nf = new DecimalFormat("0.000");
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_exchangerate);
        bt_exchange = (Button) findViewById (R.id.bt_exchange);
        et_cash = (EditText) findViewById (R.id.et_cash);
     array_country = getResources().getStringArray(R.array.array_country);
     array_cash = getResources().getStringArray(R.array.array_cash);
     array_unit = getResources().getStringArray(R.array.array_unit);
     array_deafault_exchangerate = getResources().getStringArray(R.array.array_cash);
        tv_updatedate = (TextView) findViewById (R.id.tv_updatedate);
        spinner_cash = (Spinner) findViewById (R.id.spinner_cash);
        lv_exchange = (ListView) findViewById (R.id.lv_exchange);
        
     sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

     default_sqlite_table_listdata();
     update_spinner();
     update_listview();
     
        bt_exchange.setOnClickListener(new OnClickListener()
        {
   public void onClick(View v) 
   {
    Log.i(Tag, "匯率換算ing...");
    //tv_updatedate.setText(sdf.format(new java.util.Date()));
    //擷取EditText的值, 更新allarray_cash
    System.out.println("104 et_cash.getText().toString() = "+et_cash.getText().toString());
    System.out.println("105 allarray_cash = "+ allarray_cash); 
    if(!et_cash.getText().toString().equals(""))
    {
        save_sqlite_table_value();    
     save_sqlite_table_listData();
     //save_sqlite_table_exchangerate();
     Log.i(Tag, "更新畫面資料");
     update_spinner();
     update_listview();
    }
    else
    {
     Toast.makeText(context, "請輸入正確數字", Toast.LENGTH_SHORT).show();
     allarray_cash = new ArrayList();
     for (int i=0; i<4 ; i++)
     {
      allarray_cash.add("");
     }
     save_sqlite_table_listData();
     update_listview();
    }
   }         
        });
    }

    //AP關閉前執行
 @Override
 protected void onPause() 
 {
  save_sqlite_table_value();
        save_sqlite_table_listData();
  super.onPause();
 }
 
 /*
  *  更新tables[0]
  *    TextView更新日期   Spinner所選貨幣   EditText兌換金額
  *  {"fieldname_date", "fieldname_country", "fieldname_cash"}
  */
    public void save_sqlite_table_value()
    {
     Log.i(Tag, "儲存tables[0]資料ing...");
     Cursor cursor_sqlite_table_value = null;
  try
  { 
   cursor_sqlite_table_value = dbHelper.select(tables[0], null, null, null, null, null, null);
   cursor_sqlite_table_value.moveToFirst();  
   String[] updateFields = {"fieldname_date", "fieldname_country", "fieldname_cash"};
   String[] updateValues = {tv_updatedate.getText().toString(), String.valueOf(int_selected_country), et_cash.getText().toString()};
      dbHelper.update(tables[0], updateFields, updateValues, null, null);      
  }
  catch(Exception e)
  {
   System.out.println("158 Exception : save_sqlite_table_value()");
  }
  finally
  {
   cursor_sqlite_table_value.close();
  }
    }

 /*
  *  更新tables[1]
  *   換算後各國幣值List
  *  {"fieldname_column_cash"}
  */
    public void save_sqlite_table_listData()
    {
     Log.i(Tag, "儲存tables[1]資料ing...");
     Cursor cursor_sqlite_table_listdata = null;
  try
  {   
   cursor_sqlite_table_listdata = dbHelper.select(tables[1], null, null, null, null, null, null);
      cursor_sqlite_table_listdata.moveToFirst();
      //更新資料庫
   String[] updateFields = {"fieldname_column_cash"};
   String where = "fieldname_id=?"; 
   int position = 1;
   do
   {
    if(position <= cursor_sqlite_table_listdata.getCount())
    {
     String[] updateValues = {allarray_cash.get(position-1)};
     String[] whereValue = {String.valueOf(position)};
     dbHelper.update(tables[1], updateFields, updateValues, where, whereValue);
     position++;
    }
   }while(cursor_sqlite_table_listdata.moveToNext());
  }
  catch(Exception e)
  {
   System.out.println("196 Exception : save_sqlite_table_listData()");
  }
  finally
  {
   cursor_sqlite_table_listdata.close();
  }
    }    

 /*
  *  更新tables[2]
  *      台幣        菲律賓幣        澳幣        美金 
  *  { "fieldname_country1_exchangerate", "fieldname_country2_exchangerate", "fieldname_country3_exchangerate", "fieldname_country4_exchangerate"}
  */
    public void save_sqlite_table_exchangerate()
    {
     Log.i(Tag, "儲存tables[2]資料ing...");
     Cursor cursor_sqlite_table_listdata = null;
  try
  {   
   cursor_sqlite_table_listdata = dbHelper.select(tables[2], null, null, null, null, null, null);
      cursor_sqlite_table_listdata.moveToFirst();
      //更新資料庫
   String[] updateFields = { "fieldname_country1_exchangerate", "fieldname_country2_exchangerate", "fieldname_country3_exchangerate", "fieldname_country4_exchangerate"};
   String[] updateValues = {allarray_cash.get(0), allarray_cash.get(1), allarray_cash.get(2), allarray_cash.get(3)};
   dbHelper.update(tables[2], updateFields, updateValues, null, null);
  }
  catch(Exception e)
  {
   System.out.println("224 Exception : save_sqlite_table_listData()");
  }
  finally
  {
   cursor_sqlite_table_listdata.close();
  }
    }
    
    /*
  *  更新Spinner畫面資料 
  */
    public void update_spinner()
    {
     Log.i(Tag, "設定Spinner選項");
     Cursor cursor_sqlite_table_value = null;
     //try
     //{
      cursor_sqlite_table_value = dbHelper.select(tables[0], null, null, null, null, null, null);
      cursor_sqlite_table_value.moveToFirst();
      tv_updatedate.setText(cursor_sqlite_table_value.getString(0));
      et_cash.setText(cursor_sqlite_table_value.getString(2));     
     //}
     //catch(Exception e)
     //{     
      adapter_spinner_country = new ArrayAdapter(this, android.R.layout.simple_spinner_item, array_country);
      adapter_spinner_country.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      spinner_cash.setAdapter(adapter_spinner_country);
      //從SQLite中擷取資料, 避免spinner item又跳回預設值0
      spinner_cash.setSelection(Integer.valueOf(cursor_sqlite_table_value.getString(1)));
      spinner_cash.setOnItemSelectedListener(new Spinner.OnItemSelectedListener()
      {      
       public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3)
       {
        int_selected_country = arg2;
        //依Spinner的選項更改, 置換ListView的幣值換算結果
        change_selected_country(int_selected_country);
        save_sqlite_table_value();
        save_sqlite_table_listData();
        //save_sqlite_table_exchangerate();
        update_listview();
       } 
    public void onNothingSelected(AdapterView arg0) 
    {
  
    }
      });   
     //}
     //finally
     //{
      cursor_sqlite_table_value.close();
     //}     
    }
    
    /*
  *  更新ListView畫面資料 
  */
    public void update_listview()
    {
     Log.i(Tag, "設定ListView內容");
     Cursor cursor_sqlite_table_listdata = null;
     try
     {
      //在此必須初使化allarray_cash, 否則ListView資料無法更新
      final_allarray_cash = new ArrayList();
      cursor_sqlite_table_listdata = dbHelper.select(tables[1], null, null, null, null, null, null);
      cursor_sqlite_table_listdata.moveToFirst();
      do
      {
       allarray_country.add(cursor_sqlite_table_listdata.getString(1));
       final_allarray_cash.add(cursor_sqlite_table_listdata.getString(2));
       allarray_unit.add(cursor_sqlite_table_listdata.getString(3));
      }while(cursor_sqlite_table_listdata.moveToNext());
     }
     catch(Exception e)
     {
      System.out.println("299 Exception : update_listview()");
     }
     finally
     {
      cursor_sqlite_table_listdata.close();
     }
     
     adapter_listview_exchange = new Adapter_ListView_Exchange
     (
      this, 
      android.R.layout.simple_list_item_1, 
      allarray_country, 
      final_allarray_cash,
      allarray_unit
     );
     lv_exchange.setAdapter(adapter_listview_exchange);    
    }
    
    /*
     *  先將SQLite欄位的預設值填好, 避免之後select時產生Exception
     */
 public void default_sqlite_table_listdata()
 {
  Log.i(Tag, "載入SQLite預設值");
  //insert tables[0]
  Cursor cursor_sqlite_table_value = null;
  try
  {
   cursor_sqlite_table_value = dbHelper.select(tables[0], null, null, null, null, null, null);
   cursor_sqlite_table_value.moveToFirst();
   String[] updateFields = {"fieldname_date", "fieldname_country", "fieldname_cash"};
   if(cursor_sqlite_table_value.getCount() == 0)
   {        
     String[] updateValues = {"2011-12", "0", "1"};
     dbHelper.insert(tables[0], updateFields, updateValues);
   }   
  }
     catch(Exception e)
     {
      System.out.println("338 Exception : default_sqlite_table_listdata()");
     }
     finally
     {
      cursor_sqlite_table_value.close();
     }
 
  //insert tables[1]
  Cursor cursor_sqlite_table_listdata = null;
  try
  {
   cursor_sqlite_table_listdata = dbHelper.select(tables[1], null, null, null, null, null, null);
   cursor_sqlite_table_listdata.moveToFirst();
   String[] updateFields = {"fieldname_column_country", "fieldname_column_cash", "fieldname_column_unit"};
   if(cursor_sqlite_table_listdata.getCount() == 0)
   {        
    for(int i=0 ; i();
   cursor_sqlite_table_exchangerate = dbHelper.select(tables[2], null, null, null, null, null, null);
   cursor_sqlite_table_exchangerate.moveToFirst();

   System.out.println("407 int_selected_country = "+int_selected_country);
      if(int_selected_country == 0)
      {
       allarray_cash.add(et_cash.getText().toString());
       allarray_cash.add(String.valueOf(nf.format(Double.valueOf(cursor_sqlite_table_exchangerate.getString(1))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(String.valueOf(nf.format(Double.valueOf(cursor_sqlite_table_exchangerate.getString(2))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(String.valueOf(nf.format(Double.valueOf(cursor_sqlite_table_exchangerate.getString(3))*Double.valueOf(et_cash.getText().toString()))));
       System.out.println("414 "+allarray_cash);       
      }
      else if(int_selected_country == 1)
      {
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(0))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(1))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(et_cash.getText().toString());
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(2))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(1))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(3))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(1))*Double.valueOf(et_cash.getText().toString()))));
       System.out.println("421 "+allarray_cash);
      }
      else if(int_selected_country == 2)
      {
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(0))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(2))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(1))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(2))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(et_cash.getText().toString());
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(3))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(2))*Double.valueOf(et_cash.getText().toString()))));
       System.out.println("430 "+allarray_cash);
      }
      else
      {
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(0))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(3))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(1))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(3))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(String.valueOf(nf.format(Double.parseDouble(cursor_sqlite_table_exchangerate.getString(2))/Double.parseDouble(cursor_sqlite_table_exchangerate.getString(3))*Double.valueOf(et_cash.getText().toString()))));
       allarray_cash.add(et_cash.getText().toString());
       System.out.println("438 "+allarray_cash);
      }
  }
  catch(Exception e)
  {
   System.out.println("443 Exception : change_selected_country(int int_selected_country)");
  }
  finally
  {
   cursor_sqlite_table_exchangerate.close();
  }
    }
}
////


Adapter_ListView_Exchange.java
package com.tsots.ExchangeRate;

import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class Adapter_ListView_Exchange extends BaseAdapter
{
 private LayoutInflater mInflater;
 List adapter_allarray_country;
 List adapter_allarray_cash;
 List adapter_allarray_unit;
 TextView column_country;
 TextView column_cash;
 TextView column_unit;

 public Adapter_ListView_Exchange
 (
   Context context,
   int simple_list_item_single_choice, 
   List allarray_country,
   List allarray_cash, 
   List allarray_unit
 ) 
 {
  mInflater = LayoutInflater.from(context);
  adapter_allarray_country = allarray_country;
  adapter_allarray_cash = allarray_cash;
  adapter_allarray_unit = allarray_unit;
 }

 public int getCount()
 {
  return adapter_allarray_cash.size();
 }

 public Object getItem(int position)
 {
  return adapter_allarray_cash.get(position);
 }
  
 public long getItemId(int position)
 {
  return position;
 }
  
 public View getView(int position,View convertView,ViewGroup parent)
 {
     convertView = mInflater.inflate(R.layout.layout_adapter_listview_exchange,null);
     column_country = (TextView)convertView.findViewById(R.id.column_country);
     column_cash = (TextView)convertView.findViewById(R.id.column_cash);
     column_unit = (TextView)convertView.findViewById(R.id.column_unit);
     column_country.setText(adapter_allarray_country.get(position).toString());
     column_cash.setText(adapter_allarray_cash.get(position).toString());
     column_unit.setText(adapter_allarray_unit.get(position).toString());
     return convertView;
 }
}


SQLiteOpenHelper_ExchangeRate.java
package com.tsots.ExchangeRate;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class SQLiteOpenHelper_ExchangeRate extends SQLiteOpenHelper

{

  public String TableNames[];

  public String FieldNames[][];

  public String FieldTypes[][];

  public static String NO_CREATE_TABLES = "no tables";

  private String message = "";

  

  public SQLiteOpenHelper_ExchangeRate(Context context, String dbname, CursorFactory factory, int version, String tableNames[], String fieldNames[][], String fieldTypes[][])

  {

    super(context, dbname, factory, version);

    TableNames = tableNames;

    FieldNames = fieldNames;

    FieldTypes = fieldTypes;

  }



  @Override

  public void onCreate(SQLiteDatabase db)

  {

    if (TableNames == null)

    {

      message = NO_CREATE_TABLES;

      return;

    }



    for (int i = 0; i < TableNames.length; i++)

    {

      String sql = "CREATE TABLE " + TableNames[i] + " (";

      for (int j = 0; j < FieldNames[i].length; j++)

      {

        sql += FieldNames[i][j] + " " + FieldTypes[i][j] + ",";

      }

      sql = sql.substring(0, sql.length() - 1);

      sql += ")";

      db.execSQL(sql);

    }

  }



  @Override

  public void onUpgrade(SQLiteDatabase db, int arg1, int arg2)

  {

    for (int i = 0; i < TableNames[i].length(); i++)

    {

      String sql = "DROP TABLE IF EXISTS " + TableNames[i];

      db.execSQL(sql);

    }

    onCreate(db);

  }



  public void execSQL(String sql) throws java.sql.SQLException

  {

    SQLiteDatabase db = this.getWritableDatabase();

    db.execSQL(sql);

  }



  public Cursor select(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)

  {

    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);

    return cursor;

  }



  public long insert(String table, String fields[], String values[])

  {

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues cv = new ContentValues();

    for (int i = 0; i < fields.length; i++)

    {

      cv.put(fields[i], values[i]);

    }

    return db.insert(table, null, cv);

  }



  public int delete(String table, String where, String[] whereValue)

  {

    SQLiteDatabase db = this.getWritableDatabase();



    return db.delete(table, where, whereValue);

  }



  public int update(String table, String updateFields[],

      String updateValues[], String where, String[] whereValue)

  {

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues cv = new ContentValues();

    for (int i = 0; i < updateFields.length; i++)

    {

      cv.put(updateFields[i], updateValues[i]);

    }

    return db.update(table, cv, where, whereValue);

  }



  public String getMessage()

  {

    return message;

  }



  @Override

  public synchronized void close()

  {

    // TODO Auto-generated method stub

    super.close();

  }

}

2012年1月1日 星期日

How to use ListView








這是一個應用ListView的小範例, 讓Activity產生一個具有清單效果的條列式資料表.

讓我們在layout中放置一個EditText, 二個Button和一個ListView Widget, 並且預設4筆資料在ListView中, 使用者可自行輸入資料, 新增到ListView中或將ListView中的資料刪除.

為觸發點選列表的事件, 需要實作OnItemClickListener.

不過由於這個範例並沒有建立資料庫, 所以所有的變更在退出AP後就會回到原始狀態了>_<

另外如需要更進階的去增加多筆欄位, 色彩, 文字大小....等, Android API中有提供android.widget.BaseAdaoter物件讓開發者也能透過自行定義的Adapter去設計更豐富的畫面, 甚至還能加入圖檔呢!


ListView_malloc.java
package com.tsots.ListView_malloc;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class ListView_malloc extends Activity
{
 Context context = ListView_malloc.this;
 String tag = "ListView_malloc.this";
 String[] countriesStr;
 TextView myTextView;
 EditText myEditText;
 Button myButton_add;
 Button myButton_remove;
 ListView listview;
 ArrayAdapter adapter2;
 List allData;
 String newData;
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  countriesStr = getResources().getStringArray(R.array.array_listview);
  allData = new ArrayList();
  for (int i = 0; i < countriesStr.length; i++)
  {
   allData.add(countriesStr[i]);
  }
  adapter2 = new ArrayAdapter(this,android.R.layout.simple_list_item_1, allData);  
     myTextView = (TextView) findViewById(R.id.myTextView);
     myEditText = (EditText) findViewById(R.id.myEditText);
     myButton_add = (Button) findViewById(R.id.myButton_add);
     myButton_remove = (Button) findViewById(R.id.myButton_remove);
     listview = (ListView) findViewById(R.id.listview1);    
     listview.setAdapter(adapter2);
     myButton_add.setOnClickListener(new Button.OnClickListener()
     {
      public void onClick(View arg0)
      {
       newData = myEditText.getText().toString();
       for (int i = 0; i < adapter2.getCount(); i++)
       {
        if (newData.equals(adapter2.getItem(i)))
        {
         return;
        }
       }       
       if (!newData.equals(""))
       {
        adapter2.add(newData);
        int position = adapter2.getPosition(newData);
        listview.setSelection(position);
        myEditText.setText("");
       }
      }
     });
 
     //替ListView加入被選重的事件
     listview.setOnItemClickListener(new ListView.OnItemClickListener()
     {
      public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) 
      {
       myTextView.setText(allData.get(arg2)); 
       myEditText.setText(allData.get(arg2));
      }
     });

     //當按下"移除"button, 先判別user是否有選中一筆資料
     myButton_remove.setOnClickListener(new Button.OnClickListener()
     {
      public void onClick(View arg0)
      {
       if (myEditText.getText().toString() != "")
       {
        //從ListView移除
        allData.remove(myEditText.getText().toString());
        listview.setAdapter(adapter2);
        myEditText.setText("");
        if (adapter2.getCount() == 0)
        {
         myTextView.setText("");
        }
       }
      }
     });    
 }
}//