保存数据到android的rom空间

android存储空间介绍:

       Rom:相当于一块硬盘(微硬盘)能持久的储存一些数据,如手机掉电,之前的用户数据依然会被保存,,一般空间为1G~32G

       Ram:相当于电脑里面的内存条,掉电不能保存用户数据,运行速度比较快。一般的Ram空间为512M~1G

       SD卡:相当于一个外部的U盘,不是一个必须设备




需求:用户输入用户名和密码后选择保存的位置,rom,cache,SD代表以指定文件格式保存在不同的位置。xml代表把用户输入的数据以xml格式保存。

选择了保存方式,点击记住密码并登陆以后,退出应用,对应的用户名,密码输入框会回显用户之前输入的数据。











要实现的功能如上图,布局文件fragment_main.xml 如下:

<RelativeLayout 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.lenovo.login.MainActivity$PlaceholderFragment" >

    <TextView
        android:id="@+id/text_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/input_login" />
    
    <EditText 
        android:id="@+id/et_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:layout_below="@id/text_login"
        android:hint="@string/username"/>
     <TextView
        android:id="@+id/text_pwd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/et_name"
        android:text="@string/input_pwd" />
    <EditText 
        android:id="@+id/et_pwd"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:layout_below="@id/text_pwd"
        android:hint="@string/password"/>
    
     <RadioGroup 
         android:id="@+id/rg"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:layout_below="@id/et_pwd" >
        
        <RadioButton 
             android:id="@+id/rb_rom"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="@string/rom"/>
        <RadioButton 
             android:id="@+id/rb_cache"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="@string/cache"/>
        <RadioButton
             android:id="@+id/rb_sd" 
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="@string/sd"/>
         <RadioButton
             android:id="@+id/rb_xml" 
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="@string/xml"/>
    </RadioGroup>
    <RelativeLayout 
        android:id="@+id/rl"
         android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/rg">
        <CheckBox 
            android:id="@+id/cb_remeber"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/remember"/>
        <Button 
            android:id="@+id/bt_login"
            android:layout_alignParentRight="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/login_in" />
    </RelativeLayout>
</RelativeLayout>
对应的strings.xml为:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">login</string>
    <string name="action_settings">Settings</string>
    <string name="input_login">请输入用户名</string>
    <string name="username">用户名</string>
    <string name="input_pwd">请输入密码</string>
    <string name="password">密码</string>
    <string name="remember">记住密码</string>
    <string name="login_in">登录</string>
    <string name="msg">用户名或密码不应为空</string>
    <string name="rom">rom</string>
    <string name="cache">cache</string>
    <string name="sd">SD</string>
    <string name="xml">xml</string>
</resources>

保存用户输入数据到rom

public  class FileService {
	/**
	 * save data to phone rom
	 * @param context  上下文
	 * @param fileName  保存的文件名
	 * @param name      用户名
	 * @param password   密码
	 * @return
	 */
   public static boolean saveToRom(Context context,String fileName,String name,String password){
	    // File file = new File("/data/data/cn.itcast.login/a.txt");
	    //相当于存储到/data/dat/packageName/目录下
		File file = new File(context.getFilesDir(), fileName);
		// 如果没有指定访问的模式 ,文件的模式 默认是私有的权限.
		// 只有当前的应用程序可以读写这个文件 ,别的应用程序是不可以操作这个文件.
	   try {
		FileOutputStream fos=new FileOutputStream(file);
		fos.write((name+":"+password).getBytes());
		fos.close();
		return true;
	} catch (Exception e) {
		e.printStackTrace();
		return false;
	}
   }
   
