While retrieving values from Preference, it is repeating 20 times - android

Hi I am storing BigInteger[] array into Preference, This is working fine, but while retrieving i am getting the same value 20 times, can someone tell me what's wrong with the code :
final String DELIMITER = "BOND";
final int DELIMITER_LENGTH = 4;
String str = null ;
//BigInteger [] integer = new BigInteger[50];
for(int l = 0; l < arrayTimes.length ; l++){
if(str == null){
str = arrayTimes[i].toString() + DELIMITER;
}else{
str += arrayTimes[i].toString() + DELIMITER;
}
}
savePreference("your_key", str);
Log.d("Prefs", "Array Time Saved");
String strone = loadPreference("your_key");
ArrayList<BigInteger> myBigInt = new ArrayList<BigInteger>();
while(strone != null){
int subStringLastIndex = 0;
if(strone.contains(DELIMITER) && strone.length() != DELIMITER_LENGTH){
subStringLastIndex = strone.indexOf(DELIMITER.charAt(0));
myBigInt.add(new BigInteger(strone.substring(0, subStringLastIndex)));
strone = strone.substring(subStringLastIndex + 4);
}else{
strone = null;
}
}
for(int m = 0; m < myBigInt.size(); m++){
Log.d("Prefs", myBigInt.get(m).toString()); //Here i am printing values
}

You seem to have a typo. Your for loop uses l but you reference the array with i. If arrayTimes has 20 items, you'll add the same value to the string 20 times.

Related

Filter number from Array of string and get the index of last two greater number in android

I have a ArrayList that has value like [Value,Sum3,121,data8input,in:21::7,7.00,9.01] and I want to extract only number as the output should be like this [3,121,8,21,7,7.00,9.01] and then have to rearrange ascending and then get the index of last two number as result will be [21,121].
My tried code below,
for (int i = 0; i < arrayString.size(); i++) {
Pattern p = Pattern.compile("-?\\d+(,\\d+)*?\\.?\\d+?");
List<String> numbers = new ArrayList<String>();
Matcher m = p.matcher(arrayString.get(i).getvalue);
numbers.addAll(m);
for (int j = 0; j < numbers.size(); j++) {
Log.d("REMEMBERFILTER", allCollection.get(i).getTextValue());
}
}
}
do something like this, though it is not exactly memory efficient as I am using another list.
ArrayList<String> tempList = new ArrayList<>();
for (int i = 0; i < yourArrayList.size(); i++) {
tempList.add(yourArrayList.get(i).replaceAll("[^0-9]", ""));
}
//Arrange in ascending order
Collections.sort(tempList);
//Also try to remove those indexes which has only letters with
tempList.removeAll(Arrays.asList("", null));
for (int i = 0; i < tempList.size(); i++) {
Log.d("+++++++++", "" + tempList.get(i));
}
//You can get the last two or any element by get method of list by //list.size()-1 and list.size()-2 so on
This is a way to do it, finalArray has the 2 numbers you want:
String[] str = new String[] {"Value", "Sum3", "121", "data8input", "in:21::7", "7.00,9.01"};
StringBuilder longStringBuilder = new StringBuilder();
for (String s : str) {
longStringBuilder.append(s).append(" ");
}
String longString = longStringBuilder.toString();
String onlyNumbers = " " + longString.replaceAll("[^0-9.]", " ") + " ";
onlyNumbers = onlyNumbers.replaceAll(" \\. ", "").trim();
while (onlyNumbers.indexOf(" ") > 0) {
onlyNumbers = onlyNumbers.replaceAll(" ", " ");
}
String[] array = onlyNumbers.split(" ");
Double[] doubleArray = new Double[array.length];
for (int i = 0; i < array.length; i++) {
try {
doubleArray[i] = Double.parseDouble(array[i]);
} catch (NumberFormatException e) {
e.printStackTrace();
doubleArray[i] = 0.0;
}
}
Arrays.sort(doubleArray);
int numbersCount = doubleArray.length;
Double[] finalArray;
if (numbersCount >= 2) {
finalArray = new Double[]{doubleArray[numbersCount - 2], doubleArray[numbersCount - 1]};
} else if (numbersCount == 1) {
finalArray = new Double[]{ doubleArray[0]};
} else {
finalArray = new Double[]{};
}
for (Double number : finalArray) {
System.out.println(number);
}

