2012年4月25日 星期三

Sqlite

Sqlite 的應用


                                          updated result

main.java:



public class SQLiteActivity extends Activity {
    /** Called when the activity is first created. */
MySQLiteHelper myHelper; //資料庫輔助類別物件的引用
TextView tv;
private static final String TABLE_NAME = "dictionary_info";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        tv = (TextView) findViewById(R.id.textView01);
        myHelper = new MySQLiteHelper(this, "my.db", null, 1); //新建資料庫輔助類別物件
        insertAndUpdateData(myHelper); //向資料庫中插入和更新資料
        String result = queryData(myHelper); //向資料庫中查詢資料
        tv.setText("字彙\t      中文\t       難度\n" + result);
    }
    
  //方法:向資料庫中的表中插入和更新資料
    public void insertAndUpdateData (MySQLiteHelper myHelper) {
    SQLiteDatabase db = myHelper.getWritableDatabase();//獲取資料庫物件,設定可以寫入的資料庫
    
    //使用execSQL方法向表中插入第一筆資料
    db.execSQL("insert into " + TABLE_NAME + "(voc, chimeaning, level) values('kiwi', '奇異果', 4)");
    
//使用insert方法向表中插入第二筆資料
    ContentValues values = new ContentValues(); //新建ContentValues物件儲存“欄名-欄值”映射
    values.put("voc", "cantaloupe");
    values.put("chimeaning", "哈密瓜");
    values.put("level", 2);
    db.insert(TABLE_NAME, "id", values); //呼叫方法插入資料
    
    //使用insert方法向表中插入第三筆資料
    values.clear();
    values.put("voc", "pomello");
    values.put("chimeaning", "柚子");
    values.put("level", 5);
    db.insert(TABLE_NAME, "id", values); //呼叫方法插入資料
    
    //使用insert方法向表中插入第四筆資料
    values.clear();
    values.put("voc", "sugar cane");
    values.put("chimeaning", "甘蔗");
    values.put("level", 5);
    db.insert(TABLE_NAME, "id", values); //呼叫方法插入資料
    
    //使用update方法更新表中的資料
    values.clear(); //清空ContentValues物件
    values.put("voc", "sugar apple");
    values.put("chimeaning", "釋迦");
    values.put("level", 3);
    db.update(TABLE_NAME, values, "level = 5", null); //更新表中level為2的那列資料
    db.close(); //關閉SQLiteDatabase物件
    
    
    } //end of insertAndUpdateData()
    
    
    
  //方法:從資料庫中查詢資料
    public String queryData(MySQLiteHelper myHelper) {
    String result = "";
    SQLiteDatabase db = myHelper.getReadableDatabase(); //設定可以讀出
    Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
    int nameIndex = cursor.getColumnIndex("voc"); //獲取voc欄的索引
    int chiIndex = cursor.getColumnIndex("chimeaning"); //獲取voc欄的索引
    int levelIndex = cursor.getColumnIndex("level");//獲取level欄的索引
    for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) { //提取資料
    result = result + cursor.getString(nameIndex) + "  ";
    result = result + cursor.getString(chiIndex) + "  ";
    result = result + cursor.getInt(levelIndex) + "      \n";
    }
    cursor.close(); 
    db.close();
    return result;
    }// end of queryData()

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
SQLiteDatabase db = myHelper.getWritableDatabase();
db.delete(TABLE_NAME, "1", null); //刪除hero_info表中的所有資料
super.onDestroy();
}
    
}

*********************************************
public class MySQLiteHelper extends SQLiteOpenHelper{

public MySQLiteHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table if not exists dictionary_info("
+ "id integer primary key,"
+ "voc varchar,"
+ "chimeaning varchar,"
+ "level integer)"
);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}

}

2012年4月4日 星期三

Voice Recognition


res/layout/voice_recognition.xml:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="4dip"
        android:text="Click the button and start speaking" />

    <Button
        android:id="@+id/bVoice"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="speakButtonClicked"
        android:text="Click Me!" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1" >
    </ListView>
 

</LinearLayout>

***************************************************************






public class VoiceRecognitionDisplay extends Activity implements OnClickListener{
    /** Called when the activity is first created. */

ListView listview;
static final int check = 987;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.voice_recognition);
     
        listview = (ListView)findViewById(R.id.listView1);
        Button button = (Button)findViewById(R.id.bVoice);
        button.setOnClickListener(this);
    }//end of onCreate

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

Intent intent = new Intent (RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak up son!");
startActivityForResult(intent, check);
}//end of onClick

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub

if (requestCode == check &&  resultCode == RESULT_OK){
ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));

//檢查一共幾筆資料
lv.setClickable(true);
Toast.makeText(Cq_VoiceRecognition02Activity.this, "一共 "+ Integer.toString(listview.getAdapter().getCount()) + " 個查詢到的項目", Toast.LENGTH_LONG).show();

//設定點選的項目
listview.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {

// 取得Clicked String
String item = (String)listview.getAdapter().getItem(position);

//利用TOAST顯示點選的項目
Toast.makeText(Cq_VoiceRecognition02Activity.this, Integer.toString(position), Toast.LENGTH_SHORT).show();
Toast.makeText(Cq_VoiceRecognition02Activity.this, item, Toast.LENGTH_LONG).show();
}
});

}


