android中的存储问题

来源:互联网 发布:xbox你的网络尚未设置 编辑:程序博客网 时间:2024/05/18 02:25

SharedPreferences存储

 

ShardPreferences 是android 上的一个轻量级存储类,主要用来存储应用程序的一些参数,例如用户名、密码等

使用ShardPreferences 类存储数据时,首先需要通过 content.getShardPreferences (String name,int mode)获取ShardPreferences 对象,如果不是在Activity 中则需要传入一个Content(用来获取上下文)

使用ShardPreferences 存储数据时,需要先获取ShardPreferences  对象 ,通过该对象获取 Editor 对象,然后通过Editor相关方法存储数据

SharedPreferences sp = context.getSharedPreferences("date",Context.MODE_APPEND);

        SharedPreferences.Editor editor = sp.edit();
        editor.putString("username",number);
        editor.putString("pwd",password);
        editor.commit();

使用ShardPreferences获取数据

SharedPreferences sp = context.getSharedPreferences("dte",Context.MODE_APPEND);
        String number = sp.getString("username",null);
        String password = sp.getString("pwd",null);

使用ShardPreferences 删除数据

SharedPreferences sp = context.getSharedPreferences("date",Context.MODE_APPEND);

        SharedPreferences.Editor editor = sp.edit();

editor.remove("pwd",password);//删除一条数据

editor.clear();//清除所有数据
editor.commit();

案例:QQ登陆

1.布局文件

<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"
    android:orientation="vertical"
    tools:context="com.example.review_memory.Main3Activity"
>

    <ImageView
        android:layout_gravity="center_horizontal"
        android:id="@+id/iv_head"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginTop="40dp"
        android:src="@mipmap/ic_launcher"
/>

    <LinearLayout
        android:orientation="vertical"
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"
>

        <RelativeLayout
            android:id="@+id/rl_username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
>

            <TextView
                android:id="@+id/tv_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:text="账号"
/>

            <EditText
                android:id="@+id/et_name"
                android:layout_marginLeft="5dp"
                android:layout_toRightOf="@+id/tv_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@null"
/>

        </RelativeLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="#e6e6e6"
></View>

        <RelativeLayout
            android:id="@+id/rl_userpsw"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
>

            <TextView
                android:id="@+id/tv_psw"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:text="密码"
/>

            <EditText
                android:id="@+id/et_psw"
                android:layout_marginLeft="5dp"
                android:layout_toRightOf="@+id/tv_psw"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@null"
/>

        </RelativeLayout>

    </LinearLayout>

    <Button
        android:id="@+id/bt_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="20dp"
        android:background="#3c8dc4"
        android:text="登陆"
        android:onClick="login"
        android:textColor="#ffffff"
/>



</LinearLayout>

 

2.MainActivity

public class Main3Activityextends AppCompatActivity  {

    private EditText  etNumber;
    private EditText etPassword;
    @Override
    protected voidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);

        etNumber = (EditText) findViewById(R.id.et_name);
        etPassword = (EditText) findViewById(R.id.et_psw);

        //取出号码
        
Map<String,String> userInfo = Utils.getUserInfo(this);
        if (userInfo != null){
            //显示在桌面上
            
etPassword.setText(userInfo.get("number"));
            etNumber.setText(userInfo.get("passsword"));
        }
    }

    public void login(View view){
        //当单击按钮时,获取用户名和密码
        
String number = etNumber.getText().toString();
        String password = etPassword.getText().toString();
        //检查号码和密码是否正确
        
if(TextUtils.isEmpty(number)){
            Toast.makeText(this,"请输入QQ号码",Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(password)){
            Toast.makeText(this,"请输入QQ密码",Toast.LENGTH_SHORT).show();
            return;
        }

        //登陆成功
        
Toast.makeText(this,"登陆成功",Toast.LENGTH_SHORT).show();
        //如果正确,判断是否勾选了记住密码
        
Log.d("Main","记住密码"+"number"+password);

        boolean isSaveSuccess = Utils.saveUserInfo(this,number,password);
        if (isSaveSuccess){
            Toast.makeText(this,"保存失败",Toast.LENGTH_SHORT).show();
        }
        else {
            Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
        }
    }
}

 

3.工具类Utils

public class Utils {
    public static boolean saveUserInfo(Context context,String number,String password){

        SharedPreferences sp = context.getSharedPreferences("date",Context.MODE_APPEND);

        SharedPreferences.Editor editor = sp.edit();
        editor.putString("username",number);
        editor.putString("pwd",password);
        editor.commit();
        return true;
    }

