首页 > 代码库 > SharedPreferences
SharedPreferences
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。