目录
MainActivity.this 调用时加个参数MainActivity.this 就是context
UserInfoUtils.java 不硬编码,改用context获取目录路径
案例1:记住用户名密码
写法1:纯IO流方式,硬编码
布局:
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity" >
<EditText
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名" />
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:password="true"
android:hint="请输入密码" />
<RelativeLayout
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<CheckBox
android:id="@+id/cb_ischeck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="记住密码" />
<Button
android:onClick="login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="登录"
/>
</RelativeLayout>
</LinearLayout>
主逻辑代码:MainActivity.java
package com.example.login;
import java.util.Map;
import android.os.Bundle;
import android.app.Activity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.TextureView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.example.login2.R;
public class MainActivity extends Activity {
private EditText et_name;
private EditText et_pwd;
private CheckBox cb_check;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name = (EditText) findViewById(R.id.et_username);
et_pwd = (EditText) findViewById(R.id.et_password);
cb_check = (CheckBox) findViewById(R.id.cb_ischeck);
//读取info.txt
Map<String,String> maps=UserInfoUtils.read();
if(maps!=null){
et_name.setText(maps.get("name"));
et_pwd.setText(maps.get("pwd"));
cb_check.setChecked(true);
}
}
public void login(View v){
String username = et_name.getText().toString().trim();
String pwd = et_pwd.getText().toString().trim();
if(TextUtils.isEmpty(username)||TextUtils.isEmpty(pwd)){
Toast.makeText(this, "用户名或密码不能为空!", 0).show();
}else{
System.out.println("连接服务器中...");
if(cb_check.isChecked()){
boolean res = UserInfoUtils.saveInfo(username, pwd);
if(res){
Toast.makeText(this, "保存成功!", 0).show();
}else{
Toast.makeText(this, "保存失败!", 0).show();
}
}else{
System.out.println("未保存密码!");
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
工具类UserInfoUtils.java
package com.example.login;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class UserInfoUtils {
public static boolean saveInfo(String username,String pwd) {
try {
String result=username+"##"+pwd;
//创建文件(确定输出位置)
File file=new File("/data/data/com.example.login2/info.txt");
//创建输出流
FileOutputStream fos=new FileOutputStream(file);
//输出(写)文件
fos.write(result.getBytes());
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static Map<String, String> read() {
try {
Map<String, String> maps=new HashMap<String, String>();
File file=new File("/data/data/com.example.login2/info.txt");
FileInputStream fis=new FileInputStream(file);
BufferedReader bfr=new BufferedReader(new InputStreamReader(fis));
String content=bfr.readLine();//读一行
String[] splits = content.split("##");
maps.put("name",splits[0]);
maps.put("pwd", splits[1]);
fis.close();
return maps;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
第一次改进
写法2:使用上下文获取文件录
上下文context就是this或者说MainActivity.this
String path = context.getFilesDir().getPath();//context就是MainActivity.this 调用此api,会自动帮我们在本项目包名目录下创建一个专门的文件目录files以供我们创建,存放,读取文件到外存
MainActivity.this 调用时加个参数MainActivity.this 就是context
package com.example.login;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText et_name;
private EditText et_pwd;
private CheckBox cb_check;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name = (EditText) findViewById(R.id.et_username);
et_pwd = (EditText) findViewById(R.id.et_password);
cb_check = (CheckBox) findViewById(R.id.cb_ischeck);
// 读取info.txt
Map<String, String> maps = UserInfoUtils.read(MainActivity.this);
if (maps != null) {
et_name.setText(maps.get("name"));
et_pwd.setText(maps.get("pwd"));
cb_check.setChecked(true);
}
}
public void login(View v) {
String username = et_name.getText().toString().trim();
String pwd = et_pwd.getText().toString().trim();
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(pwd)) {
Toast.makeText(this, "用户名或密码不能为空!", 0).show();
} else {
System.out.println("连接服务器中...");
if (cb_check.isChecked()) {
boolean res = UserInfoUtils.saveInfo(this, username, pwd);
if (res) {
Toast.makeText(this, "保存成功!", 0).show();
} else {
Toast.makeText(this, "保存失败!", 0).show();
}
} else {
System.out.println("未保存密码!");
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
UserInfoUtils.java 不硬编码,改用context获取目录路径
package com.example.login;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
public class UserInfoUtils {
public static boolean saveInfo(Context context, String username,String pwd) {
try {
String path = context.getFilesDir().getPath();//帮我们在包名目录下生成一个目录files
System.out.println(path);
String result=username+"##"+pwd;
//创建文件(确定输出位置)
File file=new File(path,"info.txt");
//创建输出流
FileOutputStream fos=new FileOutputStream(file);
//输出(写)文件
fos.write(result.getBytes());
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static Map<String, String> read(Context context) {
try {
Map<String, String> maps=new HashMap<String, String>();
String path = context.getFilesDir().getPath();
File file=new File(path,"info.txt");
FileInputStream fis=new FileInputStream(file);
BufferedReader bfr=new BufferedReader(new InputStreamReader(fis));
String content=bfr.readLine();//读一行
String[] splits = content.split("##");
maps.put("name",splits[0]);
maps.put("pwd", splits[1]);
fis.close();
return maps;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
写法3:彻底告别IO流
String path = context.getFilesDir().getPath();
File file=new File(path,"info.txt");
FileInputStream fis=new FileInputStream(file);上面3行可以缩减为下面一行
FileInputStream fis = context.openFileInput("infoo.txt");
UserInfoUtils.java
package com.example.login;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
public class UserInfoUtils {
public static boolean saveInfo(Context context, String username,String pwd) {
try {
String result=username+"##"+pwd;
//创建输出流
FileOutputStream fos=context.openFileOutput("infoo.txt",context.MODE_PRIVATE);
//输出(写)文件
fos.write(result.getBytes());
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static Map<String, String> read(Context context) {
try {
Map<String, String> maps=new HashMap<String, String>();
/*String path = context.getFilesDir().getPath();
File file=new File(path,"info.txt");
FileInputStream fis=new FileInputStream(file);*/
//context特别强大,一下一行比上上面三行
FileInputStream fis = context.openFileInput("infoo.txt");
BufferedReader bfr=new BufferedReader(new InputStreamReader(fis));
String content=bfr.readLine();//读一行
String[] splits = content.split("##");
maps.put("name",splits[0]);
maps.put("pwd", splits[1]);
fis.close();
return maps;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
其他不变
写法4:写到sdcard
加权限:android.permission.WRITE_EXTERNAL_STORAGE
原始方案下修改
UserInfoUtils.java
package com.example.login;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class UserInfoUtils {
public static boolean saveInfo(String username,String pwd) {
try {
String result=username+"##"+pwd;
//创建文件(确定输出位置)
File file=new File("/mnt/sdcard/info2.txt");
//创建输出流
FileOutputStream fos=new FileOutputStream(file);
//输出(写)文件
fos.write(result.getBytes());
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static Map<String, String> read() {
try {
Map<String, String> maps=new HashMap<String, String>();
File file=new File("/mnt/sdcard/info2.txt");
FileInputStream fis=new FileInputStream(file);
BufferedReader bfr=new BufferedReader(new InputStreamReader(fis));
String content=bfr.readLine();//读一行
String[] splits = content.split("##");
maps.put("name",splits[0]);
maps.put("pwd", splits[1]);
fis.close();
return maps;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
逍遥模拟器可能将sdcard砍掉了,因此eclipse里查看不到
写法5:写到sdcard,Environment告别硬编码
String sdpath = Environment.getExternalStorageDirectory().getPath();//获取sdcard路径
UserInfoUtils.java
package com.example.login;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import android.os.Environment;
public class UserInfoUtils {
public static boolean saveInfo(String username,String pwd) {
try {
String result=username+"##"+pwd;
//创建文件(确定输出位置)
String sdpath = Environment.getExternalStorageDirectory().getPath();
File file=new File(sdpath,"info2.txt");
//创建输出流
FileOutputStream fos=new FileOutputStream(file);
//输出(写)文件
fos.write(result.getBytes());
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static Map<String, String> read() {
try {
Map<String, String> maps=new HashMap<String, String>();
String sdpath = Environment.getExternalStorageDirectory().getPath();
File file=new File(sdpath,"info2.txt");
FileInputStream fis=new FileInputStream(file);
BufferedReader bfr=new BufferedReader(new InputStreamReader(fis));
String content=bfr.readLine();//读一行
String[] splits = content.split("##");
maps.put("name",splits[0]);
maps.put("pwd", splits[1]);
fis.close();
return maps;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
写法6:SharedPreferences存取简单数据★
十分简单,工具类没有了,就一个MainActivity.java
MainActivity.java
package com.example.login;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.example.sp.R;
public class MainActivity extends Activity {
private EditText et_name;
private EditText et_pwd;
private CheckBox cb_check;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name = (EditText) findViewById(R.id.et_username);
et_pwd = (EditText) findViewById(R.id.et_password);
cb_check = (CheckBox) findViewById(R.id.cb_ischeck);
//sp的xml中读取出数据
SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
//读直接取即可 不需要edit
String name=sp.getString("name","");
String pwd = sp.getString("pwd", "");
//直接展示 没有默认值都设置为空""了嘛
et_name.setText(name);
et_pwd.setText(pwd);
}
public void login(View v){
String username = et_name.getText().toString().trim();
String pwd = et_pwd.getText().toString().trim();
if(TextUtils.isEmpty(username)||TextUtils.isEmpty(pwd)){
Toast.makeText(this, "用户名或密码不能为空!", 0).show();
}else{
System.out.println("连接服务器中...");
if(cb_check.isChecked()){
//getSharedPreferences(name, mode);
/**
* 文件以xml格式存储
* name:xml文件名
* mode:模式 eg:MODE_PRIVATE(0) 私有的
*/
//获取sp (创建xml)
SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
//获取sp编辑器
Editor edit = sp.edit();
//利用编辑器往xml里存值 (写xml)
edit.putString("name", username);
edit.putString("pwd", pwd);
//一定记得提交 java没法写得像c#那么好,跨平台不能写死
edit.commit();
Toast.makeText(this, "保存成功!", 0).show();
}else{
System.out.println("未保存密码!");
}
}
}
}
改进:sp直接做一个成员变量
package com.example.login;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.example.sp.R;
public class MainActivity extends Activity {
private EditText et_name;
private EditText et_pwd;
private CheckBox cb_check;
private SharedPreferences sp;// 获取sp (创建xml)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//java不能写死 设计上相比于C#就太丑了.....写些机械冗余的代码
et_name = (EditText) findViewById(R.id.et_username);
et_pwd = (EditText) findViewById(R.id.et_password);
cb_check = (CheckBox) findViewById(R.id.cb_ischeck);
sp = getSharedPreferences("config", MODE_PRIVATE);
// 读直接取即可 不需要edit
String name = sp.getString("name", "");
String pwd = sp.getString("pwd", "");
// 直接展示 没有默认值都设置为空""了嘛
et_name.setText(name);
et_pwd.setText(pwd);
}
public void login(View v) {
String username = et_name.getText().toString().trim();
String pwd = et_pwd.getText().toString().trim();
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(pwd)) {
Toast.makeText(this, "用户名或密码不能为空!", 0).show();
} else {
System.out.println("连接服务器中...");
if (cb_check.isChecked()) {
// 获取sp编辑器
Editor edit = sp.edit();
// 利用编辑器往xml里存值 (写xml)
edit.putString("name", username);
edit.putString("pwd", pwd);
// 一定记得提交 java没法写得像c#那么好,跨平台不能写死
edit.commit();
Toast.makeText(this, "保存成功!", 0).show();
} else {
System.out.println("未保存密码!");
}
}
}
}
生成xml文件存储数据
格式如下
改进2:记住cb_checked选中状态
package com.example.login;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.example.sp.R;
public class MainActivity extends Activity {
private EditText et_name;
private EditText et_pwd;
private CheckBox cb_check;
private SharedPreferences sp;// 获取sp (创建xml)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//java不能写死 设计上相比于C#就太丑了.....写些机械冗余的代码
et_name = (EditText) findViewById(R.id.et_username);
et_pwd = (EditText) findViewById(R.id.et_password);
cb_check = (CheckBox) findViewById(R.id.cb_ischeck);
sp = getSharedPreferences("config", MODE_PRIVATE);
// 读直接取即可 不需要edit
String name = sp.getString("name", "");
String pwd = sp.getString("pwd", "");
// 直接展示 没有默认值都设置为空""了嘛
et_name.setText(name);
et_pwd.setText(pwd);
//TODO 记忆选中状态
cb_check.setChecked(sp.getBoolean("checked", false));
}
public void login(View v) {
String username = et_name.getText().toString().trim();
String pwd = et_pwd.getText().toString().trim();
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(pwd)) {
Toast.makeText(this, "用户名或密码不能为空!", 0).show();
} else {
System.out.println("连接服务器中...");
// 获取sp编辑器
Editor edit = sp.edit();
if (cb_check.isChecked()) {
// 利用编辑器往xml里存值 (写xml)
edit.putString("name", username);
edit.putString("pwd", pwd);
edit.putBoolean("checked", true);
// 一定记得提交 java没法写得像c#那么好,跨平台不能写死
edit.commit();
Toast.makeText(this, "保存成功!", 0).show();
} else {
edit.putBoolean("checked", false);
edit.commit();
Toast.makeText(this, "未保存密码!", 0).show();
}
}
}
}
SharedPreferences很重要:
SharedPreferences详细学习使用
xml序列化:自定义生成xml(备份短信到xml)
设计备份短信xml格式如下:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<smss>
<sms>
<address>110</address>
<body>你被捕了</body>
<date>2020</date>
</sms>
<sms>
<address>120</address>
<body>来医院一趟</body>
<date>2019</date>
</sms>
</smss>
今天暂时取不出来,学到四大组件最后一个内容提供者(content provider)才行,今天只能模拟
小得1:
Android四大组件分别为activity、service、content provider、broadcast receiver。
第七章不考那么就考最简单的两大组件activity和content了,前3天正好讲这些
小结1:
padding : 控件内容相对于控件边框的距离
margin: 控件之间的距离
来源:CSDN
作者:树叶子_
链接:https://blog.csdn.net/hza419763578/article/details/103535043