1.Android提供了5中数据存储方式。本章着重讲sharepreferences存储。
sharepreferences是适合存储数据量较轻的数据,比如账号密码等
是以xml文件的形式存储在本地
使用sharepreferences存储数据时,首先要调用getSharepreferences()方法获取sharepreferences的实例对象。最后通过editor对象的putXXX()方法存储数据
实例代码如下:
布局页面:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity2">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Shareprefence信息保存"
android:textSize="20dp"
/>
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="30dp"
android:layout_marginTop="20dp"
>
<EditText
android:id="@+id/zh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="账号"
/>
<EditText
android:id="@+id/mima"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="密码"
/>
</LinearLayout>
<Button android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="保存"
android:textSize="20dp"
android:onClick="click"
/>
</LinearLayout>
Activity:
package com.example.erhao;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
//声明控件
private Button btn;
private EditText zh,mima;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init(){
//找到控件
btn = findViewById(R.id.btn);
zh = findViewById(R.id.zh);
mima = findViewById(R.id.mima);
}
public void click(View view){
String zhanghao =zh.getText().toString();
String mm =mima.getText().toString();
Toast.makeText(MainActivity.this,"账号:"+zhanghao+"\n密码"+mm,Toast.LENGTH_LONG).show();
SharedPreferences sp = getSharedPreferences("文件", MODE_PRIVATE);
SharedPreferences.Editor editor =sp.edit();
editor.putString("zhanghao",zhanghao);
editor.putString("mm",mm);
//提交数据
editor.commit();
}
}
最后存储的文件可以通过Device File Explorer视图中找到data/data目录,并在里面找到相对应的包名