Android. How to switch String = (A B, C D, E F, .....) to String (B A, D C, F E, ......)

i am a beginner.
I get String from SQLite.
WKT = cursor.getString(cursor.getColumnIndex(polygon));
WKT = WKT.replaceAll(",", ", ");
Its look like String = (1.00 2.00, 3.00 4.00, 5.00 6.00, .....).
How to switch it to String (2.00 1.00, 4.00 3.00, 6.00 5.00, ......).
Thanks.
try this
private static void testMethod() {
String result = "(A B, C D, E F)";
String resultTmp = result;
resultTmp = resultTmp.replace("(", "");
resultTmp = resultTmp.replace(")", "");
String[] aryResult = resultTmp.split(",");
String[] finalResult = reverseString(aryResult);
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < finalResult.length; i++) {
String dfgf = strBuilder.toString().equals("") ? "" : ",";
strBuilder.append(dfgf);
strBuilder.append(finalResult[i]);
}
String newString = strBuilder.toString();
System.out.println("RESULT : " + newString);
}
public static String[] reverseString(String[] words)
{
String[] t = new String[words.length];
for (int i = 0; i < words.length; i++)
{
t[i] = "";
for (int j = words[i].length() - 1; j >= 0; j--)
t[i] += words[i].charAt(j);
}
return t;
}
Follow below steps
1)Split string with ","
2)User Reverse() function to reverse the string(AB->BA)
3)Store the result in to an array.
Repeat the step until you split the last entry from sql lite.
Try this logic,its working in c and c++.
int Groups = 1; // Count 1 for the first group of letters
for ( int Loop1 = 0; Loop1 < strlen(String); Loop1++)
if (String[Loop1] == ' ') // Any extra groups are delimited by space
Groups += 1;
int* GroupPositions = new int[Groups]; // Stores the positions
for ( int Loop2 = 0, Position = 0; Loop2 < strlen(String); Loop2++)
{
if (String[Loop2] != ' ' && (String[Loop2-1] == ' ' || Loop2-1 < 0))
{
GroupPositions[Position] = Loop2; // Store position of the first letter
Position += 1; // Increment the next position of interest
}
}
try this..
private static void testTwo() {
String result = "(1.00 2.00, 3.00 4.00, 5.00 6.00)";
String resultTmp = result;
resultTmp = resultTmp.replace("(", "");
resultTmp = resultTmp.replace(")", "");
String[] aryResult = resultTmp.split(",");
for (int i = 0; i < aryResult.length; i++) {
String str = aryResult[i].trim();
String[] sdf = str.split(" ");
aryResult[i] = reverseArray(sdf);
}
String strResult = Arrays.toString(aryResult).replace("[", "(").replace("]", ")");
System.out.println("RESULT : " + strResult);
}
public static String reverseArray(String[] words)
{
for(int i = 0; i < words.length / 2; i++)
{
String temp = words[i];
words[i] = words[words.length - i - 1];
words[words.length - i - 1] = temp;
}
return ((Arrays.toString(words)).replace("[", "")).replace("]", "").replace(",", "");
}
#. If you want to swap sub-string, just use below method:
public String swapString(String str) {
str = str.replace("(", "");
str = str.replace(")", "");
String[] array = str.split(", ");
StringBuilder result = new StringBuilder();
result.append("(");
for (int i = 0; i < array.length; i++) {
String[] temp = String.valueOf(array[i]).split(" ");
result.append(temp[1]);
result.append(" ");
result.append(temp[0]);
if (i != array.length -1)
result.append(", ");
}
result.append(")");
return result.toString();
}
USE:
String yourString = "(1.00 2.00, 3.00 4.00, 5.00 6.00)";
Log.d("ARRAY", "Before Swap: " + yourString);
yourString = swapString(yourString);
Log.d("ARRAY", "After Swap: " + yourString);
OUTPUT:
D/ARRAY: Before Swap: (1.00 2.00, 3.00 4.00, 5.00 6.00)
D/ARRAY: After Swap: (2.00 1.00, 4.00 3.00, 6.00 5.00)
#. If you want to swap char, use below method:
public String swapChar(String str) {
// Convert string to char array
char[] array = str.toCharArray();
for (int i = 1; i < array.length - 1; i+=5) {
// Swap char
char temp = array[i];
array[i] = array[i+2];
array[i+2] = temp;
}
return String.valueOf(array);
}
USE:
String yourString = "(A B, C D, E F, G H, I J)";
Log.d("ARRAY", "Before Swap: " + yourString);
yourString = swapChar(yourString);
Log.d("ARRAY", "After Swap: " + yourString);
OUTPUT:
D/ARRAY: Before Swap: (A B, C D, E F, G H, I J)
D/ARRAY: After Swap: (B A, D C, F E, H G, J I)
Hope this will help~

