Search code examples
androidsharedpreferencesmultiautocompletetextview

Contacts storage in Shared Preferences


I am Building an app where a Dialog box pops up when a button is clicked in an activity and the Dialog Box contain a MultiAutoCompleteTextview to select contacts in the form of contactname%number,contactname1%number,contactname2%number...

so now i am stuck at a place where i have to store the individual contacts by spliting the MultiAutoCompleteTextview using the comma "," and storing them one by one in an string array named "arrayOfString".

Next i want to split the name and the contact no using % in between them and store all contactnumbers and only contactnumbers without names in sharedpreferences one by one using a string "setnum".

but the app is crasing and reloading when i click the positivebutton save with the code below

Initilizations:

    SharedPreferences sp;
SharedPreferences.Editor ed;
String setnum="";

code:

    .setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
           String[] arrayOfString=localMultiAutoCompleteTextview.getText().toString().split(",");
            int i=0;
            if(i>=arrayOfString.length){
                System.out.println("**********************" + setnum);
                Toast.makeText(getActivity(), setnum, Toast.LENGTH_SHORT).show();
                sp=getActivity().getSharedPreferences("sdat", 2);
                ed=sp.edit();
                ed.putString("snum", setnum);
                ed.commit();
                setnum="";
                getActivity().finish();
                return;
            }
           String str2="";
            if(arrayOfString[i].contains("%"))
                str2 = arrayOfString[i].split("%")[1];
            String str1;
            for (setnum=(setnum+str2+",");;setnum=(setnum+str1+",")) {
                i++;
                str1 = arrayOfString[i]; /*i am getting error here*/
            }
        }
    });

i am getting the error at forth line from last at str1 = arrayOfString[i];

log:

    java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
        at com.sharat.emin3m.antirag.ContactDialog$1.onClick(ContactDialog.java:75)
        at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5354)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:911)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

plz help me with the code for my miniproject in college. thankyou.


Solution

  • Use the increment like below.

    for (setnum=(setnum+str2+",");i<arrayOfString.length;setnum=(setnum+str1+",")) {
        str1 = arrayOfString[i++]; /*error solved here*/
    }
    

    Reason: i is incremented before the usage. Set exit condition in the for loop

    Edit: This is the complete code for your use case.

    String[] arrayOfString=localMultiAutoCompleteTextview.getText().toString().split(",");
    sp=getActivity().getSharedPreferences("sdat", 2);
    ed=sp.edit();
    
    // Get already stored numbers from preference
    String oldNumbers = sp.getString("snum", new JSONArray().toString());
    
    JSONArray numberArray;
    // Create a JSONArray to store all numbers
    try {
        numberArray = new JSONArray(oldNumbers);
    } catch (JSONException e) {
        e.printStackTrace();
        numberArray = new JSONArray();
    }
    
    /// Loop through the multiautocomplete textview value array
    for(int i=0; i < arrayOfString.length; i++)
    {
        // Check whether the string contains '%'
        if(arrayOfString[i].contains("%"))
        {
            // Add numbers to the already existing array of numbers
            numberArray.put(arrayOfString[i].split("%")[1]);
        }
    }
    
    // Store the complete number array in preference as String
    ed.putString("snum", numberArray.toString());
    ed.commit();
    
    
    // To read the numbers after saving
    String display = sp.getString("snum", new JSONArray().toString());
    System.out.println(display);
    

    Edit 2: To get rid of the quotes, convert the preference string to JSONArray and iterate it.

    // To get rid of quotes
    try {
        JSONArray arr = new JSONArray(display);
    
        for(int j=0; j<arr.length(); j++)
        {
            String number = arr.getString(j);
            System.out.println(j+" - numberWithoutQuotes : "+number);
        }
    
    } catch (JSONException e) {
        e.printStackTrace();
    }