根据上次的注册界面,利用安卓的的文件存储来保存注册信息
package com.cbz.blog;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button button;
private EditText name;
private EditText password;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
Map<String, String> userInfo = File.getUserInfo(this);
if (userInfo!=null){
name.setText(userInfo.get("number"));
password.setText(userInfo.get("password"));
}
}
private void initView() {
button = (Button) findViewById(R.id.button);
name=(EditText) findViewById(R.id.name);
password=(EditText)findViewById(R.id.password);
button.setOnClickListener(this);
}
public void onClick(View v){
String number = name.getText().toString().trim();
String passwords = password.getText().toString();
if(TextUtils.isEmpty(number)){
Toast.makeText(this,"输入账号",Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(passwords)){
Toast.makeText(this,"输入密码",Toast.LENGTH_LONG).show();
return;
}
Toast.makeText(this,"登录成功",Toast.LENGTH_LONG).show();
boolean isSaveSucess = File.saveUserInfo(this, number, passwords);
if (isSaveSucess){
Toast.makeText(this,"保存成功",Toast.LENGTH_LONG).show();
}else {
Toast.makeText(this,"保存失败",Toast.LENGTH_LONG).show();
}
}
}
Java
主界面的内容写好后就是文件存储的内容了
package com.cbz.blog;
import android.content.Context;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
public class File {
public static boolean saveUserInfo(Context context,String number,String password){
try {
FileOutputStream fos = context.openFileOutput("data.txt", Context.MODE_PRIVATE);
fos.write((number+":"+password).getBytes());
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static Map<String,String> getUserInfo(Context context){
String content = "";
try {
FileInputStream fis = context.openFileInput("data.txt");
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
Map<String,String> userMap=new HashMap<String, String>();
content = new String(buffer);
String[] infos = content.split(":");
userMap.put("number",infos[0]);
userMap.put("password",infos[1]);
fis.close();
return userMap;
} catch (Exception e) {
//e.printStackTrace();
return null;
}
}
}
Java
本文由 Bigbo 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Jun 2, 2020 at 06:59 pm