   /**
	 * 保存数据到手机的rom空间的缓存目录
	 * 作用 保存应用程序的临时数据, 在手机内存不足的时候 系统会释放掉这块空间
	 * 用户也可以手工的释放掉这块空间
	 * @param context 上下文
	 * @param filename 保存的文件名
	 * @param name 用户名
	 * @param password 密码
	 * @return
	 */
   public static boolean saveToRomCache(Context context,String fileName,String name,String password){
	    File file=new File(context.getCacheDir(),fileName);///data/dat/packageName/
		   try {
			FileOutputStream fos=new FileOutputStream(file);
			fos.write((name+":"+password).getBytes());
			fos.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
  }
   
   /**
    * sava data to externalStorage【外部存储卡】
    * @param context
    * @param fileName
    * @param name
    * @param password
    * @return
    */
   public static boolean saveToSD(Context context,String fileName,String name,String password){
	    //相当于存储到/mnt/sdcard/目录下
	   //在保存数据到sd卡之前 ,最好判断一下 用户是否有sd卡 sd是否可用.
	    File file=new File(Environment.getExternalStorageDirectory(),fileName);
	    try {
			FileOutputStream fos=new FileOutputStream(file);
			fos.write((name+":"+password).getBytes());
			fos.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
   }
   
   /**
    * 将用户输入的数据以xml文件格式保存到手机rom空间
    * @param context
    * @param name
    * @param password
    * @return
    */
   public static boolean saveToXML(Context context,String name,String password){
	   File file=new File(context.getFilesDir(),"info.xml");
	   try {
		FileOutputStream fos=new FileOutputStream(file);
		XmlSerializer serial=Xml.newSerializer();
		//初始化一下xml的序列化器
		serial.setOutput(fos, "UTF-8");
		serial.startDocument("UTF-8", true);
		serial.startTag(null, "map");
		
		serial.startTag(null, "name");
		serial.text(name);
		serial.endTag(null, "name");
		
		serial.startTag(null, "password");
		serial.text(password);
		serial.endTag(null, "password");
		
		serial.endTag(null, "map");
		serial.endDocument();
		fos.flush();
		fos.close();
		return true;
	} catch (Exception e) {
		e.printStackTrace();
		return false;
	}
   }
   
   /**
    * 从rom文件中读取存储的内容
    * @param context
    * @param fileName
    * @return
    */
   public static Map<String,String>  readFromRom(Context context,String fileName){
	   File file=new File(context.getFilesDir(),fileName);
	   try {
		FileInputStream fis=new FileInputStream(file);
		byte[] result=StreamTools.getBytes(fis);
		String[] data=new String(result).split(":");
		String name=data[0];
		String password=data[1];
		Map<String,String> map=new HashMap<String, String>();
		map.put("name", name);
		map.put("password", password);
		return map;
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
   }
 }

普通方式读取保存在文件中的数据工具类:

public class StreamTools {
	/**
	 * 把一个输入流里的内容转化存放在一个byte数组里面
	 * @param is
	 * @return
	 * @throws Exception
	 */
   public static byte[] getBytes(InputStream is) throws Exception{
	   ByteArrayOutputStream baos=new ByteArrayOutputStream();
	   byte[] buffer=new byte[1024];
	   int len=0;
	   while((len=is.read(buffer))!=-1){
		   baos.write(buffer,0,len);
	   }
	   is.close();
	   return baos.toByteArray();
   }
}

MainActivity.java

public class MainActivity extends Activity implements OnClickListener {
    private EditText et_name;
    private EditText et_pwd;
    private CheckBox cb_remember;
    private Button bt_login;
    private RadioGroup rg;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_main);

		et_name=(EditText) findViewById(R.id.et_name);
		et_pwd=(EditText) findViewById(R.id.et_pwd);
		cb_remember=(CheckBox) findViewById(R.id.cb_remeber);
		bt_login=(Button) findViewById(R.id.bt_login);
		
		rg=(RadioGroup) findViewById(R.id.rg);
	//回显之前用户输入的数据到对象的文本编辑框	
//		Map<String, String> map=FileService.readFromRom(this, "rom.txt");
//		if(map!=null){
//			String name=map.get("name");
//			String pwd=map.get("pwd");
//			et_name.setText(name);
//			et_pwd.setText(pwd);
//		}
		//用sharedpreference获取保存在xml中的数据
		SharedPreferences sp=getSharedPreferences("xml", MODE_PRIVATE);
		String name=sp.getString("name", "");
		String pwd= sp.getString("password", "");
		et_name.setText(name);
	    et_pwd.setText(pwd);
		bt_login.setOnClickListener(this);
	}
	@Override
	public void onClick(View v) {
		if(v==bt_login){
			String name=et_name.getText().toString().trim();
			String pwd=et_pwd.getText().toString().trim();
			if(TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)){
				Toast.makeText(this, R.string.msg, 0).show();
			    return;
			}
			//if checked,save name and password
			if(cb_remember.isChecked()){
				int id=rg.getCheckedRadioButtonId();
				if(id==-1)
					//if does not check any radioButton,default the data on rom
					id=R.id.rb_rom;
				boolean result=false;
				switch (id) {
				case R.id.rb_rom:
					result=FileService.saveToRom(this,"rom.txt",name, pwd);
					break;
                case R.id.rb_cache:
                	result=FileService.saveToRomCache(this,"cache.txt",name, pwd);
					break;
                case R.id.rb_sd:
                	//get externalStorage's state,sdCard is or not available
                	if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
                		result=FileService.saveToSD(this, "sd.txt", name, pwd);
                	}else{
                		Toast.makeText(this, "sd卡不可用,请检查sd卡状态", 0).show();
                	}
	            break;
                case R.id.rb_xml:
                	//以前保存数据到xml文件的写法
//                  result=FileService.saveToXML(this, name, pwd);
                	//sharedPreference用于保存用户输入的数据到xml文件
                	
                	SharedPreferences sp=getSharedPreferences("xml", MODE_PRIVATE);
                	//获取一个SharedPreferences编辑器
                	Editor editor=sp.edit();
                	editor.putString("name", name);
                	editor.putString("password", pwd);
                	editor.commit();
                	result = true;
                	break;
				}
				if(result){
					Toast.makeText(this, "保存成功", 0).show();
				}else{
					Toast.makeText(this, "保存失败", 0).show();
				}
			}
			if("zhangsan".equals(name)&&"123".equals(pwd)){
				Toast.makeText(this, "登录成功", 0).show();
			}else{
				Toast.makeText(this, "登录失败", 0).show();
			}
		}
	}
}
在AndroidManifest.xml中需要加入写入数据到外部存储卡的权限:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.lenovo.login"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.lenovo.login.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值