    public static Map<String,String> getUserInfo(Context context){
        SharedPreferences sp = context.getSharedPreferences("dte",Context.MODE_APPEND);
        String number = sp.getString("username",null);
        String password = sp.getString("pwd",null);
        Map<String,String > userMap = newHashMap<String,String>();
        userMap.put("number",number);
        userMap.put("passsword",password);

        return userMap;
    }
}

 

XML序列化

上面提到了ShardPreferences ,ShardPreferences 本质上是一个XML 文件,那么久不可避免的要了解一下XML

案例:XML序列化

1.布局文件

<Button
    android:gravity="center"
    android:text="序列化文件"
    android:id="@+id/button"
    android:onClick="Serializer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
/>

 

 

2.Person类

 

public class PersonInfo {
    private String name;
    private Integer age;
    private Integer score;

    public PersonInfo(String name,Integer age,Integer score){
        super();
        this.age= age;
        this.name= name;
        this.score= score;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name= name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age= age;
    }

    public Integer getScore() {
        return score;
    }

    public void setScore(Integer score) {
        this.score= score;
    }
}

 

3.MainActivity

 

 public class Main2Activityextends AppCompatActivity {

     private List<PersonInfo>personInfoList;
     private TextView textView;
    @Override
    protected voidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        textView  = (TextView) findViewById(R.id.text_view2);
        Initdate();
    }

     public void Initdate(){
         personInfoList =new ArrayList<>();
         for (inti=0;i<3;i++){
             personInfoList.add(newPersonInfo("wang"+(char)i,i*i-2*i,10*i));
         }
     }

     public void Serializer(View view){
         try {
             XmlSerializer serializer = Xml.newSerializer();
             File file = new File(Environment.getExternalStorageDirectory(),"person.xml");
             FileOutputStream fos = new FileOutputStream(file);
             serializer.setOutput(fos,"utf-8");
             serializer.startDocument("utf-8",true);
             serializer.startTag(null,"persons");
             int count =0;
             for(PersonInfo person :personInfoList){
                 serializer.startTag(null,"person");
                 serializer.attribute(null,"id",count+"");
                 //将 person 对象的 age 属性 写入 XML 文件中
                 
serializer.startTag(null,"age");
                 serializer.text(String.valueOf(person.getAge()));
                 serializer.endTag(null,"age");
                 //将 person 对象的 name 属性 写入 XML 文件中
                 
serializer.startTag(null,"name");
                 serializer.text(person.getName());
                 serializer.endTag(null,"name");
                 //将 person 对象的 score 属性 写入 XML 文件中
                 
serializer.startTag(null,"score");
                 serializer.text(String.valueOf(person.getScore()));
                 serializer.endTag(null,"score");

                 serializer.endTag(null,"person");
                 count++;
             }

             serializer.endTag(null,"persons");
             serializer.endDocument();
             serializer.flush();
             Toast.makeText(this,"操作成功",Toast.LENGTH_SHORT).show();


         } catch (Exception e) {
             e.printStackTrace();
             Toast.makeText(this,"操作成功",Toast.LENGTH_SHORT).show();
         }
     }
}

 

4.添加权限

 

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 

文件存储

文件存储是以I/O流的形式把数据原封不动的存储到文档中

分为内部存储和外部存储,两者只是存储的位置不同

案例:存储用户信息

1.布局文件

 

 

2.MainActivity

 

public class MainActivityextends AppCompatActivity {

    private TextView textView;
    private EditText editText;
    private Button button_read;
    private  Button button_save;

    @Override
    protected voidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.text_view);
        editText = (EditText) findViewById(R.id.edit_text);
        button_read = (Button) findViewById(R.id.button1);
        button_save = (Button) findViewById(R.id.button2);
     }

    public void read(View view){
        String saveibnfo = editText.getText().toString().trim();
        FileOutputStream fos;
        try {
            fos = openFileOutput("date.txt",MODE_PRIVATE);
            fos.write(saveibnfo.getBytes());
            fos.close();
            Log.d("Main","read: ");
            Toast.makeText(MainActivity.this,"数据保存成功",Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(MainActivity.this,"数据保存失败",Toast.LENGTH_SHORT).show();
        }
    }

    public void save(View view){
        String saveinfo="";
        FileInputStream fis;
        try {
            fis = openFileInput("date.txt");
            byte [] buffer =new byte[fis.available()];
            fis.read(buffer);
            saveinfo = new String(buffer);
            fis.close();
            Log.d("Main","save: ");
            Toast.makeText(MainActivity.this,"数据保存的数据是"+saveinfo,Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

 

 

原创粉丝点击