使用SharedPreferences进行数据的存储实例:增删改查联系人界面

本文介绍如何在Android应用中使用SharedPreferences存储联系人信息,包括姓名和电话号码的增删改查操作。通过将信息编码为Base64并保存在shared_prefs目录下,实现了数据的本地持久化。
摘要由CSDN通过智能技术生成

效果描述:

在目标界面中,有两个文本编辑框,用于输入姓名和电话号码。然后有4个按钮,分别是:添加,查询,删除和更新。
该工程下载地址
效果图如下所示:
界面效果图
添加
查找
更新

实现方法

将姓名和电话号码作为一个整体保存到SharedPreferences中,这个过程需要转码,具体如下.

页面布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    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=".MainActivity"
    android:background="@drawable/b1" >

    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginTop="10dp">

        <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="在这里编辑姓名"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/phone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="在这里编辑电话号码"
        android:inputType="phone" />

    </LinearLayout>


    <LinearLayout 
         android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="10dp">

     <Button
        android:id="@+id/find"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="查询" 
        android:layout_marginLeft="10dp"/>

    <Button
        android:id="@+id/add"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="添加" 
        android:layout_marginLeft="30dp"/>


    </LinearLayout>

     <LinearLayout 
         android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="10dp">

     <Button
        android:id="@+id/delate"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="删除" 
        android:layout_marginLeft="10dp"/>

    <Button
        android:id="@+id/refresh"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="更新" 
        android:layout_marginLeft="30dp"/>


    </LinearLayout>

    <View 
        android:layout_marginTop="6dp"
        android:layout_marginLeft="5dp"
        android:layout_width="260dp"
        android:layout_height="2dp"
        android:background="#8ec7e2"/>

    <EditText
        android:id="@+id/show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="在此显示联系人信息"
        android:inputType="textMultiLine" />

</LinearLayout>

保存姓名和电话号码的people类

package com.example.p1;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Map;

public class People implements Serializable
{
    ArrayList<String> names=null;
    ArrayList<String> phones=null;

}

事件响应

package com.example.p1;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Base64;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity 
{
    private static final String FILENAME = "people";
    private static final int MODE = MODE_PRIVATE;
    EditText name,phone=null;
    Button find,add,refresh,delate=null;
    EditText show=null;
    SharedPreferences shared=null;
    People people=new People();
    String showInformation=new String("");

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

        name=(EditText) findViewById(R.id.name);
        phone=(EditText) findViewById(R.id.phone);
        find=(Button) findViewById(R.id.find);
        add=(Button) findViewById(R.id.add);
        refresh=(Button) findViewById(R.id.refresh);
        delate=(Button) findViewById(R.id.delate);
        show=(EditText) findViewById(R.id.show);
        shared=getSharedPreferences(FILENAME, MODE);
        people.names=new ArrayList();
        people.phones=new ArrayList();

        //点击添加按钮,响应响应的动作事件
        add.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View arg0) 
            {
                if(name.getText()!=null && phone.getText()!=null)
                {
                    if(!"".equals(name.getText().toString()) &&!"".equals(phone.getText().toString()))
                    {
                        people.names.add(name.getText().toString());
                        people.phones.add(phone.getText().toString());
                        ByteArrayOutputStream baos=new ByteArrayOutputStream();

                        try
                        {
                            ObjectOutputStream oos=new ObjectOutputStream(baos);
                            oos.writeObject(people);
                            String peopleBase64=new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
                            Editor editor=shared.edit();
                            editor.putString("people", peopleBase64);
                            editor.commit();

                            if("".equals(showInformation))
                            {
                                showInformation=name.getText().toString()+" "+phone.getText().toString()+"\n";
                            }
                            else
                            {
                                showInformation +=name.getText().toString()+" "+phone.getText().toString()+"\n";
                            }

                            show.setText(showInformation);
                            name.setText("");
                            phone.setText("");
                            Toast.makeText(MainActivity.this, "信息添加成功!", Toast.LENGTH_LONG).show();

                        } 
                        catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    else
                    {
                        Toast.makeText(MainActivity.this, "请填写完整!", Toast.LENGTH_LONG).show();
                    }
                }
            }
        });

        //点击查询按钮,响应相应的动作事件
        find.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View arg0) 
            {
                String peopleBase64=shared.getString("people", "none");

                if(name.getText()!=null && phone.getText()!=null)
                {
                    if(!"".equals(name.getText().toString()) && !"".equals(phone.getText().toString()))
                    {
                        String tempName=name.getText().toString();
                        String tempPhone=phone.getText().toString();
                        int flag1=0;
                        int flag2=0;

                        for(int i=0;i<people.names.size();i++)
                        {  
                            String temp=people.names.get(i);
                            if(temp.equals(tempName))
                                flag1=1;
                        }  
                        for(int i=0;i<people.phones.size();i++)
                        {  
                            String temp=people.phones.get(i);
                            if(temp.equals(tempPhone))
                                flag2=1;
                        }  

                        if(flag1==1 && flag2==1)
                            Toast.makeText(MainActivity.this, "查询成功!", Toast.LENGTH_LONG).show();
                        else
                            Toast.makeText(MainActivity.this, "查询失败!", Toast.LENGTH_LONG).show();
                    }
                }
                else
                {
                    Toast.makeText(MainActivity.this, "请输入查询内容!", Toast.LENGTH_LONG).show();
                }
            }
        });

        //为删除添加动作事件
        delate.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View arg0)
            {
                String tempName=name.getText().toString();
                String tempPhone=phone.getText().toString();

                if(name.getText()!=null && phone.getText()!=null)
                {
                    if(!"".equals(name.getText().toString()) && !"".equals(phone.getText().toString()))
                    {
                        int flag=0;

                        for(int i=0;i<people.names.size();i++)
                        {  
                            String temp1=people.names.get(i);
                            String temp2=people.phones.get(i);
                            if(temp1.equals(tempName) && temp2.equals(tempPhone))
                            {
                                people.names.remove(i);
                                people.phones.remove(i);
                                flag=1;
                            }
                        }  

                        if(flag==1)
                            Toast.makeText(MainActivity.this, "删除成功!", Toast.LENGTH_LONG).show();
                        else
                            Toast.makeText(MainActivity.this, "删除失败!", Toast.LENGTH_LONG).show();
                    }
                    else
                    {
                        Toast.makeText(MainActivity.this, "删除的内容不存在!", Toast.LENGTH_LONG).show();
                    }
                }
                else
                {
                    Toast.makeText(MainActivity.this, "删除的内容不能为空!", Toast.LENGTH_LONG).show();
                }
            }
        });

        //为更新按钮添加动作事件
        refresh.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View arg0) 
            {
                String tempShow="";
                for(int i=0;i<people.names.size();i++)
                {
                    tempShow=tempShow+people.names.get(i)+" "+people.phones.get(i)+"\n";
                }

                show.setText(tempShow);
            }
        });
    }



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

}

文件的保存路径与内容

打开DDMS,从FileExplorer中找到data/data,在com.example.p1(包名)目录下找到shared_prefs的pepple(文件名),然后导出查看。保存的转换成Base64编码。
这里写图片描述
这里写图片描述

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值