码迷,mamicode.com
首页 > 其他好文 > 详细

SharedPreferences

时间:2017-05-09 23:16:46      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:use   end   super   reference   font   username   输入   oid   leo   

xml主界面

技术分享

Java实现

package cn.edu.niit.store;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity {
//获取相关控件
private EditText username;
private EditText userage;
private Button write;
private Button read;

 

@Override

    protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取组件
username = (EditText) findViewById(R.id.name);
userage = (EditText) findViewById(R.id.age);
write= (Button)findViewById(R.id.write);
//设置监听事件
write.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = username.getText().toString();
String age = userage.getText().toString();
//使用saveToFile方法,对其进行写入
if(saveToFile(name)){
Toast.makeText( MainActivity.this,"保存成功" ,Toast.LENGTH_SHORT).show();

}
}
});
//设置监听事件
read = (Button)findViewById(R.id.read);
read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = username.getText().toString();
String filename = "data.txt";
String result = "";
try{
//打开文件,并读取其数据
FileInputStream in = openFileInput( filename );
BufferedReader reader = new BufferedReader( new InputStreamReader( in ) );
name = reader.readLine();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
name = username.getText().toString();
String age = userage.getText().toString();
Toast.makeText(MainActivity.this, "输入姓名"+name+",年龄:" + age,Toast.LENGTH_SHORT).show();
}
});
}

private boolean saveToFile(String Name) {
//打开文件
try {

FileOutputStream out = openFileOutput("data.txt", MODE_PRIVATE );
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( out ) );
writer.write(Name);
out.close();//关闭文件输入流
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}

SharedPreferences

标签:use   end   super   reference   font   username   输入   oid   leo   

原文地址:http://www.cnblogs.com/addresslc/p/6832993.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!