super.onActivityResult(requestCode, resultCode, data);
}//end of OnActivityResult

 
}//end VoiceRecognitionDisplay

2012年4月2日 星期一

ViewFlipper + gesture






public class ViewFlipperActivity extends Activity implements OnTouchListener {
/** Called when the activity is first created. */

private GestureDetector mGestureDetector;
private Animation slideLeftIn;
private Animation slideLeftOut;
private Animation slideRightIn;
private Animation slideRightOut;
private ViewFlipper mViewFlipper;

private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private int FP = ViewGroup.LayoutParams.FILL_PARENT;

private Matrix suppMatrix = new Matrix();
private Matrix mBaseMatrix = new Matrix();
private Matrix mDisplayMatrix = new Matrix();

private static boolean isZoom = false;

private Integer[] images = { R.drawable.pic01, R.drawable.pic02,
R.drawable.pic03, R.drawable.pic04, R.drawable.pic05,
R.drawable.pic06 };
private String [] textStrings = {"春香", "夏香", "秋香", "冬香", "仲香", "奎香"};

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mGestureDetector = new GestureDetector(this, new MyGestureDetector());
mViewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper1);
slideLeftIn = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
slideLeftOut = AnimationUtils
.loadAnimation(this, R.anim.slide_left_out);
slideRightIn = AnimationUtils
.loadAnimation(this, R.anim.slide_right_in);
slideRightOut = AnimationUtils.loadAnimation(this,
R.anim.slide_right_out);

LayoutParams ivParams = new ViewGroup.LayoutParams(FP, 200);
LayoutParams tvParams = new ViewGroup.LayoutParams(100, 100);
int index = 0;
for (Integer i : images) {

ImageView iv = new ImageView(this);
iv.setImageResource(i);
iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
     mViewFlipper.addView(iv, index, ivParams);
index++;
}
for (String i : textStrings) {

TextView tv = new TextView(this);
tv.setText(i);
tv.setHeight(100);
tv.setWidth(100);
tv.setGravity(300);
tv.setTextSize(50);
tv.setTextColor(Color.YELLOW);
mViewFlipper.addView(tv, index, tvParams);
index++;
}

mViewFlipper.setOnTouchListener(this);
mViewFlipper.setLongClickable(true);

}

class MyGestureDetector extends SimpleOnGestureListener {

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
// TODO Auto-generated method stub

if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
mViewFlipper.setInAnimation(slideLeftIn);
mViewFlipper.setOutAnimation(slideLeftOut);
mViewFlipper.showNext();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
mViewFlipper.setInAnimation(slideRightIn);
mViewFlipper.setOutAnimation(slideRightOut);
mViewFlipper.showPrevious();
}
return false;
}//end of onFling

// @Override
// public void onLongPress(MotionEvent e) {
// // TODO Auto-generated method stub
//
// ImageView iv = (ImageView) mViewFlipper.getCurrentView();
// //mSuppMatrix.postTranslate(2, 2);
// mDisplayMatrix.setRotateM(0.0f, +350.0f, Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF, 0.5f);
// mDisplayMatrix.set(mBaseMatrix);
// mDisplayMatrix.postConcat(suppMatrix);
// iv.setImageMatrix(mDisplayMatrix);
// //super.onLongPress(e);
//
// isZoom = true;
// }//end of onLongPress
}// end of class MyGestureDetector

@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return mGestureDetector.onTouchEvent(event);
}// end of onTouch

}

*****************************
res/layout/main.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" />

    <ViewFlipper
        android:id="@+id/viewFlipper1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/pic01" />
        
    </ViewFlipper>

</LinearLayout>

*************************************
1. res/anim/sideleft_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">  
    <translate  
        android:fromXDelta="100%p"   
        android:toXDelta="0"   
        android:duration="500"  
        />  
    <alpha  
        android:fromAlpha="0.0"   
        android:toAlpha="1.0"  
        android:duration="500"  
        /> 
</set>

2. res/anim/sideleft_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate  
        android:fromXDelta="0"   
        android:toXDelta="-100%p"   
        android:duration="500"  
        />  
    <alpha  
        android:fromAlpha="1.0"   
        android:toAlpha="0.0"   
        android:duration="500"  
        />

</set>

3. res/anim/side_right_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">  
    <translate   
        android:fromXDelta="-100%p"   
        android:toXDelta="0"   
        android:duration="500"  
        />  
    <alpha  
        android:fromAlpha="0.0"   
        android:toAlpha="1.0"  
        android:duration="500"  
        />  
</set>

4. res/anim/side_right_out.xml

<?xml version="1.0" encoding="utf-8"?>  
<set xmlns:android="http://schemas.android.com/apk/res/android">  
    <translate   
        android:fromXDelta="0"   
        android:toXDelta="100%p"   
        android:duration="500"  
        />  
    <alpha  
        android:fromAlpha="1.0"   
        android:toAlpha="0.0"  
        android:duration="500"  
        />  
</set>