2011年11月30日 星期三

資料庫連結並新增

package com.demo.android.SQLiteA;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SQLiteAActivity extends Activity {
   
    static String TABLE_NAME = "Users"; //表格名稱
    static String NAME = "name";        //姓名
    static String ADDRESS = "address";     //住址
    static String PHONE = "phone";         //電話
   
    DBConnection dbconn;
   
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        TextView show=(TextView)findViewById(R.id.show);
        //insert Button
        OnClickListener OnInsertClick = null;
       
       
        dbconn = new DBConnection(this);
        //取得可寫入的資料庫
        SQLiteDatabase db = dbconn.getWritableDatabase();
       
        //查詢資料表
        Cursor c = db.query(TABLE_NAME, new String[] {NAME,PHONE,ADDRESS}, null, null, null, null, null);
            //移至第一筆資料
       c.moveToFirst();
            //如果資料筆數大於0 才讀取資料
       if(c.getCount()> 0)
       show.setText("name="+c.getString(0)+",phone="+c.getString(1)+",address="+c.getString(2));
      
        c.close();
        //設定Onclick函數
        OnInsertClick=new OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            //ContentValues 是負責儲存一對值,但是它儲存的一個是String類型,其他是基本類型
            ContentValues values = new ContentValues();
            values.put(NAME, ((EditText)findViewById( R.id.username)).getText().toString());
            values.put(PHONE, "0912345678");
            values.put(ADDRESS, "TAIWAN");
            //執行寫入資料庫
            SQLiteDatabase db = dbconn.getWritableDatabase();
            db.insert(TABLE_NAME, null, values);
            db.close();
            onCreate(savedInstanceState);
        }
       
        };
       
        Button insertBtn=(Button)findViewById(R.id.insert);
        //建立insertBtnOnclick事件
        insertBtn.setOnClickListener(OnInsertClick);
    }
   
   
  //建立資料庫PhoneDBTable:Users
    public static class DBConnection extends SQLiteOpenHelper {
       private static final String DATABASE_NAME = "PhoneDB";
       private static final int DATABASE_VERSION = 2;
       private DBConnection(Context ctx) {
           //context=內容物件 DATABASE_NAME=傳入的資料庫名稱 null=複雜查詢時使用 DATABASE_VERSION=資料庫版本
           super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
       }
       public void onCreate(SQLiteDatabase db) {
           String sql = "CREATE TABLE " + TABLE_NAME + " (" 
           + NAME + " text not null, "
           + PHONE + " text not null, "
           + ADDRESS + " text not null" + ");";
          
           db.execSQL(sql); 
       }
       public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
           // TODO Auto-generated method stub 
       }
    }
}

2011年11月29日 星期二

使用資料庫

Android所提供的資料儲存,如果需要大量儲存資料時可以使用SQLite,SQLite可用來儲存應用程式中會使用到的資料,還可以透過『Content Provider』來讓其他應用程式可以使用建立的資料庫,在SQLite中可以使用SQL的語法來查詢(SELECT)、修改(UPDATE)、刪除(DELETE)、定義資料格式(CREATE TABLE)、新增(INSERT),首先我們先透過cmd了解如何建立一個資料庫與新增資料表

