android学习笔记(五)——android的存储1 sharedpreferences介绍

本文介绍了Android中使用SharedPreferences存储轻量级数据的方法,包括基本用法、数据读取、跨应用数据共享及如何利用DDMS验证数据正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

任何软件或者app都在一定程度上需要数据存储,android提供了sharedpreferences用来存储轻量数据,sharedpreference将数据存储于xml中,位于/data/data/{包名}/shared_prefs下,仿真机可以通过ddms从中取出,下面就来介绍一下
一、sharedpreferences的基本用法——写入
1.毫无疑问,首先需要定义sharedpreferences的对象
sharedpreferences share =getsharedpreferences(“包名”,Context.MODE_PRIVATE),第一个参数为android程序所属的包的名称
第二个参数为存储模式,
MODE_PRIVATE为默认参数,设置为该参数后,写入形式为覆盖式,即新写入的内容会直接覆盖掉原本的内容
MODE_APPEND参数,设置为该参数后,写入形式为追加式,如果文件存在,即会在文件末尾添加新内容,而不会覆盖原本内容,但需注意的是如果tag是相同的,依然会覆盖掉
MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE这两个参数设置后,即可允许别的程序访问本程序的存储数据,第一个是可读,第二个是可写
2.对象创建后,就要获得对象的编辑器
Editor editor=share.edit();之后就可以通过该编辑器写入数据了
editor.putString(“name”,”aaa”);第一个参数为TAG即存储的数据名称,第二个参数是存储的数据,之后用editor.commit()确认即可将数据写入xml存储
完整过程如下:
share=getSharedPreferences(“com.example.ui_demo”,mySelected);
Editor editor=share.edit();//获取编辑器
editor.putString(“name”, name.getText().toString());
editor.putString(“id”,id.getText().toString());
editor.commit();//确认写入
二、数据读取
1.创建对象,和上面的一样
2.直接通过对象获得数据
share.getString(“name”,”“);第一个参数为获取的数据名称,第二个参数为缺省值,如果未取得该名称数据就会返回第二个参数
三、不同应用读取数据
读取不同应用,首先要保证存储模式是MODE_WORLD_READABLE或者MODE_WORLD_WRITEABLE这两种形式,否则另外的应用是无法读取的
具体的读取方法如下
1.定义需要读取数据所在应用的context
context=createPackageContext(“com.example.ui_demo”,Context.CONTEXT_IGNORE_SECURITY);
2定义sharedPreferences对象,通过1中Context来获取
SharedPreferences shared=context.getSharedPreferences(“com.example.ui_demo”, Context.MODE_WORLD_READABLE);
之后的读取过程与同一应用的读取方式一致

四、DDMS的应用
为了印证是否正确写入,如果是仿真机的话就需要用到ddms了,首先点击windows选项,选择Open perspective选项中other,即可打开如下界面,选择DDMS即可
这里写图片描述
之后会跳转到如下界面,选择对应的仿真机后,点击右侧的选项卡到fileExplorer选项卡下,按照之前的目录找到文件,在导出到电脑上进行查看

这里写图片描述
导出方法点击右上角的如下所示图标即可
这里写图片描述

四,示例代码
Shared_prefdemo.java

package com.example.ui_demo;

import java.util.List;

import android.app.Activity;
import android.app.TabActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.TabHost.OnTabChangeListener;

public class SharedP_ref extends Activity {
    private String []str={"Mode_Private","Mode_Append","Mode_WorldRead","Mode_WorldWrite"};
    private Spinner sp;
    private ArrayAdapter<String> arrayAdapter;
    private int mySelected=-1;
    private Button write;
    private Button read;
    private SharedPreferences share;
    private EditText name;
    private EditText id;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_p_ref);
        sp=(Spinner)this.findViewById(R.id.type);
        write=(Button)this.findViewById(R.id.write);
        read=(Button)this.findViewById(R.id.read);
        name=(EditText)this.findViewById(R.id.editName);
        id=(EditText)this.findViewById(R.id.editid);
        arrayAdapter=new ArrayAdapter<String>(SharedP_ref.this,android.R.layout.simple_spinner_item, str);
        //arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp.setAdapter(arrayAdapter);
        sp.setOnItemSelectedListener(new OnItemSelectedListener(){

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int position, long id) {
                // TODO Auto-generated method stub
                String str=arg0.getItemAtPosition(position).toString();
                if(str=="Mode_Private"){
                   mySelected=Context.MODE_PRIVATE;
                }else if(str=="Mode_Append"){
                    mySelected=Context.MODE_APPEND;
                }else if(str=="Mode_WorldRead"){
                    mySelected=Context.MODE_WORLD_READABLE;
                }else if(str=="Mode_WorldWrite"){
                    mySelected=Context.MODE_WORLD_WRITEABLE;
                }else{
                    mySelected=-1;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
                mySelected=-1;
            }

        });
        Mybutton m=new Mybutton();
        write.setOnClickListener(m);
        read.setOnClickListener(m);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.shared_p_ref, menu);
        return true;
    }

    @Override
    public 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);
    }
    public class Mybutton implements OnClickListener{

        @Override
        public void onClick(View vi) {
            // TODO Auto-generated method stub
            if(vi==write){

                if(mySelected!=-1){
                share=getSharedPreferences("com.example.ui_demo",mySelected);
                Editor editor=share.edit();//获取编辑器
                editor.putString("name", name.getText().toString());
                editor.putString("id",id.getText().toString());
                editor.commit();//确认写入
                }else{
                    Toast.makeText(SharedP_ref.this, "未选择type",Toast.LENGTH_LONG).show();
                }
            }else if(vi==read){
                if(mySelected!=-1){
                    share=getSharedPreferences("com.example.ui_demo",mySelected);
                    String names=share.getString("name", "未找到");//若查询不到会返回第二个参数
                    String s=share.getString("id", "未找到");//若查询不到会返回第二个参数
                    Toast.makeText(SharedP_ref.this, names+s,Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(SharedP_ref.this, "未选择type",Toast.LENGTH_LONG).show();
                }
            }
        }

    }
}

xml

<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:orientation="vertical"
    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.ui_demo.SharedP_ref" >

    <TextView
        android:id="@+id/Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name:" >

    </TextView>

    <EditText
        android:id="@+id/editName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="清输入数值" >

    </EditText>
        <TextView
        android:id="@+id/id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="id:" >

    </TextView>

    <EditText
        android:id="@+id/editid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="清输入数值" >

    </EditText>

    <Spinner
        android:id="@+id/type"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:spinnerMode="dropdown" >

    </Spinner>
    <Button  
        android:id="@+id/write"
        android:text="写入"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </Button>
     <Button  
        android:id="@+id/read"
        android:text="读取"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </Button>
</LinearLayout>

otherActivity.java

package com.example.readothershared;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button mybutton=(Button)this.findViewById(R.id.read);

        mybutton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Context context;
                //创建context
                try {
                    context=createPackageContext("com.example.ui_demo",Context.CONTEXT_IGNORE_SECURITY);
                    SharedPreferences shared=context.getSharedPreferences("com.example.ui_demo", Context.MODE_WORLD_READABLE);
                    String name=shared.getString("name", "未获取到");
                    TextView myText=(TextView)MainActivity.this.findViewById(R.id.show);
                    myText.setText(name);
                } catch (NameNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }
        });
    }

    @Override
    public 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;
    }

    @Override
    public 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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值