android登录案例

一、私有目录下存储用户名和密码

项目目录截图:


layout界面:


界面xml代码:

<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: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="com.zgs.login.MainActivity"
    android:orientation="vertical" >
	
    <EditText 
        android:id="@+id/et_username"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/hint_inputname"
        />
    <EditText 
        android:id="@+id/et_password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/hint_inputpassword"
        android:inputType="textPassword"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        />
    
    <RelativeLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >
        
        <CheckBox 
            android:id="@+id/cb_rem"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/rem_password"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            />
        
        <Button 
            android:id="@+id/bt_login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/txt_login"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:paddingLeft="50dp"
            android:paddingRight="50dp"
            android:layout_centerVertical="true"
            />
        
    </RelativeLayout>

</LinearLayout>

MainActivity文件代码:

package com.zgs.login;

import java.util.HashMap;

import com.zgs.login.Util.UserInfoUtil;
import com.zgs.login1.R;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

	private EditText et_username;
	private EditText et_password;
	private CheckBox cb_rem;
	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext = this;
		
		et_username = (EditText) findViewById(R.id.et_username);
		et_password = (EditText) findViewById(R.id.et_password);
		cb_rem = (CheckBox) findViewById(R.id.cb_rem);
		Button bt_login = (Button) findViewById(R.id.bt_login);
		
		bt_login.setOnClickListener(this);
		
		HashMap<String, String> hmap = UserInfoUtil.getUserInfo(mContext);
		if (hmap != null) {
			String username = hmap.get("username");
			String password = hmap.get("password");
			et_username.setText(username);
			et_password.setText(password);
			cb_rem.setChecked(true);
		}
	}
	
	private void login() {
		String username = et_username.getText().toString().trim();
		String password = et_password.getText().toString().trim();
		Boolean isrem = cb_rem.isChecked();
		
		if (TextUtils.isEmpty(username)||TextUtils.isEmpty(password)) {
			Toast.makeText(mContext, "用户名密码不能为空", Toast.LENGTH_SHORT).show();
			return;
		}
		
		if (isrem) {
			Boolean result = UserInfoUtil.saveUserInfo(mContext,username,password);
			
			if (result) {
				Toast.makeText(mContext, "用户名密码保存成功", Toast.LENGTH_SHORT).show();
			}else {
				Toast.makeText(mContext, "用户名密码保存失败", Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.bt_login:
			login();
			break;

		default:
			break;
		}
		
	}

}
UserInfoUtil文件代码(写法一):
package com.zgs.login.Util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

import android.content.Context;

public class UserInfoUtil {

	//保存用户信息
	public static Boolean saveUserInfo(Context mContext, String username,
			String password) {
		try {
			String userinfo = username + "##" + password; //分割用户名和密码
			//String path = "/data/data/com.zgs.login/"; //存储路径,私有目录"/data/data/com.zgs.login/"
			String path=mContext.getFilesDir().getPath(); //存储路径,私有目录"/data/data/com.zgs.login/files"
			File file = new File(path, "userinfo.txt"); //创建file
			FileOutputStream fos = new FileOutputStream(file); //创建文件写入流
			fos.write(userinfo.getBytes()); //将用户名密码写入文件
			fos.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	//读取用户信息
	public static HashMap<String, String> getUserInfo(Context mContext) {
		try {
			//String path = "/data/data/com.zgs.login/";
			String path=mContext.getFilesDir().getPath(); //存储路径,私有目录"/data/data/com.zgs.login/files"
			File file = new File(path,"userinfo.txt");
			FileInputStream fis = new FileInputStream(file);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));
			//读取一行中包含用户密码,需要解析
			String readLine = bufferedReader.readLine();
			String[] split = readLine.split("##");
			HashMap<String, String> hashMap = new HashMap<String ,String>();
			hashMap.put("username", split[0]);
			hashMap.put("password", split[1]);
			bufferedReader.close();
			fis.close();
			return hashMap;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

UserInfoUtil文件代码(写法二):

package com.zgs.login.Util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

import android.content.Context;

public class UserInfoUtil {

	//保存用户信息
	public static Boolean saveUserInfo_android(Context mContext, String username,
			String password) {
		try {
			String userinfo = username + "##" + password; //分割用户名和密码
			//得到私有目录下一个文件写入流; name : 私有目录文件的名称    mode: 文件的操作模式, 私有,追加,全局读,全局写
			FileOutputStream fos = mContext.openFileOutput("userinfo.txt", Context.MODE_PRIVATE);
			fos.write(userinfo.getBytes()); //将用户名密码写入文件
			fos.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	//读取用户信息
	public static HashMap<String, String> getUserInfo_android(Context mContext) {
		try {
			FileInputStream fis = mContext.openFileInput("userinfo.txt");
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));
			//读取一行中包含用户密码,需要解析
			String readLine = bufferedReader.readLine();
			String[] split = readLine.split("##");
			HashMap<String, String> hashMap = new HashMap<String ,String>();
			hashMap.put("username", split[0]);
			hashMap.put("password", split[1]);
			bufferedReader.close();
			fis.close();
			return hashMap;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

二、sdcard目录下存储用户名和密码

项目目录截图:


layout界面和对应的xml代码和上面项目一致,就不再重复了。

MainActivity文件代码:

package com.zgs.login;

import java.io.File;
import java.util.HashMap;

import com.zgs.login.Util.UserInfoUtil;
import com.zgs.login_sdcard1.R;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

	private EditText et_username;
	private EditText et_password;
	private CheckBox cb_rem;
	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext = this;
		
		et_username = (EditText) findViewById(R.id.et_username);
		et_password = (EditText) findViewById(R.id.et_password);
		cb_rem = (CheckBox) findViewById(R.id.cb_rem);
		Button bt_login = (Button) findViewById(R.id.bt_login);
		
		bt_login.setOnClickListener(this);
		
		HashMap<String, String> hmap = UserInfoUtil.getUserInfo(mContext);
		if (hmap != null) {
			String username = hmap.get("username");
			String password = hmap.get("password");
			et_username.setText(username);
			et_password.setText(password);
			cb_rem.setChecked(true);
		}
	}
	
	private void login() {
		String username = et_username.getText().toString().trim();
		String password = et_password.getText().toString().trim();
		Boolean isrem = cb_rem.isChecked();
		
		if (TextUtils.isEmpty(username)||TextUtils.isEmpty(password)) {
			Toast.makeText(mContext, "用户名密码不能为空", Toast.LENGTH_SHORT).show();
			return;
		}
		
		if (isrem) {
			
			//判断Sdcard状态是否正常
			if(!Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)){
				//sdcard状态是没有挂载的情况
				Toast.makeText(mContext, "sdcard不存在或未挂载", Toast.LENGTH_SHORT).show();
				return;
			}
			
			//判断sdcard存储空间是否满足文件的存储
			File sdcard_filedir = Environment.getExternalStorageDirectory();//得到sdcard的目录作为一个文件对象
			long usableSpace = sdcard_filedir.getUsableSpace();//获取文件目录对象剩余空间
			//long totalSpace = sdcard_filedir.getTotalSpace();//获取文件目录对象总空间
			//将一个long类型的文件大小格式化成用户可以看懂的M,G字符串
			String usableSpace_str = Formatter.formatFileSize(mContext, usableSpace);
			//String totalSpace_str = Formatter.formatFileSize(mContext, totalSpace);
			if(usableSpace < 1024 * 1024 * 200){//判断剩余空间是否小于200M
				Toast.makeText(mContext, "sdcard剩余空间不足,无法满足下载;剩余空间为:"+usableSpace_str, Toast.LENGTH_SHORT).show();
				return ;	
			}
			
			Boolean result = UserInfoUtil.saveUserInfo(mContext,username,password);
			
			if (result) {
				Toast.makeText(mContext, "用户名密码保存成功", Toast.LENGTH_SHORT).show();
			}else {
				Toast.makeText(mContext, "用户名密码保存失败", Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.bt_login:
			login();
			break;

		default:
			break;
		}
		
	}

}
UserInfoUtil文件代码:
package com.zgs.login.Util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

import android.content.Context;
import android.os.Environment;

public class UserInfoUtil {

	//保存用户信息
	public static Boolean saveUserInfo(Context mContext, String username,
			String password) {
		try {
			String userinfo = username + "##" + password; //分割用户名和密码
			//String path="/mnt/sdcard/";
			String path = Environment.getExternalStorageDirectory().getPath();
			File file = new File(path, "userinfo.txt"); //创建file
			FileOutputStream fos = new FileOutputStream(file); //创建文件写入流
			fos.write(userinfo.getBytes()); //将用户名密码写入文件
			fos.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	//读取用户信息
	public static HashMap<String, String> getUserInfo(Context mContext) {
		try {
			//String path="/mnt/sdcard/";
			String path = Environment.getExternalStorageDirectory().getPath();
			File file = new File(path,"userinfo.txt");
			FileInputStream fis = new FileInputStream(file);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));
			//读取一行中包含用户密码,需要解析
			String readLine = bufferedReader.readLine();
			String[] split = readLine.split("##");
			HashMap<String, String> hashMap = new HashMap<String ,String>();
			hashMap.put("username", split[0]);
			hashMap.put("password", split[1]);
			bufferedReader.close();
			fis.close();
			return hashMap;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
三、sdcard注意事项
1.权限问题:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2.硬性编码问题:通过 Environment可以获取sdcard的路径
Environment.getExternalStorageDirectory().getPath();
3.使用前需要判断sdcard状态

if(!Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)){
//sdcard状态是没有挂载的情况
Toast.makeText(mContext, "sdcard不存在或未挂载", Toast.LENGTH_SHORT).show();
return ;
}
4.需要判断sdcard剩余空间
//判断sdcard存储空间是否满足文件的存储
File sdcard_filedir = Environment.getExternalStorageDirectory();//得到sdcard的目录作为一个文件对象
long usableSpace = sdcard_filedir.getUsableSpace();//获取文件目录对象剩余空间
long totalSpace = sdcard_filedir.getTotalSpace();
//将一个long类型的文件大小格式化成用户可以看懂的M,G字符串
String usableSpace_str = Formatter.formatFileSize(mContext, usableSpace);
String totalSpace_str = Formatter.formatFileSize(mContext, totalSpace);
if(usableSpace < 1024 * 1024 * 200){//判断剩余空间是否小于200M
Toast.makeText(mContext, "sdcard剩余空间不足,无法满足下载;剩余空间为:"+usableSpace_str, Toast.LENGTH_SHORT).show();
return ;
四、私有目录和sdcard区别
/data/data: context.getFileDir().getPath();
是一个应用程序的私有目录,只有当前应用程序有权限访问读写,其他应用无权限访问。一些安全性要求比较高的数据存放在该目录,一般用来存放size比较小的数据。
/mnt/sdcard: Enviroment.getExternalStorageDirectory().getPath();

是一个外部存储目录,只用应用声明了<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>的一个权限,就可以访问读写sdcard目录;所以一般用来存放一些安全性不高的数据,文件size比较大的数据。

五、使用SharedPreferences存储与读取数据

sharedPreferences是通过xml文件来做数据存储的,可以放在私有目录:/data/data/包名/shared_prefs下
一般用来存放一些标记性的数据,一些设置信息、偏好信息等

layout界面、对应的xml代码及MainActivity代码和上面项目一致,就不再重复了。

UserInfoUtil文件代码:

package com.zgs.login.Util;
import java.util.HashMap;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class UserInfoUtil {

	//保存用户信息
	public static Boolean saveUserInfo_android(Context mContext, String username,
			String password) {
		try {
			//1.通过Context对象创建一个SharedPreference对象
			//name:sharedpreference文件的名称    mode:文件的操作模式
			//SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);//创建以包名_preference的xml文件
			SharedPreferences sharedPreferences = mContext.getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE); //创建的是xml文件,加txt没有意义
			//2.通过sharedPreferences对象获取一个Editor对象
			Editor editor = sharedPreferences.edit();
			//3.往Editor中添加数据
			editor.putString("username", username);
			editor.putString("password", password);
			//4.提交Editor对象
			editor.commit();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	//读取用户信息
	public static HashMap<String, String> getUserInfo_android(Context mContext) {
		try {
			//1.通过Context对象创建一个SharedPreference对象
			//SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
			SharedPreferences sharedPreferences = mContext.getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
			//2.通过sharedPreference获取存放的数据
			//key:存放数据时的key   defValue: 默认值,根据业务需求来写
			String username = sharedPreferences.getString("username", "");
			String password = sharedPreferences.getString("password", "");
			
			
			HashMap<String, String> hashMap = new HashMap<String ,String>();
			hashMap.put("username",username);
			hashMap.put("password", password);
			return hashMap;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值