本文实例为大家分享了Android SharedPreferences保存登录数据的具体代码,供大家参考,具体内容如下
目标效果:
程序运行显示一个登陆框,用户名输入admin,密码输入123456会提示登录成功,如果不是则提示不正确,如果勾选保存用户名,在下一个程序打开时,用户名会自动读取并显示。
1.activity_main.xml页面存放所有的控件,我在每一行都使用了线性布局。
activity_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:layout_marginLeft="20dp" android:layout_marginRight="20dp" tools:context=".SecondActivity" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:orientation="horizontal" > <TextView android:id="@+id/tvName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="用户名:" /> <EditText android:id="@+id/etInputName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="2" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="60dp" android:orientation="horizontal" > <TextView android:id="@+id/tvPass" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="密 码:" /> <EditText android:id="@+id/etInputPass" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="2" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="100dp" android:orientation="horizontal" > <CheckBox android:id="@+id/cbSave" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="false" android:text="保存用户名" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="130dp" android:orientation="horizontal" > <Button android:id="@+id/btLogin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="登录" /> <Button android:id="@+id/btCancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="取消" /> </LinearLayout> </RelativeLayout>2.MainActivity.java页面处理登录和保存数据。
MainActivity.java页面:
3.保存的文件目录可以查看的到,点击右上角进入,找到data->data->当前目录的包名->shared-prefs->新建的文件名
4.另外,点击右上角导出可以暂时保存到桌面,然后选择打开方式可以查看里边信息。
5.还有一点是,当程序在真机上运行时,file explore打不开data文件夹,根据网上的经验,真机先root,然后在手机上装上R.E 管理器(或类似软件),将/data/data的权限修改为可读可写可执行,然后,就可以在eclipse中展开了。
6.SharedPreferences多用于配置信息或者内容较少的数据的保存,当数据量复杂或者较大,还是需要使用数据库。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。