Android之数据存储共享参数简单用户登录(一)
来源:互联网 发布:国际数据分析师证书 编辑:程序博客网 时间:2024/06/04 23:24
App存储数据,可以存储在数据库(database),文件(file),参数引用(preferences),内部或者外部可移除存储(sd卡)
有五种存储方式:
①SharedPreferences(是一个接口)
使用共享参数,SharedPreferences类提供了一个可以让我们保存或者保存数据持久化的数据类型,这种数据是key-value键值对应类型的。保存的基本数据类型:boolean,float,int.long,string.
为了获得SharedPreferences对象可以使用任何一种方法:getSharedPreferences()或者getPreferences()
getSharedPreferences()这种方法的共享参数是通过标识符来命名的文件,这个文件是被多个应用程序访问的。
getPreferences()这种共享参数的文件只是给你的当前的Activity访问。
步骤:
1.调用edit(),得到SharedPreferences.Editor
2.把这个values值添加到putBoolean()和putString()里面
3.调用commit()方法
新建工程android_data_storage
这里要用到单元测试(复习):添加单元测试的包和单元测试的约束
双击AndroidManifest.xml->Instrumentation->Add 双击Instrumentation后ok->Name Browse->输入框中点击一下,等待搜索,选中Instrumentation TestRunner点击ok->Target Package Browse 选中自己的工程名中的包,点击ok->点击AndroidManifest.xml中的application节点中添加<uses-library android:name="android.test.runner"/>保存。接下来就可以使用单元测试了
在工程中新建包com.example.android_data_storage.sharepreference下创建类LoginService.java
(在qq的登陆界面有隐身,离线,忙碌等选项,如果选中登录,下次登录的时候就会勾上,这种功能的实现就是使用共享参数来实现的。)
如果第一次登陆成功,就可以把用户名和密码保存在本地,下次再登录的时候,匹配本地的账号就不需要再匹配服务器的数据了,省去一个中间环节。
SharedPreferences是一个接口,把一个临时的信息保存在一个文件里面,这个文件是以.xml作为扩展名。getSharedPreferences(String name,int mode)方法,接收的是一个文件名,返回一个共享参数的对象,仅仅用单例模式提供了一个文件,意味着每一个编辑都可以得到这个编辑的对象来修改。
name:如果这个文件不存在,当调用edit()方法时会帮我们创建,并且当commit()方法时数据发生改变。文件不要加后缀名,系统自动以.xml文件形式保存。
mode:文件操作的权限模式。MODE_PRIVATE表示只有当前的Activity才有权限访问文件。如果想让某个文件既可读又可写则用“+”把两个权限相加。
package com.example.android_data_storage.sharepreference;import android.content.Context;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;public class LoginService {private Context context;public LoginService(Context context) {// TODO Auto-generated constructor stubthis.context=context;}public boolean saveLoginMsg(String name,String password){boolean flag=false;//文件名不要加后缀名,系统会自动以.xml的文件保存SharedPreferences preferences=context.getSharedPreferences("login", Context.MODE_PRIVATE);Editor editor=preferences.edit();editor.putString("username", name);editor.putString("password", password);flag=editor.commit();//只有调用commit方法才会把传回来的参数保存在文件上return flag;}}
在com.example.android_data_storage中写一个MyTest类继承android.test.AndroidTestCase
package com.example.android_data_storage;import com.example.android_data_storage.sharepreference.LoginService;import android.test.AndroidTestCase;import android.util.Log;public class MyTest extends AndroidTestCase {private final String TAG="MyTest";public MyTest() {// TODO Auto-generated constructor stub}public void save(){LoginService service=new LoginService(getContext());boolean flag=service.saveLoginMsg("admin", "123");Log.i(TAG, "---->"+flag);}}
双击save()方法,右键Run As ->Android JUnit Test进行单元测试,出现如下界面
在File Explorer下的data->data中找到工程名,会看到里面有个login.xml文件
把login.xml文件导出来,打开看到如下
封装成工具类:在LoginService.java中添加方法saveSharedPreferences
/** * * @param fileName * @param map * @return */public boolean saveSharedPreferences(String fileName,Map<String, Object> map){boolean flag=false;SharedPreferences preferences=context.getSharedPreferences(fileName, Context.MODE_PRIVATE);Editor editor=preferences.edit();for(Map.Entry<String, Object> entry:map.entrySet()){String key=entry.getKey();Object object=entry.getValue();if(object instanceof Boolean){Boolean new_name=(Boolean) object;editor.putBoolean(key, new_name);}else if(object instanceof Integer){Integer integer =(Integer)object;editor.putInt(key, integer);}else if(object instanceof Float){Float f=(Float) object;editor.putFloat(key, f);}else if(object instanceof Long){Long l=(Long) object;editor.putLong(key, l);}else if(object instanceof String){String s=(String) object;editor.putString(key, s);}}flag=editor.commit();return flag;}在MyTest.java添加测试方法save2()测试
public void save2(){LoginService service=new LoginService(getContext());Map<String, Object> map=new HashMap<String, Object>();map.put("name", "CCNU");map.put("age", 123);map.put("salary", 3500.1f);map.put("id", 123456789l);map.put("isMale",true);boolean flag=service.saveSharedPreferences("msg", map);Log.i(TAG, "---->"+flag);}
双击save2()方法,右键Run As ->Android JUnit Test进行单元测试,出现如下界面
同样在File Explorer多了一个文件msg.xml
导出msg.xml并打开看到如下
这个工具类其实在开发当中不用写,直接拿来用就行了。至此,数据文件已经能保存进来。接下来就是怎么取数据文件?
在LoginService.java中添加读取数据文件的方法getSharePreference
public Map<String, ?> getSharePreference(String fileName) {Map<String, ?> map = null;SharedPreferences preferences = context.getSharedPreferences(fileName,Context.MODE_PRIVATE);map = preferences.getAll();return map;}
在MyTest.java中添加测试方法read()
public void read() {LoginService service = new LoginService(getContext());Map<String, ?> map = service.getSharePreference("msg");Log.i(TAG, "--->" + map.get("name"));Log.i(TAG, "--->" + map.get("age"));Log.i(TAG, "--->" + map.get("salary"));Log.i(TAG, "--->" + map.get("id"));Log.i(TAG, "--->" + map.get("isMale"));}
双击read()方法,右键Run As ->Android JUnit Test进行单元测试,出现如下界面
<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.example.android_data_storage.MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginTop="16dp" android:text="用户名:" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView1" android:layout_alignBottom="@+id/textView1" android:layout_toRightOf="@+id/textView1" android:ems="10" > </EditText> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1" android:layout_below="@+id/editText1" android:layout_marginTop="25dp" android:text="密码:" /> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView2" android:layout_alignBottom="@+id/textView2" android:layout_alignLeft="@+id/editText1" android:ems="10" android:inputType="textPassword" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView2" android:layout_below="@+id/editText2" android:layout_marginLeft="21dp" android:layout_marginTop="151dp" android:text="登录" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button1" android:layout_alignBottom="@+id/button1" android:layout_alignRight="@+id/editText1" android:layout_marginRight="41dp" android:text="取消" /> <CheckBox android:id="@+id/checkBox1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView2" android:layout_below="@+id/editText2" android:layout_marginTop="21dp" android:text="记住用户名" /> <CheckBox android:id="@+id/checkBox2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/checkBox1" android:layout_alignBottom="@+id/checkBox1" android:layout_alignRight="@+id/button2" android:text="静音登录" /></RelativeLayout>在MainActivity.java写业务逻辑如下
package com.example.android_data_storage;import java.util.HashMap;import java.util.Map;import com.example.android_data_storage.sharepreference.LoginService;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.CheckBox;import android.widget.EditText;public class MainActivity extends ActionBarActivity {private Button button;private EditText editText, editText2;private CheckBox checkBox;// 记住用户名private CheckBox checkBox2;// 静音登录private LoginService service;Map<String, ?> map = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);service = new LoginService(this);button = (Button) this.findViewById(R.id.button1);editText = (EditText) this.findViewById(R.id.editText1);editText2 = (EditText) this.findViewById(R.id.editText2);checkBox = (CheckBox) this.findViewById(R.id.checkBox1);checkBox2 = (CheckBox) this.findViewById(R.id.checkBox2);map = service.getSharePreference("login");//提取数据,第一次进来的时候要读文件if (map != null && !map.isEmpty()) {editText.setText(map.get("username").toString());checkBox.setChecked((Boolean) map.get("isname"));checkBox2.setChecked((Boolean) map.get("isquiet"));}button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubif (editText.getText().toString().trim().equals("admin")) {Map<String, Object> map = new HashMap<String, Object>();if(checkBox.isChecked()){map.put("username", editText.getText().toString().trim());}else{map.put("username", "");}map.put("isname", checkBox.isChecked());map.put("isquiet", checkBox2.isChecked());service.saveSharedPreferences("login", map);}}});}@Overridepublic 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;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();if (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}}
第一次运行界面如下
②Internal Storage
③External Storage
④SQLite Databases
⑤Network Connection
- Android之数据存储共享参数简单用户登录(一)
- Android 数据存储(一) 共享参数存储
- Android 数据存储之 共享参数 SharedPreferences
- android数据存储--共享参数(sharedPreferences)
- 【Android 开发】:数据存储之 SharedPreference 共享参数
- Android 数据存储(二) 共享参数存储
- 数据的存储(一、共享参数 SharedPreferences)
- Android之数据存储共享参数实现系统设置操作功能(二)
- Android数据存储SharedPreferences共享参数
- Android-数据储存:用户登录界面(存储)
- Android学习(19) -- 数据存储之File (简单登录保存用户名和密码)
- Android数据存储和访问之SharedPreferences存储方式_用户登录记住密码案例
- android数据存储(一)之SharedPreferences
- Android应用程序之数据存储(一)
- android开发之数据共享(参数传递)
- Android数据读写之用户登录
- android之数据存储(一)
- Android数据存储之一SharedPreferences共享参数类
- C语言学习笔记----伊能C语言学习笔记-----全局变量
- 深入理解URL
- 为了安装htop 添加源
- 关于webservice的那点事
- Objective-c语言_莫名其妙的错误1
- Android之数据存储共享参数简单用户登录(一)
- voliey下载
- 我对消息中间件的理解
- 4-9汽车加油问题
- android开发java工具包的添加方式
- Hadoop2.4.1学习笔记(二)之hdfs文件系统学习
- Sexy Beach PR 汉化补丁+新手教程
- InnoDB创建数据压缩页
- C#大框架小要素