C:\Users\USER>I://切換到磁碟機路徑
I:\>cd eclipse\android-sdk-windows\tools//指向資料夾
I:\eclipse\android-sdk-windows\tools>adb shell//利用此命令進入模擬器的命令行介面
# cd data/data/
cd data/data/
# ls//列出目錄
ls
com.demo.android.MapA
com.android.providers.subscribedfeeds
com.example.android.softkeyboard
com.android.gesture.builder
com.example.android.livecubes
com.example.android.apis
com.android.vending
com.android.htmlviewer
com.android.gallery
com.android.fallback
com.android.providers.drm
com.android.development
com.google.android.street
com.android.speechrecorder
com.android.spare_parts
com.android.soundrecorder
com.android.sdksetup
com.android.protips
com.android.inputmethod.pinyin
com.svox.pico
com.android.defcontainer
com.android.customlocale
com.android.contacts
com.android.certinstaller
com.android.cardock
com.android.carhome
com.android.camera
com.android.calculator2
com.android.providers.applications
com.android.server.vpn
android.tts
com.android.term
com.android.packageinstaller
jp.co.omronsoft.openwnn
com.google.android.location
com.android.netspeed
com.android.music
com.android.wallpaper.livepicker
com.android.providers.userdictionary
com.android.mms
com.android.quicksearchbox
com.m.map
com.android.providers.settings
com.android.providers.contacts
com.android.phone
com.demo.android.MapB
com.android.launcher
com.android.providers.telephony
com.android.providers.downloads
com.google.android.gsf
com.android.providers.media
com.android.email
com.android.alarmclock
com.android.settings
com.android.inputmethod.latin
com.android.browser
com.google.android.apps.maps
com.demo.android.RadioGroupA
com.demo.android.Map
com.demo.android.SQLiteA
# cd com.demo.android.SQLiteA//指向到你的package
cd com.demo.android.SQLiteA
# ls
ls
database
lib
databases
# chmod 777 database//777表完整的權限 可讀/可寫/可修改 chmod改變預設的存取權限
chmod 777 database
# ls –l//-l列出詳細的檔案資訊 大小 日期 存取權限
ls -l
drwxrwxrwx root     root              2011-11-29 02:04 database
drwxr-xr-x system   system            2011-11-28 07:28 lib
drwxrwxrwx root     root              2011-11-28 08:48 databases
# cd database
cd database
# sqlite3 test.db//利用sqlite3建立db
sqlite3 test.db
SQLite version 3.6.22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table film(num, name, phone, address);// 建一名叫film的資料表4個欄
create table film(num, name, phone, address);
sqlite> .database//進行驗證
.database
seq  name             file

---  ---------------  ----------------------------------------------------------

0    main             /data/data/com.demo.android.SQLiteA/database/test.db

sqlite> .tables//列出所有資料表
.tables
film
sqlite> .schema//印出建立的資料表
.schema
CREATE TABLE film(num, name, phone, address);
sqlite>.exit//離開
#ls

2011年11月27日 星期日

google地圖加入縮放圖示

這篇文章的用意是讓我們的地圖能夠放大和縮小,也就是當地圖拖動時會出現一個浮動的選項,裡面有『+』和『-』代表著放大和縮小,這樣在瀏覽地圖時就方便許多。
首先先更改XML描述檔

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
     >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
     <com.google.android.maps.MapView
        android:id="@+id/map"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:apiKey=""
        android:clickable="true"        />
     <LinearLayout android:id="@+id/draw"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
         >      
     </LinearLayout>  
</RelativeLayout>
android:alignParentBottom 如果該值為true,則將該控制項的底部和父控制項的底部對齊
android:layout_centerHorizontal 如果為真,該控制項將被至於水準方向的中央

package com.demo.android.MapA;


import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;


import android.os.Bundle;
import android.view.ViewGroup;


public class MapAActivity extends MapActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        findViews();
        setupMap();
        
    }
         private MapView mv;//宣告googleMap物件
         private MapController mc;//宣告googleMap控制物件
         private ViewGroup vg;//宣告縮放控制物件
         
private void setupMap() {
// TODO Auto-generated method stub
GeoPoint point_pingtung=new GeoPoint((int)(22.669306*1E6),((int)(120.486203*1E6)));//設定地圖座標經度及緯度
mv.setTraffic(true);//地圖檢視模式
mc.setZoom(17);//值為1-256
mc.animateTo(point_pingtung);//顯示給定的點
}


@SuppressWarnings("deprecation")
private void findViews() {
// TODO Auto-generated method stub
mv=(MapView)findViewById(R.id.map);//抓取google map物件
mc=mv.getController();//控制map物件
        vg=(ViewGroup)findViewById(R.id.draw);//載入LinerLayout
        mv.setBuiltInZoomControls(true);//加入縮放控制到LinerLayout
        //vg.addView(mv.getZoomControls());//加入縮放控制到LinerLayout(1.5版\後不建議使用)
}


@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}



2011年11月24日 星期四

建立Android新專案時無法正常生成R檔

今天又鬼打牆的遇到了建立Android新專案時無法正常生成R檔這個新問題,嘗試了2次都是同樣的結果之後,我決定使用Project → clean 之後再Build 就OK了!!

2011年11月23日 星期三

使用google地圖

    在使用google地圖前我們須先了解Android同時接受KML及GPX等多種地圖座標的資訊格式
※KML(Keyhole Makeup Language):是google地圖和google Earth所使用的座標格式
※GPX:是GPS上常見的紀錄格式
  如何取得KML值:http://www.mygeoposition.com/網站輸入目標值即可取得經緯度


