【问题标题】:How to save Array of phone number into SharedPreference如何将电话号码数组保存到 SharedPreference
【发布时间】:2016-09-29 04:38:49
【问题描述】:

我想使用 SharedPreference 保存电话号码。由于它是从电话簿中获取并在 textView 中设置的,因此我无法将它们中的每一个都保存在 SharedPreference 中。请帮助我了解如何通过 SharedPreference 保存和检索一组电话号码(数组或集合)并将其发送到另一个片段以发送该号码。

Contact.java

package com.kamal.sos10;

import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.nfc.Tag;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.Intent;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.Array;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Contact extends AppCompatActivity {

EditText msg,editText2,editText3,editText4;
Button con1,con2,con3;
TextView textView3,textView5,textView6,textView7,textView8,textView9;

TextView text1;
//  static final int PICK_CONTACT = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contact);

    msg=(EditText)findViewById(R.id.msg);
   // editText2=(EditText)findViewById(R.id.editText2);

    textView3=(TextView)findViewById(R.id.textView3);
  //  text1=(TextView)findViewById(R.id.first);
    textView5=(TextView)findViewById(R.id.textView5);
    textView6=(TextView)findViewById(R.id.textView6);
    textView7=(TextView)findViewById(R.id.textView7);
    textView8=(TextView)findViewById(R.id.textView8);
    textView9=(TextView)findViewById(R.id.textView9);
    con1=(Button)findViewById(R.id.con1);
    con2=(Button)findViewById(R.id.con2);
    con3=(Button)findViewById(R.id.con3);

    con1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.putExtra("extra_text1", "1");
            intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
             if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
                startActivityForResult(intent, 1);
            }
        }
    });

    con2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.putExtra("extra_text2", "2");
            intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
            if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
                startActivityForResult(intent,2);
            }
        }
    });

    con3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.putExtra("extra_text3", "3");
            intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
            if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
                startActivityForResult(intent, 3);
            }
        }
    });
    int num = Integer.valueOf(textView3.getText().toString());
    int num2 = Integer.valueOf(textView6.getText().toString());
    int num3 = Integer.valueOf(textView7.getText().toString());
    Integer[] array=new Integer[3];
    array[0]=num;
    array[1]=num;
    array[2]=num;

    for (int j=0;j<3;j++)
    {

        Log.i("key", String.valueOf(array[j]));

    }
  /*
   SharedPreferences sharedPreferences=this.getSharedPreferences("com.kamal.sos10", Context.MODE_PRIVATE);

    SharedPreferences.Editor edit = sharedPreferences.edit();
    edit.putInt("array_size", strings.length);
    for(int i=0;i<strings.length; i++)
        edit.putString("array_" + i, strings[i]);
    edit.commit();

    int size = sharedPreferences.getInt("array_size", 0);
    strings = new String[size];
    for(int i=0; i<size; i++) {
       strings[i]= sharedPreferences.getString("array_" + i, null);
        Log.i("sdert",strings[i]);
    }
    */


}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1 || requestCode == 2 || requestCode == 3) {
        if (resultCode == this.RESULT_OK) {
            contactPicked(data,requestCode);
        }
    }
}

