Contacts storage in Shared Preferences - android

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

The error is coming due below two lines. After spliting you have check the length of array.
Your Code
if(arrayOfString[i].contains("%"))
str2 = arrayOfString[i].split("%")[1];
It should be like below.
if(arrayOfString[i].contains("%")){
String[] str3 = arrayOfString[i].split("%");
if(str3.lenght >=2)
str2 = str3[1];
}

Related

Why do I get an empty response when my android app calls my API on my server?

I have android application that called information and show it as a list.
I have a spinner when you choose the date from the spinner you get the information related to that date.
In the app first load it calls automatically today information.
this is the code I use in my main activity to create my spinner and fill it with elements and handle the clicks on each item:
// Spinner element
spinner = (Spinner) v.findViewById(R.id.spinner);
// Spinner click listener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// On selecting a spinner item
//String item = parent.getItemAtPosition(position).toString();
switch(position){
case 3:
if (JsonUtils.isNetworkAvailable(getActivity())) {
list.clear();
new MyTask().execute(Config.SERVER_URL + "/banko_api.php?d_o=-1");
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.failed_connect_network), Toast.LENGTH_SHORT).show();
}
break;
case 4:
if (JsonUtils.isNetworkAvailable(getActivity())) {
list.clear();
new MyTask().execute(Config.SERVER_URL + "/banko_api.php?d_o=0");
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.failed_connect_network), Toast.LENGTH_SHORT).show();
}
break;
case 5:
if (JsonUtils.isNetworkAvailable(getActivity())) {
list.clear();
new MyTask().execute(Config.SERVER_URL + "/banko_api.php?d_o=1");
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.failed_connect_network), Toast.LENGTH_SHORT).show();
}
break;
default:
if (JsonUtils.isNetworkAvailable(getActivity())) {
list.clear();
new MyTask().execute(Config.SERVER_URL + "/banko_api.php?d_o=0");
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.failed_connect_network), Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, -1);
Date yesterday = calendar.getTime();
calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
DateFormat dateFormat = new SimpleDateFormat("dd/MM EEE");
String todayAsString = dateFormat.format(today);
String tomorrowAsString = dateFormat.format(tomorrow);
String yesterdayAsString = dateFormat.format(yesterday);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
categories.add(yesterdayAsString);
categories.add(todayAsString);
categories.add(tomorrowAsString);
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getContext(), R.layout.spinner_item, categories);
dataAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
spinner.setSelection(4);
The problem : first load of the app is calling the data of today (which is the default choice in my spinner) without any problem.
if i choose another element in the spinner it also calls the related data without problem.
now if I want to select back today element in the spinner no data will be brought from the server even when the app at the start up it calls data from the same link and get it.
I get this message in my log :
W/System.err: org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject
The onPostExcute of my Asynktask contains this code:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != progressDialog && progressDialog.isShowing()) {
progressDialog.dismiss();
}
if (null == result || result.length() == 0) {
Toast.makeText(getActivity(), getResources().getString(R.string.failed_connect_network), Toast.LENGTH_SHORT).show();
} else {
try {
Log.d("resultTT",result);
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(JsonConfig.CATEGORY_ARRAY_NAME);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemMatch objItem = new ItemMatch();
objItem.setMatchId(objJson.getString(JsonConfig.Match_ID));
objItem.setMatchTournamentName(objJson.getString(JsonConfig.Match_LEAGUE_NAME));
objItem.setMatchTime(objJson.getString(JsonConfig.Match_TIME));
objItem.setMatchStatus(objJson.getString(JsonConfig.Match_STATUS));
objItem.setMatchLocalTeamName(objJson.getString(JsonConfig.Match_LOCALTEAM_NAME));
objItem.setMatchVisitorTeamName(objJson.getString(JsonConfig.Match_VISITORTEAM_NAME));
objItem.setMatchLocalTeamGoals(objJson.getString(JsonConfig.Match_LOCALTEAM_GOALS));
objItem.setMatchVisitorTeamGoals(objJson.getString(JsonConfig.Match_VISITORTEAM_GOALS));
objItem.setMatchBestOddPercent(objJson.getString(JsonConfig.Match_BEST_ODD_PERCENT));
objItem.setMatchBestOddResult(objJson.getString(JsonConfig.Match_BEST_ODD_RESULT));
list.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
for (int j = 0; j < list.size(); j++) {
object = list.get(j);
array_match_id.add(String.valueOf(object.getMatchId()));
str_match_id = array_match_id.toArray(str_match_id);
array_league_name.add(String.valueOf(object.getMatchTournamentName()));
str_league_name = array_league_name.toArray(str_league_name);
array_match_time.add(String.valueOf(object.getMatchTime()));
str_match_time = array_match_time.toArray(str_match_time);
array_match_status.add(String.valueOf(object.getMatchStatus()));
str_match_status = array_match_status.toArray(str_match_status);
array_match_localteam_name.add(object.getMatchLocalTeamName());
str_match_localteam_name = array_match_localteam_name.toArray(str_match_localteam_name);
array_match_visitorteam_name.add(object.getMatchVisitorTeamName());
str_match_visitorteam_name = array_match_visitorteam_name.toArray(str_match_visitorteam_name);
array_match_localteam_goals.add(object.getMatchLocalTeamGoals());
str_match_localteam_goals = array_match_localteam_goals.toArray(str_match_localteam_goals);
array_match_visitorteam_goals.add(object.getMatchVisitorTeamGoals());
str_match_visitorteam_goals = array_match_visitorteam_goals.toArray(str_match_visitorteam_goals);
array_match_best_odd_percent.add(object.getMatchBestOddPercent());
str_match_best_odd_percent = array_match_best_odd_percent.toArray(str_match_best_odd_percent);
array_match_best_odd_result.add(object.getMatchBestOddResult());
str_match_best_odd_result = array_match_best_odd_result.toArray(str_match_best_odd_result);
}
setAdapterToListView();
}
In the try section of this code u can see I make a log of the result to see what is coming from the server i just get this : D/resultTT: []
and as you see the try is inside the else section so in the if statement of this section i check if the result is null or empty ; but the code passes it and enter the else statement but still showing that the returned result array is empty.
I want some help to find the reason behind this empty returned array even it loads fine at the start up. why can not it get the information after I choose any element in the spinner and then come back to the default (today) element?
UPDATE : this is my php side-server api code
<?php
include_once ('includes/variables.php');
DEFINE ('DB_HOST', $host);
DEFINE ('DB_USER', $user);
DEFINE ('DB_PASSWORD', $pass);
DEFINE ('DB_NAME', $database);
$mysqli = #mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL');
#mysql_select_db (DB_NAME) OR die ('Could not select the database');
?>
<?php
mysql_query("SET NAMES 'utf8'");
$date_offset = mysql_real_escape_string($_GET[d_o]);
//$date_offset = 0;
if(empty($date_offset) || $date_offset == "0")
{
$date_offset_value = "0";
$query="SELECT a.*, m.match_id, m.match_time, m.en_tournament_name FROM app_banko a inner join matches_of_comments m on m.match_id = a.match_id where a.date_offset = $date_offset_value limit 20";
$resouter = mysql_query($query);
}
else
{
$date_offset_value = $date_offset;
$query="SELECT a.*, m.match_id, m.match_time, m.en_tournament_name FROM app_banko a inner join matches_of_comments m on m.match_id = a.match_id where a.date_offset = $date_offset_value limit 20";
$resouter = mysql_query($query);
}
$set = array();
$total_records = mysql_num_rows($resouter);
if($total_records >= 1){
while ($link = mysql_fetch_array($resouter, MYSQL_ASSOC)){
$set['NewsApp'][] = $link;
}
}
echo $val= str_replace('\\/', '/', json_encode($set));
?>
If you get an array in return when expecting an object, there might be something wrong with the request to the API. One way is to figure it out it set up Wireshark on the development machine to sniff and filter the traffic. Then you can see if your request is faulty.
It is possible that the value of the response argument from the onPostExecute method contains stringified JSONArray, not JSONObject.
You can always test this with:
try:
JSONArray jsonArray = new JSONArray(result);
catch(JSONException e) {
// String `result` is not an array. Parse it as a regular JSONObject.
}
Testing wheter string is an empty json array (depends on it's formatting, especially when it may contain some white characters) checking it's length might be a pretty bad idea.
It all depends how are determined an API endpoints that you are calling.
One more tip at the end. If you are planning to consume REST API I strongly recommend using:
Retrofit - which allows you to easily define interfaces to access your API,
GSON - to automatically convert responses for Java models.
Your result string is an empty array but not an empty string. The empty array is represented as the following string:
String result = "[]";
In that case result.length() is equal to 2.
When parsing JSON you need to know if the parsed object is of type Object or of type Array. The former one is wrapped with braces {}, the later one with square brackets [].
So the following line:
JSONObject mainJson = new JSONObject(result);
Should probably be:
JSONArray mainJson = new JSONArray(result);
But I cannot emphasize enough that you need to know what your API returns if you want to be able to parse it correctly.
EDIT:
Well, json_encode will have a hard time to guess whether it should create a JSON Array or a JSON Object out of the empty array that you created with $set = array();.
Adding objects to the array like you do in your loop makes it obvious for json_encode that it should create a JSON Object.
I don't know if you can force json_encode's behavior, but worst case you could check yourself if the array is empty and return "" or null if the array is empty.
$set = array();
$total_records = mysql_num_rows($resouter);
if ($total_records >= 1) {
while ($link = mysql_fetch_array($resouter, MYSQL_ASSOC)) {
$set['NewsApp'][] = $link;
}
echo $val= str_replace('\\/', '/', json_encode($set));
} else {
echo $val="";
}
please put a check result.isEmpty() in your try block condition may this could solve your problem.
you can not directly get response in string . it can use JSONObject and JSONArray.

Android - Set text of TextView with Final String Array

I have managed to extract the first letters on a sentence and store that into a variable.
String[] result = matches.toString().split("\\s+");
// The string we'll create
String abbrev = "";
// Loop over the results from the string splitting
for (int i = 0; i < result.length; i++){
// Grab the first character of this entry
char c = result[i].charAt(0);
// If its a number, add the whole number
if (c >= '0' && c <= '9'){
abbrev += result[i];
}
// If its not a number, just append the character
else{
abbrev += c;
}
}
I then store the values into a Final String Array;
List<String> list = Arrays.asList(abbrev);
final String[] cs12 = list.toArray(new String[list.size()]);
I then set the values into a alert dialog as follows:
builder2.setItems(cs12[0].toString().split(","), new DialogInterface.OnClickListener(){
My next task is when the user selects one of the items for it to go into the text view. However it doesn't let me do this.
public void onClick(DialogInterface dialog, int item) {
TextView speechText = (TextView)findViewById(R.id.autoCompleteTextView1);
speechText.setText(Arrays.toString(cs12));
// TextView speechText = (TextView)findViewById(R.id.autoCompleteTextView1);
// speechText.setText(matches.get(item).toString());
However for my other parts matches.get works fine but I cant seem to get cs12.get.
Any Ideas?
Thanks
Use cs12[0].toString().split(",")[item] to show selected item in TextView:
String[] strArr= cs12[0].toString().split(",");
speechText.setText(strArr[item]);

Storing String Array as JSON Array then getting Ljava.lang.String# when trying to receive and set TextView as value

Right now i am pulling a value from a EditText MainActivity and putting that as at string in sharedpref. In a later activity I am receiving that value and trying to add it to the end of an array that is contunially growing. To store the Array in that later activity for receiving later to continue adding I used a JSON array. So basically I create a String Array when the counter is 0 (first input the user has done since clearing) and receive the string value from the MainActivity EditText and add that as the first value in the String Array and then store it as a JSON Array. When I receive it later (when counter is > 0) and convert it back to string Array, the outPut in my TextView for any given spot in the array is [L.java.lang.String;#42a5e438,. Below is my code for both if coutner == 0 and counter >0; Does anyone know what the solution is?
int placeCounterExplanation = pref.getInt("placeCounterExplanation",0);
//getting new item
String explanationItem = pref.getString("explanationItem",null);
if(placeCounterExplanation > 0){
///////////////////////////////////// RECEIVE//
//pull existing array
JSONArray explanationjArray;
try {
explanationjArray = new JSONArray(settings.getString("jArray", ""));
//converting from json back to workable string array
// String []ExplanationDetailArray = new String[explanationjArray.length()];
String []ExplanationDetailArray = new String[100];
//matching them/converting
for(int i = 0, count = explanationjArray.length(); i<= count; i++)
{
try {
String jsonString = explanationjArray.getString(i);
ExplanationDetailArray[i] = jsonString;
}
catch (JSONException e) {
e.printStackTrace();
}
}
//after matching^ it adds newest value
ExplanationDetailArray[placeCounterExplanation] = explanationItem;
////////////////////////////////////////////////////////////////////////
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("product");
// displaying selected product name
txtProduct.setText(product);
if (product.equals("Alcohol")){
test.setText(ExplanationDetailArray[0]);
String placeCount = Integer.toString(placeCounterExplanation);
test2.setText(ExplanationDetailArray[1]);
// test3.setText(placeCounterExplanation - 1);
}
//////////////////////////////////////////////////////////////////////////
/////STORE
explanationjArray.put(Arrays.toString(ExplanationDetailArray));
// explanationjArray.put(ExplanationDetailArray);
editor2.putString("jArray", explanationjArray.toString());
editor2.commit();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if (placeCounterExplanation == 0){
ExplanationDetailArray = new String[100];
ExplanationDetailArray[0] = explanationItem;
JSONArray explanationjArray = new JSONArray();
//////////////////////////////
// String sC = Integer.toString(spotCounter);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("product");
// displaying selected product name
txtProduct.setText(product);
if (product.equals("Alcohol")){
test.setText(ExplanationDetailArray[0]);
// test2.setText(ExplanationDetailArray[1]);
// test3.setText(placeCounterExplanation - 1);
}
///////////////////////////////
//STORING MIGHT NOT NEED THIS INSIDE HERE
// explanationjArray.put(ExplanationDetailArray);
explanationjArray.put(Arrays.toString(ExplanationDetailArray));
editor2.putString("jArray", explanationjArray.toString());
editor2.commit();
// placeCounterExplanation = placeCounterExplanation + 1;
// editor.putInt("placeCounterExplanation",placeCounterExplanation);
//editor.commit();
}
//after either IF Statement catches teh program, it advances the counter.
placeCounterExplanation = placeCounterExplanation + 1;
editor.putInt("placeCounterExplanation",placeCounterExplanation);
editor.commit();
I believe your problem is coming from the following line in code :
explanationjArray.put(ExplanationDetailArray);
This will insert a textual representation of the object into the JSON array. Instead you can do :
explanationjArray.put(Arrays.toString(ExplanationDetailArray));
or your own implementation of converting the string array to a concatenated set of strings.

How to save an array of strings with SharedPreferences?

I have an array of Strings, I need to save this array with SharedPreferences, and then read and display them on a ListView.
For now, I use this algorithm:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//To save the strings
public void saveStrings(String[] str){
int a = 0;
int lenght = str.length;
while (a<lenght){
sp.edit().putString(Integer.toString(a), Integer.toString(str[a])).apply();
a=a+1;
}
}
//To read the strings
public String[] getStrings(){
String[] str = new String [8];
int a = 0;
int lenght = 8; //To read 8 strings
while (a<lenght){
str[a] = sp.getString(Integer.toString(a),"Null");
a=a+1;
}
return str;
}
Is there a way to save and read the entire array, rather than a string at a time?
For this project I'm using API level 19 (Android 4.4.2 KitKat)
Well, you could use putStringSet(), but (a) it's only from API level 11 onwards, and (b) as its name says, it's for sets (which means that you will lose the original ordering and any duplicates present in the array).
We solved this problem by "encoding" collections into a string and using putString() and decoding them afterwards on getString(), with this pair of methods (for ArrayList, but should be easily convertible into array versions):
public String encodeStringList(List<String> list, char separator)
{
StringBuilder sb = new StringBuilder(list.size() * 50);
for (String item : list)
{
if (sb.length() != 0)
sb.append(separator);
// Escape the separator character.
sb.append(item.replace(Character.toString(separator), "\\" + separator));
}
return sb.toString();
}
public List<String> decodeStringList(String encoded, char separator)
{
ArrayList<String> items = new ArrayList<String>();
if (encoded != null && encoded.length() != 0)
{
// Use negative look-behind with backslash, because it's used for escaping the separator.
// Expression is "(?<!\)s" with doubling because of escaping in regex, and again because of escaping in Java).
String splitter = "(?<!\\\\)" + separator; //$NON-NLS-1$
String[] parts = encoded.split(splitter);
// While converting to list, take out the escape characters used to escape the now-removed separator.
for (int i = 0; i < parts.length; i++)
items.add(parts[i].replace("\\" + separator, Character.toString(separator)));
}
return items;
}
Set<String> set =list.getStringSet("key", null);
Set<String> set = new HashSet<String>();
set.addAll(list of the string list u have);
editor.putStringSet("key", set);
editor.commit();
Please refer to this thread for further details Save ArrayList to SharedPreferences
//while storing
str is string array
String fin="";
for(i=0;i<n;i++){
fin=fin+str[i]+",";
}
fin=fin.substring(0,fin.length()-1);
//while retrieving
List<String> items = Arrays.asList(fin.split("\\s*,\\s*"));

android how can i format a arrayList<String>

i have a problem with format arrayList.I have one parameter it have value
Licence_car:[[คย1453 กรุงเทพมหานคร], [รง2344 กรุงเทพมหานคร], [รน4679 กรุงเทพมหานคร]] (Data is a ThaiLanguage)
I use this parameter to set entry of list preference but it will show like this
I want to delete character is "[" and "]" to make a variable like this Licence_car:[คย1453 กรุงเทพมหานคร, รง2344 กรุงเทพมหานคร, รน4679 กรุงเทพมหานคร] how can i do that?
This is my code set entry to list preference.
#SuppressWarnings("unchecked")
public void showCar(Context context,ArrayList<String> currentCars){
SharedPreferences MYprefs = context.getSharedPreferences(PREFERENCES, PREFERENCE_MODE);
if (null == currentCars) {
currentCars = new ArrayList<String>();
}
try {
currentCars = (ArrayList<String>) ObjectSerializer.deserialize(MYprefs.getString("car_licence_", ObjectSerializer.serialize(new ArrayList<String>())));
//String[] car_list = currentCars.toCharArray;
Log.d(TAG,"Licence_car:"+currentCars);
final CharSequence[] charSequenceCarEntry = currentCars.toArray(new CharSequence[currentCars.size()]);
mCarDefault.setEntries(charSequenceCarEntry);
mCarDefault.setEntryValues(charSequenceCarEntry);
mCarDelete.setEntries(charSequenceCarEntry);
mCarDelete.setEntryValues(charSequenceCarEntry);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I get a preference value in arrayList and format to CharSequence[] for set entry to list preference i think that i do format from this point but i don't know how can do it.
Thank for any answer and sorry for my English.
Hello Developer,
You can foramt your charsequence before storing into array list ,hete i am giving the sample code please use it so here it is-
CharSequence[] charSequenceCarEntry = new CharSequence[10];
int startindex=charSequenceCarEntry.toString().indexOf("[");
int endindex=charSequenceCarEntry.toString().indexOf("]");
CharSequence cs =charSequenceCarEntry.toString().substring(startindex, endindex);
so in your case use it like-
currentCars = (ArrayList<String>) ObjectSerializer.deserialize(MYprefs.getString("car_licence_", ObjectSerializer.serialize(new ArrayList<String>())));
final CharSequence[] charSequenceCarEntry = currentCars.toArray(new CharSequence[currentCars.size()]);
int startindex=charSequenceCarEntry.toString().indexOf("[");
int endindex=charSequenceCarEntry.toString().indexOf("]");
CharSequence cs =charSequenceCarEntry.toString().substring(startindex, endindex);
mCarDefault.setEntries(cs);
mCarDefault.setEntryValues(cs);
mCarDelete.setEntries(cs);
mCarDelete.setEntryValues(cs);
I have solve this problem. I create input variable is type list<string> car_entry; to input a car_licence and output result is [คย1453 กรุงเทพมหานคร] so i will try to change type variable to String and the output is คย1453 กรุงเทพมหานคร as a result of charSequenceCarEntry is Licence_car:[คย1453 กรุงเทพมหานคร, รง2344 กรุงเทพมหานคร, รน4679 กรุงเทพมหานคร].Ok now It is done thank for any answer again. :)

Categories

Resources