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. :)
Related
I want to compare two JSONArray with the same value with different order how compare it. This code work fine if value place in the same index.
String a = "[\"ABC-110101-056079-0001\",\"CBA-111101-056079-0001\",\"BCD-110101-056079-0011\"]";
String b = "[\"ABC-111101-056079-0001\",\"CBA-110101-056079-0001\",\"BCD-110101-056079-0011\"]";
JSONArray jsonArraya = null;
JSONArray jsonArrayb = null;
try {
jsonArraya = new JSONArray(a);
jsonArrayb = new JSONArray(b);
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonArraya.equals(jsonArrayb)) {
Log.i("TAG",str2 is equal to str1 = " + "true");
}
You could add the elements of each array to a SortedSet instance and compare those:
SortedSet<Object> seta = new TreeSet<>();
jsonArraya.forEach(seta::add);
SortedSet<Object> setb = new TreeSet<>();
jsonArrayb.forEach(setb::add);
Log.i("TAG", "str2 is equal to str1 = " + seta.equals(setb));
The best solution in this situation is to parse values of those arrays first using Gson into POJO files, After that create .equals() method, which will add all strings from array into Set<>.
Then iterate over one set and remove all current item from another set and remove the same elements. Both objects are the same if at the end there will be no elements in the second set.
I am having JSON object like
{
key1:value1,
key2:value2
key3:value3
}
and i will write this JSON content to file.(Done)
For next interval of time i am getting JSON Object as
{
key1:newValue1,
key2:value2
key3:newValue3
}
I need to find out difference between each values. and need to write new json into file
{
key1:(value1- newValue1),
key2:(value2 - value2)
key3:(value3- newValue3)
}
How can i achieve it.? Please help.
The code below just iterates through the keys of your testObject, subtracts the value of the object from file and puts the result of this subtraction back to the testObject... Than you can save, or do whatever you want to do with the values in testObject
for(Iterator<String> iterator = testObject.keys(); iterator.hasNext();) {
String key = iterator.next();
try {
int testValue = testObject.getInt(key);
int fileValue = fileObject.getInt(key);
int differenceValue = testValue - fileValue;
testObject.put(key, differenceValue);
} catch (JSONException e) {e.printStackTrace();}
}
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];
}
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.
I have this piece of code;
Scanner s = new Scanner(getResources().openRawResource(R.raw.game));
try {
while (s.hasNextLine()) {
System.out.println(s.nextLine());
}
} finally {
s.close();
}
How can I make to load a random line from this piece of code?
Thanks.
You could load the lines into another data structure such as an ArrayList and then use Random to generate a random index number.
Here's some code to put it into an ArrayList:
Scanner s = new Scanner(getResources().openRawResource(R.raw.game));
ArrayList<String> list = new ArrayList<String>();
try {
while (s.hasNextLine()) {
list.add(s.nextLine());
}
} finally {
s.close();
}
This code will return a random line:
public static String randomLine(ArrayList list) {
return list.get(new Random().nextInt(list.size()));
}
First load all of them from file into a String array then randomly pick one of them from that String array.
lets supose that you did the collecting to the String array lines:
int randomLine = (int)(Math.random()*lines.length);
there you got your random line.
Edit: oh well, you could use just String[]