0

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();
    }
}
}
Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33
  • You can go through [this](http://stackoverflow.com/questions/3876680/is-it-possible-to-add-an-array-or-object-to-sharedpreferences-on-android) and [this](http://stackoverflow.com/questions/23024831/android-shared-preferences-example) SO posts. Its always better to use a Database when you are storing large volume of data. – Jaydroid Sep 29 '16 at 04:57
  • @Jaydroid I want to save only 3 contact.For that i think SharedPreference is good option.But I am unable to save the contact rather it store the text assigned to textView. – Kamal Kumar Majhi Sep 29 '16 at 05:06

2 Answers2

2

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

    }

        }
    });
Community
  • 1
  • 1
A.s.ALI
  • 1,992
  • 3
  • 22
  • 54
  • I want to save only 3 contact.For that i think SharedPreference is good option.But I am unable to save the contact rather it store the text assigned to textView. – Kamal Kumar Majhi Sep 29 '16 at 05:06
  • Actually i am unable to retrive phone number from textView . May be because of some error in my code. without that storing garbage value in set is not useful. Can you figure out any error there? – Kamal Kumar Majhi Sep 29 '16 at 05:38
  • I want to make app which will fetch contact from phone book and set the phone number to textView. Then i want to retrive it from textView and store it in sharedpreference .And from sharedpreference i want to get the data. – Kamal Kumar Majhi Sep 29 '16 at 07:00
  • is ur step 1 is successful? I mean are you getting contact in the TextView ? – A.s.ALI Sep 29 '16 at 07:06
  • Yeah i'm getting it.But when i'm retriving it i am not getting phone number . I am getting text assigned to textView. – Kamal Kumar Majhi Sep 29 '16 at 07:10
  • show us the exact part where u are getting the contact name and phone number from the textview and also mention where in code u are putting contact in the textfields – A.s.ALI Sep 29 '16 at 07:13
  • private void contactPicked(Intent data,int req) in this function i am putting contact in textview and after con3.setOnclicklistener i am trying to getting contact from textview – Kamal Kumar Majhi Sep 29 '16 at 07:27
  • con3 is only to set one textView . There is 3 button 3 textView. On clicking button contact is set on textView. – Kamal Kumar Majhi Sep 29 '16 at 08:52
  • comment all the code in the con3 , just to test it , but keep the code which i put above in answer and then let me know – A.s.ALI Sep 29 '16 at 09:06
  • On putting the code in con3 clicklistener or any button click listener it throws NumberFormatException. Invalid int: "phone1" – Kamal Kumar Majhi Sep 29 '16 at 10:30
  • Finally got my code right. The error was in retriving phone number in oncreate method. Thank You. – Kamal Kumar Majhi Sep 29 '16 at 10:58
  • then that must be parsing issue – A.s.ALI Sep 29 '16 at 11:18
  • yeah I mentioned it in my answer – A.s.ALI Sep 29 '16 at 11:18
0

after api level 11 Set will be stored in preferences so convert your Array or List to set and stored in preferences

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

For Retriving using Iterator

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