總網頁瀏覽量

關於我自己

我的相片
人生的必修課是接受無常,人生的選修課是放下執著。

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;
 }
}
////

沒有留言:

張貼留言