04(New!)

shrewdnessmodernMobile - sans fil

14 déc. 2013 (il y a 3 années et 10 mois)

198 vue(s)

//2
-
1.

ItemDeclare


private

EditText
height
;


private

EditText
weight
;


private

Button
submit
;



private

TextView
result
;


private

TextView
suggest
;



//
2
-
2_Binding


height = (EditText)findViewById(R.id.Input_Height);


weight = (EditText)findVie
wById(R.id.Input_Weight);


submit = (Button)findViewById(R.id.Btn_submit);


result =(TextView)findViewById(R.id.txt_Result);


suggest =(TextView)findViewById(R.id.txt_suggest);



//
02
-
3_Set Listener for Button


submit.setOnClic
kListener(new View.OnClickListener() {



public void onClick(View v) {




// put your code here



//2
-
4




















}



});




//
02
-
4 BMI calculate


DecimalFormat nf = new DecimalFormat("0.00");


double h = Double.parseDouble(h
eight.getText().toString())/100;


double w = Double.parseDouble(weight.getText().toString());


double BMI = w / (h * w);



result.setText("Your BMI is "+nf.format(BMI));



//Give health advice


if
(BMI>25){




suggest.setText("
您太重了
,
需要減肥
");


}else if(BMI<20){




suggest.setText("
您太輕了
,
需要增肥
");


}else{




suggest.setText("
恭喜您
,
身材剛剛好

^_^");


}






//
03
-
1


void findViews()


{


//3
-
2






}


//
03
-
3


void SetListener()


{




//3
-
4











}


//
03
-
5

findViews();

SetListener();


//
03
-
6

//3
-
6 extra:

suggest.sexText
當中的文字
,
建立一個
advice.xml
並儲存起來





//
04
-
1


//
設定
Item ID


protected static final int MENU_ABOUT = Menu.FIRST;


protected stat
ic final int MENU_QUIT = Menu.FIRST+1;


//
04
-
2


private void openOptionsDialog() {


new AlertDialog.
Builder
(MainActivity.this)


.setTitle("BMI
計算器
")


.setMessage("
作者
:XXX")


.setPositiveButton("
確定
",


new
DialogInterface.OnClickListener(){


public void onClick(


DialogInterface dialoginterface, int i){


}


})


.show();



}


// reference :
http://developer.android.com/intl/zh
-
TW/reference/android/app/AlertDialog.Builder.html


//
04
-
3


//



@Override


public boolean onCr
eateOptionsMenu(Menu menu) {



// TODO Auto
-
generated method stub



super.onCreateOptionsMenu(menu);



menu.add(0,MENU_ABOUT,0,"
關於
...");



menu.add(0,MENU_QUIT,0,"
結束
");



return true;


}




//
04
-
4


//



@Override


public boolean onOptionsItemSelected(MenuI
tem item) {



// TODO Auto
-
generated method stub



super.onOptionsItemSelected(item);



switch(item.getItemId())



{



case MENU_ABOUT:




openOptionsDialog();




break;








case MENU_QUIT:




finish();




break;



}









return true;


}



//
05
-
1

//
File
-
> New
-
> Android Activity

// name "Report"


//
05
-
2

//
參考
main.xml ,
建立新的
report.xml ,
做為此
Activity

LayOut

//
底下為
report.xml
的描述


<?xml version="1.0" encoding="utf
-
8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"


android:orientation="vertical"


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"


/>

</LinearLayout>



//
05
-
3

//

Report Activity
當中加入

setContentView(R.layout.rep
ort);


//
05
-
4


//Switch to report page


Intent intent = new Intent();


intent.setClass(MainActivity.this, Report.class);


//
05
-
5


Bundle bundle = new Bundle();


bundle.putString("KEY_HEIGHT", height.getText().toS
tring());


bundle.putString("KEY_WEIGHT", weight.getText().toString());


intent.putExtras(bundle);


//
05
-
6

startActivity(intent);




//05
-
6

AndroidManifest
.
xml




<?xml version="1.0" encoding="utf
-
8"?>



<manifest xmlns:android="http://schemas.android.com/apk/res/android"







package="com.demo.android.bmi">






<application android:icon="@drawable/icon">










<activity android:name=".bmi" android:label
="@string/app_name">













<intent
-
filter>
















<action android:name="android.intent.action.MAIN" />

















<category android:name="android.intent.category.LAUNCHER" />













</intent
-
filter>









</activity>







<activi
ty android:name="Report"></activity>




</application>


</manifest>




//
05
-
7 report.xml

//

Report.xml
中新增
BMI
結果
(TextView),
建議
(TextView) ,
回到前一頁
(Button)



<TextView android:id="@+id/result"


android:layout_width="fill_parent"



android:layout_height="wrap_content"


android:text=""


/>


<TextView android:id="@+id/suggest"


android:layout_width="fill_parent"


android:layout_height="wrap_content"


android:text=""


/>


<Button android:id="@+id/report_back"


android:layout_width="wrap_content"


android:layout_height="wrap_content"


android:text="Return to Previous"


/>




//
05_8 Report.java

//
加在
Report Activity class
裡面





private TextView view_result;


private TextView view_suggest;


private Button button_back;




private void findViews()


{



view_result = (TextView) findViewById(R.id.result);



view_suggest = (TextView) findViewById(
R.id.suggest);



button_back = (Button) findViewById(R.id.report_back);


}





private void setListensers()


{



// Define a button called yourButtonName in your xml layout file (res/layout)



button_back=(Button)findViewById(R.id.report_back);



butt
on_back.setOnClickListener(new View.OnClickListener() {



public void onClick(View v) {




// put your code here




Report.this.finish();




}



});




}





private void showResults() {




DecimalFormat nf = new DecimalFormat("0.00");








Bu
ndle bunde = this.getIntent().getExtras();




double height = Double.parseDouble(bunde.getString("KEY_HEIGHT"))/100;




double weight = Double.parseDouble(bunde.getString("KEY_WEIGHT"));




double BMI = weight / (height * height);




view_res
ult.setText(getString(R.string.txt_result) +nf.format(BMI));








//Give health advice




if(BMI>25){




view_suggest.setText(R.string.advice_heavy);




}else if(BMI<20){




view_suggest.setText(R.string.advice_light);




}else{




view_suggest.setText(R.string.advice_average);




}





}



//
05_9 Report.java



findViews();



showResults();



setListensers();







//
06
-
0


public static final String PREF = "BMI_PREF";


public static final String PRE
F_HEIGHT = "BMI_Height";




//
06
-
1


@Override


protected void onStop(){


super.onStop();


// Save user preferences. use Editor object to make changes.


SharedPreferences settings = getSharedPrefere
nces(PREF, 0);


settings.edit()


.putString(PREF_HEIGHT, height.getText().toString())


.commit();


}



//
06
-
2


// 06
-
2


private void restorePrefs()


{


SharedPreferences settings = get
SharedPreferences(PREF, 0);


String pref_height = settings.getString(PREF_HEIGHT, "");


if(! "".equals(pref_height))


{


height.setText(pref_height);


weight.requestFocus();


}


}



//
06
-
3

re
storePrefs();



//
06_4

[Optional]
database
-

Date choose Button Create in main.XML

<TextView android:text="plz choose a date" android:id="@+id/TextView01"
android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>

<Button andro
id:text="Button01" android:id="@+id/Btn_Date"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>

<Button android:text="
紀錄當日體重
" android:id="@+id/Btn_Update"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>



//
06_5 database
-

class create

// create class myDBAdapter in myDBAdapter.java to wrap the database related class




public class myDB
Adapter {



private SQLiteDatabase mDb;


private final Context mCtx;




private myDBHelper mDbHelper;




private static final String TAG = "DbAdapter"; //
用於
Log
輸出




//
根據需要來建立
ID


// public static final String KEY_TITLE = "title";


// public static final String KEY_BODY = "body";


// public static final String KEY_ROWID = "_id";




public static final String Col_Date = "recorddate"; //
項目索引號


public static final String Col_Weight = "weight"; //
重量









// DB info


private static String DB_name = "myDB";


private static final String DB_TABLE = "myexercise";



private static int DB_version=2;






// TODO: Client/Server
端加入
LastUpdate,
方便判斷同步


private static final String DATABASE_CREATE =


"create table

"+ DB_TABLE +" ("


+ Col_Date + " integer primary key autoincrement"


+ ","+Col_Weight+ " Float not null"


+ ");";





private static class myDBHelper extends SQLiteOpenHelper{




public myDBHelper(Con
text context) {




super(context, DB_name, null, DB_version);




// TODO Auto
-
generated constructor stub







}




@Override



public void onCreate(SQLiteDatabase db) {




// TODO Auto
-
generated method stub




try{




db.execSQL(DATABASE_CREATE);




}




catch(SQLException e)




{




Log.e("ERROR", e.toString());




return;




}







}




@Override



public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {




// TODO Auto
-
generated method stub


Log.w(TAG, "Upgrading database f
rom version " + oldVersion + " to "


+ newVersion + ", which will destroy all old data");


db.execSQL("DROP TABLE IF EXISTS "+DB_TABLE );


onCreate(db);







}


}








///
建構式


public myDBAdapter( Context ctx) {



super();






mCtx = ctx;


}







public myDBAdapter Open(){



mDbHelper = new myDBHelper(mCtx)

;



mDb = mDbHelper.getWritableDatabase();



return this;


}




public void Close(){



mDbHelper.close();


}




pu
blic Cursor Query(int nRecorddate)


{







return mDb.query(DB_TABLE, new String[] {Col_Date, Col_Weight,



}, Col_Date+"="+ nRecorddate, null, null, null, null);







}








public long Insert(int nRecorddate , float fWeight)


{



Conte
ntValues initValues = new ContentValues();



initValues.put(Col_Date, nRecorddate);



initValues.put(Col_Weight, fWeight);






return mDb.insert(DB_TABLE, null, initValues);


}




public boolean updateOne(int nRecorddate , float fWeight){



ContentValues
args = new ContentValues();



args.put(Col_Date, nRecorddate);


args.put(Col_Weight, fWeight);






return mDb.update(DB_TABLE, args, Col_Date+"="+nRecorddate, null) >0;


}






public Cursor Update(int nRecorddate , float fWeight)


{



Log.v(TAG, "
Update:"+nRecorddate+","+fWeight );






//

Query
看看
,
有的話就更新
,
沒有的話不更新



Cursor cur = Query(nRecorddate);






//
如果
Query
不到
,insert
進去



if(cur.getCount()==0){




Insert(nRecorddate,fWeight);



}



else



{




// update




updateOne(nRecorddate,fWeight);



}






return cur;









}




///
根據需要進行實作


public void testProc(){






//
根據取得的
date

db query



//
如果
NULL
-
> Insert



//
如果不是
NULL
-
> update









//mDb.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);



//mDb.delete(table, whereClause, whereArgs);



//mDb.insert(table, n
ullColumnHack, values);



//mDb.update(table, values, whereClause, whereArgs);




}















}



//
06_6 database


prepare



//
用來紀錄從
Date Widget
取得的

年月日


private int mYear;


private int mMonth;


private int mDay;





private Button Btn_Date;


private Button Btn_Update;






static final int DATE_DIALOG_ID = 0;


private myDBAdapter m_myDBA; // DBA Adapter




public void SetDateButtonListen
ers(){



//
更新按鈕

-

設定日期




Btn_Date.setOnClickListener(





new View.OnClickListener()





{






public void onClick(View v)






{







showDialog(DATE_DIALOG_ID);






}





}



);














//
更新按鈕

-

執行對
SQL Lite

Query



Btn_Update.setOnClickListener(





new View.OnClickListener()





{






public void onClick(View v)






{







//
把當下的欄位日期
,
天數紀錄到此
,
把日期先轉成整數格式
EX : 20090811









m_myDBA.Update( Integer.parseInt((String) Btn_Date.getText()),
Float.parseFloat( weight.getText().toString() ) ) ;








updateDisplay();








updateDataToViews();








Toast.makeText(MainActivity.this, "
更新完畢
",
Toast.LENGTH_SHORT).show();






}





}



);












}




//
將更新後的日期顯示在按鈕上


private void updateDisplay() {




Btn_Date = (Button)findViewById(R.id.Btn_Date);




Btn_Update = (Button)findViewById(R.id.Btn_Update);





///
格式轉換
-

200884
轉成
20080804



String sMonth = new String(); sMonth = Integer.toString(mMonth+1);



String sDay = new String(); sDay = Integer.toString(mDay);




if( (mMonth +1)<10 )




sMonth = "0"+(mMonth+1);





if( (mDay)<10 )




sDay = "0"+mDay;







Btn_Date.setText(new StringBuilder()


// Month is 0 based so add 1



.append(mYear)



.append(sMonth)


.append(sDay)


);



}




//
程式開始時
,
初始化日期資訊



private void DataInit()



{




//
抓到當天的日期




final Calendar c = Calendar.getInstance();




mYear = c.get(Calendar.YEAR);




mMonth = c.get(Calendar.MONTH);




mDay = c.get(Calendar.DAY_OF_MONTH);





updateDisplay();



}










//

DB
中取得資訊
,
並且反應到
UI



private void updateDataToViews()


{


Cursor cur;


cur = m_myDBA.Query(Integer.parseInt(Btn_Date.getText().toString()));



if(cur.getCount()==0)//
當天尚未有資料


{



//
顯示
-
當天尚未輸入體重



Toast.makeText(MainActivity.this, "
這一天尚未輸入體重
",
Toast.LENGTH_SHORT).show();



//


}


else


{



Toast.makeText(Ma
inActivity.this, "
已有體重記錄
", Toast.LENGTH_SHORT).show();



Log.v("debug", "
已有體重記錄
");



if(cur.moveToFirst())



{





float nValue = cur.getFloat(cur.getColumnIndex(m_myDBA.Col_Weight));





Log.e("ERRORRR"
, Float.toString(nValue));





weight.setText(Float.toString(nValue) );



}


}


}



//
06
-
7


m_myDBA = new myDBAdapter(this);


m_myDBA.Open();


DataInit(); //
取得今天日期


SetDateButtonListen
ers();


updateDataToViews(); //

DB
中取資料
,
並且寫入



//
06
-
8



@Override


protected Dialog onCreateDialog(int id) {



// TODO Auto
-
generated method stub



switch(id)



{



case DATE_DIALOG_ID:




return new DatePickerDialog(this, mDateSetListener, mYear,
mMonth,mDay );



}



return null;


}



/// Date Weight
的測試


private DatePickerDialog.OnDateSetListener mDateSetListener=



new DatePickerDialog.OnDateSetListener(){




@Override




public void onDateSet(DatePicker view, int year, int monthOfYear,






int

dayOfMonth) {





// TODO Auto
-
generated method stub





mYear= year;





mMonth = monthOfYear ;





mDay = dayOfMonth;





updateDisplay();





updateDataToViews();//
試著從
DB
中取出資料








}


};





//
07
-
1 Animation Pic Import



Pic_Animation/
底下的圖匯入至

專案的

dr
awable/
目錄底下




//
07
-
2 anim XML create , name: fat.xml


<?xml version="1.0" encoding="UTF
-
8"?>

<animation
-
list xmlns:android="http://schemas.android.com/apk/res/android"


android:oneshot="true">


<item android:drawable="@drawable/init" android:dur
ation="20" />


<item android:drawable="@drawable/fat01" android:duration="20" />


<item android:drawable="@drawable/fat02" android:duration="20" />


<item android:drawable="@drawable/fat03" android:duration="20" />


<item android:drawable="@dra
wable/fat04" android:duration="20" />


<item android:drawable="@drawable/fat05" android:duration="20" />

</animation
-
list>



//
07
-
3 Add ImageView in report.xml


// Report.xml


<ImageView android:id="@+id/ImageView01" android:layout_width="wrap_co
ntent"
android:layout_height="wrap_content"></ImageView><Button android:id="@+id/report_back"


android:layout_width="wrap_content"


android:layout_height="wrap_content"


android:text="Return to Previous"


/>




//
07
-
4


private ImageView mImageView;



AnimationDrawable ani_show;



//
07
-
5


mImageView = (ImageView)findViewById(R.id.ImageView01);


mImageView.setBackgroundResource(R.anim.fat);


ani_show = (AnimationDrawable)mImageView.getBackg
round();



//
07
-
6


@Override


public boolean onTouchEvent(MotionEvent event) {



// TODO Auto
-
generated method stub



if(event.getAction() == MotionEvent.ACTION_DOWN)



{




ani_show.start();




return true;



}






return super.onTouchEvent(event);


}