how to check condition for json array elements

I am developing an app in which i am calling a service, in which data is coming as an array format.
As shown below:
[
{
"Image":null,
"FirstName":null,
"Active":false,
"HallTicketNumber":0,
"ReportingTime":null,
"EventDetails":null,
"CompanyName":null,
"Designation_Role":null,
"EventDate":null,
"StateName":null,
"CityName":null,
"FullAddress":null,
"HallTicket_Status":"HETSTOP"
}
]
In that i need to check the condition for HET_STATUS,if that StATUS is HET STOP then it should print that het stop. But when i am trying to check the condition it is showing nothing:
Below is my code:
String StringData = "" + data;
try {
JSONArray rootArray = new JSONArray(StringData);
int len = rootArray.length();
for (int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
String CompanyName = json.optString("CompanyName ");
String Position = json.optString("Designation_Role");
String EventDate = json.optString("EventDate");
String StateName = json.optString("StateName ");
String CityName = json.optString("CityName");
String Address = json.getString("FullAddress");
String ReportingTime = json.getString("ReportingTime");
String HallTicket_Status = json.getString("HallTicket_Status");
if (HallTicket_Status == "HETSTOP") {
Toast toast = Toast.makeText(UpcomingEventsDetails.this, "HET STOP", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Try this way,
if(HallTicket_Status.equalsIgnoreCase("HETSTOP")){
Toast toast = Toast.makeText(UpcomingEventsDetails.this, "HET STOP", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}else{
//do something
}
boolean equals(String str): Case sensitive comparison
boolean equalsIgnoreCase(String str): Case in-sensitive comparison
== will still test object equality. It is easy to be fooled, however:
Integer a = 10;
Integer b = 10;
System.out.println(a == b); //prints true
Integer c = new Integer(10);
Integer d = new Integer(10);
System.out.println(c == d); //prints false. however:
Integer a = 10;
Integer b = 10;
System.out.println(a == b); //prints true
Integer c = new Integer(10);
Integer d = new Integer(10);
System.out.println(c == d); //prints false
Don't use == condition for strings. Instead of use str.equals("HEYSTOP") . This will return boolean. If you check string is null then you should use == or != conditions.

Check if next char in a string is a space

I would like to check if the current char is a blank space as i dont want to change that. So i would like to change all the letters like i do now, but keep the spaces.
e.g. "that man" with C = 2 should become "vjcv ocp".
thanks in advance :)
String initialString = yourString.getText().toString();
char[] chars = initialString.toCharArray();
for (int i = 1; i <= chars.length; i++) {
C = Integer.valueOf(ceasarNr);
chars[i-1] = characters.get((characters.indexOf(chars[i-1]) + C)%29);
}
String resultString = new String(chars);
krypteredeTekst.setText(resultString);
}
Just skip the iteration if the character is a space:
String initialString = yourString.getText().toString();
char[] chars = initialString.toCharArray();
for (int i = 1; i <= chars.length; i++) {
//Skip if it is space.
if chars[i-1] == ' ';
continue;
C = Integer.valueOf(ceasarNr);
chars[i-1] = characters.get((characters.indexOf(chars[i-1]) + C)%29);
}
String resultString = new String(chars);
krypteredeTekst.setText(resultString);
}
There is method for checking if char is blank space ->
String initialString = yourString.getText().toString();
char[] chars = initialString.toCharArray();
for (int i = 1; i <= chars.length; i++) {
C = Integer.valueOf(ceasarNr);
if(!Character.isWhitespace(chars.charAt(i-1)) {
chars[i-1] = characters.get((characters.indexOf(chars[i-1]) + C)%29);
}
}
String resultString = new String(chars);
krypteredeTekst.setText(resultString);

regular-expressions android

i have string like these for example
309\306\308\337_338
309\306\337_338
310
311\315_316\336_337
311\315_316\336_337
311\335_336
these strings means list of page number , for example string "309\306\308\337_339" means
pages 309,306,308,337,338,339
i want to pass one of these string to function which return it as string like this
309,306,308,337,338,339
this function do that but in c# , i want to impalement in android
private static string Get_PageNumbers(string str)
{
ArrayList arrAll = new ArrayList();
MatchCollection match;
string[] excar;
string strid, firstNumber, lastlNumber;
int fn, ln;
ArrayList arrID = new ArrayList();
//***In Case The Range Number Between "_"
if (str.Contains("_"))
{
// match_reg = new Regex("(w?[\\d]+)*(_[\\d]+)");
Regex matchReg = new Regex("(w?[\\69]+_[\\d]+)*(q?[\\d]+//)*(a?[\\d]+_[\\d]+)*(y?[\\d]+)*");
match = matchReg.Matches(str);
int count = match.Count;
excar = new string[0];
for (int i = 0; i < count; i++)
{
Array.Resize(ref excar, count);
excar[i] = match[i].Groups[0].Value;
if (excar[i] != string.Empty)
arrID.Add(excar[i]);
}
//******IF Array Contains Range Of Number Like"102_110"
if (str.Contains("_"))
{
for (int i = 0; i < arrID.Count; i++)
{
strid = arrID[i].ToString();
if (arrID[i].ToString().Contains("_"))
{
int idy = strid.LastIndexOf("_");
firstNumber = strid.Substring(0, idy);
if (idy != -1)
{
lastlNumber = strid.Substring(idy + 1);
fn = int.Parse(firstNumber);
arrAll.Add(fn);
ln = int.Parse(lastlNumber);
for (int c = fn; c < ln; c++)
{
fn++;
arrAll.Add(fn);
}
}
}
else
{
arrAll.Add(arrID[i].ToString());
}
}
//******If Array Contain More Than One Number
if (arrAll.Count > 0)
{
str = "";
for (int i = 0; i < arrAll.Count; i++)
{
if (str != string.Empty)
str = str + "," + arrAll[i];
else
str = arrAll[i].ToString();
}
}
}
}
//***If string Contains between "/" only without "_"
else if (str.Contains("/") && !str.Contains("_"))
{
str = str.Replace("/", ",");
}
else if (str.Contains("\\"))
{
str = str.Replace("\\", ",");
}
return str;
}
I think this is easier to do with split function:
public static String Get_PageNumbers(String str) {// Assume str = "309\\306\\308\\337_338"
String result = "";
String[] pages = str.split("\\\\"); // now we have pages = {"309","306","308","337_338"}
for (int i = 0; i < pages.length; i++) {
String page = pages[i];
int index = page.indexOf('_');
if (index != -1) { // special case i.e. "337_338", index = 3
int start = Integer.parseInt(page.substring(0, index)); // start = 337
int end = Integer.parseInt(page.substring(index + 1)); // end = 338
for (int j = start; j <= end; j++) {
result += String.valueOf(j);
if (j != end) { // don't add ',' after last one
result += ",";
}
}
} else { // regular case i.e. "309","306","308"
result += page;
}
if (i != (pages.length-1)) { // don't add ',' after last one
result += ",";
}
}
return result; // result = "309,306,308,337,338"
}
For example this function when called as follows:
String result1 = Get_PageNumbers("309\\306\\308\\337_338");
String result2 = Get_PageNumbers("311\\315_316\\336_337");
String result3 = Get_PageNumbers("310");
Returns:
309,306,308,337,338
311,315,316,336,337
310
if i can suggest different implementation....
first, split string with "\" str.split("\\");, here you receive an array string with single number or a pattern like "num_num"
for all string founded, if string NOT contains "" char, put string in another array (othArr named), than, you split again with "" str.split("_");, now you have a 2 position array
convert that 2 strings in integer
now create a loot to min val form max val or two strings converted (and put it into othArr)
tranform othArr in a string separated with ","

Categories

Resources