Search code examples
androidsharedpreferencesandroid-contacts

How to save Array of phone number into SharedPreference


I want to save phone number using SharedPreference . As it has been fetched from phone book and set in textView i am unable to save every one of them in SharedPreference. Please help me towards how to save and retrive set of phone number(array or set) via SharedPreference and send it to another fragment for messaging the number.

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();
    }
}
}

Solution

  • You can save ArrayList/Array/List to SharedPrefernces Here is How you can do it

        //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();
    

    but You an refer this link for details and this link . these Are useful and easy to understand.

    For your second part To Send the Data to Fragment

    Well I would suggest to save the data in the current Activity/Fragment what ever you have and then get the data from shared preferences in the fragment you wish to open but in case if you really want to get the data and to send the data to the fragment consider this link please.

    Note:

    By Looking at your code I think there could be large amount of contacts, so it means that you will have a large array. I will suggest you to store them in database as you can easily retrieve/update/delete any data and record.

    Update : (after getting clear in comments )

    You have written the code to get the contacts from the Textview in On create where as I think the contacts in textviews gets update later where as that code in the onCreate run before it.

    make this change

    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]));
    
        }
    
            }
        });