How to limit added data by looping in sqlite android
I have a program that can retrieve values in a sqlite table using ArrayList
. I’m retrieving string data from it and calculating the length of the string. If the total number of strings is less than or equal to 160, the string is concatenated to another piece of data. If the total number of strings is greater than 160, the string is not added.
The concept is this:
- Retrieves the string
- The variable a (which will save the string) concatenates the retrieved string to it.
- Check that the length of a is less than or equal to 160. If less than , return step (1) and stop the connection if not.
Updated
- If you stop the connection, the string is stored.
- Continue processing the remaining strings in the pending list.
However, if the length is more than 160, my program just adds all the strings, not even counting. Here is my code :
List<Pending> pending = db.getAllPending();
String a="";
do{
for (Pending pn : pending) {
a += pn.getPm_str();
}
}while(a.length()<=160);
Log.d("s", a);
Logic Cat:
RBSN/C1/12/3/4/8,CVTE/C1/2/3/4/1,RBSN/C1/4/2131/331/12,RBSN/C1/45/67/12/44,RBSN/C1/44/231/123/23213,RBSN/C1/444/55522/222/11,RBSN/C1/123/123/213123/1231232,RBSN/C1/ 2/3/1/1,RBSN/C1/123/123/213123/1231232,
(string length is 172.)
The expected output should be
RBSN/C1/12/3/4/8,CVTE/C1/2/3/4/1,RBSN/C1/4/2131/331/12,RBSN/C1/45/67/12/44,RBSN/C1/44/231/123/23213,RBSN/C1/444/55522/222/11,RBSN/C1/123/123/213123/1231232,RBSN/C1/ 2/3/1/1,
(string length is 156.)
Follow up on issues
Also, if I want to repeat the same process again, but this time the process affects strings that are not included in the first 160, what should I do?
Solution
In Java
, never Concatenate Strings
inside a loop, not this, use StringBuilder
And check after each iteration if you need to add more strings:
List<Pending> pending = db.getAllPending();
StringBuilder a = new StringBuilder();
for (Pending pn : pending) {
a.append(pn.getPm_str());
if (a.length > 160) break;
}
Log.d("s", a.toString());