private void contactPicked(Intent data,int req) {
    ContentResolver cr = this.getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    cur.moveToFirst();
    try {
        // getData() method will have the Content Uri of the selected contact
        Uri uri = data.getData();
        //Query the content uri
        cur = this.getContentResolver().query(uri, null, null, null, null);
        cur.moveToFirst();
        // column index of the contact ID
        String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
        // column index of the contact name
        String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        // column index of the phone number
        Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                new String[]{id}, null);
        while (pCur.moveToNext()) {
            String phone = pCur.getString(
                    pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll(" ", "");
            String text1 = getIntent().getStringExtra("extra_text1");
            Toast.makeText(Contact.this, text1, Toast.LENGTH_SHORT).show();

            if (req==1)
            {
                textView3.setText(phone);
                Toast.makeText(Contact.this, textView3.getText(), Toast.LENGTH_SHORT).show();
                int num = Integer.valueOf(textView3.getText().toString());
                Log.i("yut", String.valueOf(num));
                textView5.setText(name);
            }
            if (req==2)
            {
                textView6.setText(phone);
                textView8.setText(name);
            }
            if (req==3)
            {
                textView7.setText(phone);
                textView9.setText(name);
            }



            pCur.close();
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
}

【问题讨论】:

  • 您可以浏览thisthis SO 帖子。当您存储大量数据时,最好使用数据库。
  • @Jaydroid 我只想保存 3 个联系人。为此,我认为 SharedPreference 是不错的选择。但我无法保存联系人,而是存储分配给 textView 的文本。

标签: android sharedpreferences android-contacts


【解决方案1】:

您可以将 ArrayList/Array/List 保存到 SharedPrefernces 这是您可以做到的方法

    //Retrieve the values
Set<String> set = myScores.getStringSet("key", null);

//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();

但您可以参考this 链接了解详情和this 链接。这些有用且易于理解。

第二部分将数据发送到片段

好吧,我建议将数据保存在当前 Activity/Fragment 中,然后从您希望打开的 Fragment 中的共享首选项中获取数据,但如果您真的想获取数据并发送片段的数据请考虑this链接。

注意:

通过查看您的代码,我认为可能有大量联系人,因此这意味着您将拥有一个大数组。我建议您将它们存储在数据库中,因为您可以轻松检索/更新/删除任何数据和记录。

更新:(在 cmets 搞清楚后)

您已经编写了代码以从 On Create 中的 Textview 获取联系人,因为我认为 textviews 中的联系人稍后会更新,而 onCreate 中的代码在它之前运行。

进行此更改

con3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
    //Just check it here 
     int num = Integer.valueOf(textView3.getText().toString());
    int num2 = Integer.valueOf(textView6.getText().toString());
    int num3 = Integer.valueOf(textView7.getText().toString());
    Integer[] array=new Integer[3];
    array[0]=num;
    array[1]=num;
    array[2]=num;

    for (int j=0;j<3;j++)
    {

        Log.i("key", String.valueOf(array[j]));

    }

        }
    });

【讨论】:

  • 我只想保存 3 个联系人。为此,我认为 SharedPreference 是不错的选择。但我无法保存联系人,而是存储分配给 textView 的文本。
  • 实际上我无法从 textView 检索电话号码。可能是因为我的代码中有一些错误。如果没有在 set 中存储垃圾值是没有用的。你能找出其中的任何错误吗?
  • 我想制作一个从电话簿中获取联系人并将电话号码设置为 textView 的应用程序。然后我想从 textView 中检索它并将其存储在 sharedpreference 中。我想从 sharedpreference 中获取数据。
  • 你的第一步成功了吗?我的意思是你在 TextView 中取得联系吗?
  • 是的,我知道了。但是当我检索它时,我没有得到电话号码。我正在将文本分配给 textView。
【解决方案2】:

在 api 级别 11 之后设置将存储在首选项中,因此将您的数组或列表转换为设置并存储在首选项中

Set<String> setNameYouWantToStore = new HashSet<String>();
setNameYouWantToStore.addAll(listOfDetails);
scoreEditor.putStringSet("keyForSet", setNameYouWantToStore);
scoreEditor.commit();

使用迭代器进行检索

Set<String> setNameYouWantToStore = new HashSet<String>();
        Iterator iterator = setNameYouWantToStore.iterator();
        while(iterator.hasNext()) {
            System.out.println("Value: " + iterator.next() + " ");
        }

【讨论】:

  • 如果我将数组(带数据)转换为设置,是否必须使用 addAll 方法?
  • 是的,因为您使用的是列表,即 addAll 方法使用而不是特定的详细信息
  • 在一个集合中检索它是什么?
  • @KamalKumar set 将使用迭代器检索查看我编辑的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-03
  • 2023-04-04
  • 2012-02-15
  • 1970-01-01
  • 2013-01-22
相关资源
最近更新 更多