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.
Use the increment like below.
Reason:
i
is incremented before the usage. Set exit condition in thefor
loopEdit: This is the complete code for your use case.
Edit 2: To get rid of the quotes, convert the preference string to
JSONArray
and iterate it.