Android 儲存使用者資訊
Main.activity
package cn.itcast.filesave;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText et_info;
private Button btn_save;
private Button btn_read;
protected void onCreat(Bundle savedInstanceState)
{
setContentView(R.layout.activity_main);
//獲取佈局檔案中的控制元件
et_info= (EditText) findViewById(R.id.btn_save);
btn_save=(Button) findViewById(R.id.btn_save);
btn_read=(Button) findViewById(R.id.btn_read);
btn_read.setOnClickListener((OnClickListener) new ButtonListener());
}
//定義Button的時間按鈕點選事件
private class ButtonListener implements OnClickListener{
switch(v.getId()){
case R.id.btn_save:
String saveinfo=et_info.getText().toString().trim();
FileOutputStream fos;
try{
//儲存資料
fos=openFileOutput("data.txt",Context.MODE_APPEND);
fos.write(saveinfo.getBytes());
fos.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Toast.makeText(MainActivity. this, "資料儲存成功",0).show();
break;
case R.id.btn_read:
String content="";
try{
//獲取儲存資料
FileInputStream fis=openFileInput("data.txt");
byte[] buffer=new byte[fis.available()];
fis.read(buffer);
content=new String(buffer);
fis.close();
}catch(Exception e){
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "儲存的資料是:"+content, 0).show();
break;
default:
break;
}
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="20dp"
android:text="請輸入您要儲存的資訊" />
<EditText
android:id="@+id/et_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:ems="10">
<requestFocus />
</EditText>
<Button
android:id="@+id/btn_read"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/rt_info"
android:text="讀取資訊"/>
<Button
android:id="@+id/btn_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/rt_info"
android:text="儲存資訊" />
</RelativeLayout>