取得金鑰的認證指紋(MD5)
在向Google申請API Key之前,我們必需要先取得自己金鑰的MD5。這裡的金鑰有兩種,一種是開發中的金鑰,另一種則是要發佈用的金鑰。每一台電腦都有屬於自己的金鑰。如果是在不同電腦中開發就要個別取得,要找到你開發金鑰的位置,可以開啟Eclipse > Windows > Preferences > Android > Build裡面有個debug.keystore檔案位置,即是開發用的金鑰。

1.執行cmd,找到Javabin資料夾(若你也是使用XP,位置是:C:\Program Files\Java\jre6\bin)
2.輸入取得MD5的指令,可以取得MD5的編碼
    C:\>cd C:\Program Files\Java\jdk1.7.0\bin

    C:\Program Files\Java\jdk1.7.0\bin>C:\Users\USER\.android\debug.keystore

 C:\Program Files\Java\jdk1.7.0\bin>keytool -list -v -alias androiddebugkey -keystore        "C:\Users\USER\.android\debug.keystore" -storepass android -keypass android
3.就會出現
    別名名稱: androiddebugkey
    建立日期: 2011/10/7
    項目類型: PrivateKeyEntry
    憑證鏈長度: 1
    憑證 [1]:
    擁有者: CN=Android Debug, O=Android, C=US
    發出者: CN=Android Debug, O=Android, C=US
    序號: 53bed02f
    有效期自: Fri Oct 07 10:33:19 CST 2011 : Sun Sep 29 10:33:19 CST 2041
   憑證指紋:
         MD5:  
         SHA1:
         SHA256: 
         簽章演算法名稱: SHA256withRSA
         版本: 3
4.進入GoogleMap API Key的申請網站(http://code.google.com/intl/zh-TW/android/maps-api-signup.html),並且輸入剛剛取得的MD5編碼

5.取得Android Maps API的金鑰
6.將取得的Map API Key貼到

   XML中
   <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <com.google.android.maps.MapView
        android:id="@+id/map"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:apiKey=""//金鑰
        android:clickable="true"        />   
</LinearLayout>

   建立Google API專案
       請建立一個新的專案,在建立新專案的過程中,記得「Build Target」要選擇「Google APIs」。   
   使用地圖
    google地圖的組成元素:
       地圖模型(Moudel)
            地點資訊(GeoPoint):地圖上的座標  
            路徑:兩點之間的關係
       地圖展示(View)
            展示區域(MapView): 座標的週邊區域
            圖層(OverLay):地圖上的標示
       地圖控制(Controller)
           控制檢視圖類型:包含衛星、地圖、街景
           控制縮放尺度(Zoom):最大可以全球,最小就街道或街景地圖
佈屬MapView物件
  
      開啟androidManifest.xml
      <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.demo.android.MapA"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission  android:name="android.permission.ACCESS_FINE_LOCATION"/>"
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>"
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".MapAActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
         <uses-library  android:name="com.google.android.maps"/>"
    </application>
</manifest>
加入以上那4行,各行的存取解釋如下:
 ACCESS_COARSE_LOCATION是有關位置資訊獲取,比如說MyLocation API擷取的Cellid等定位資訊必需加上android.permission.ACCESS_COARSE_LOCATION這個聲明

ACCESS_FINE_LOCATION
ACCESS_LOCATION_EXTRA_COMMANDS ACCESS_MOCK_LOCATION是有關GPS定位擷取的資訊使用GPS LocationProvider類的相關定位資訊必需聲明
android.permission.INTERNET 因為MapView類別與google地圖一樣需要連上網路
定義XML檔(請參照佈屬MapView物件處的程式碼)

產生地圖
  package com.demo.android.MapA;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

import android.os.Bundle;

public class MapAActivity extends MapActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        findViews();
        setupMap();
    }
    private MapView mv;//宣告google map物件
    private MapController mc;//宣告google map控制物件
   
    private void setupMap() {
        // TODO Auto-generated method stub
        GeoPoint point_pintung=new GeoPoint((int)(25.047192*1000000),(int)(121.516981*1000000));//設定地圖座標值 經度&緯度
        mv.setTraffic(true);//地圖檢視模式
                      //.setTraffic         一般檢視模式
                 //.setStatellite       衛星檢視模式
                 //.setStreetView    街景檢視模式
        mc.setZoom(17);
        mc.animateTo(point_pintung);
    }

    private void findViews() {
        // TODO Auto-generated method stub
        mv=(MapView)findViewById(R.id.map);//抓取google map物件
        mc=mv.getController();//控制map物件
    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
}