0

Hi i am reading sqlite db data and store into string buffer. I want to display it in the list view in android. i am facing little problem. please help me to solve this issue.

String studentno=cursor.getString(1);
String date=cursor.getString(2);
buffer.append("student: "+studentno+"  Time:"+date+"\n");
String data=buffer.toString();
Log.d("student: "+studentno+"  Time:"+date);

the output is:student: 1234 Time:12:13 student: 1234 Time:12:14 student: 1234 Time:12:15

I want to store string buffer like this values[0]=student: 1234 Time:12:13 values[1]=student: 1234 Time:12:14 values[2]=student: 1234 Time:12:15

i tried below coding but its not working.

String[] values = data.split("");
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}

is there any way to do this. thanks in advance.

subramaniam
  • 49
  • 3
  • 12

3 Answers3

2

You seem to be adding the data into the buffer with new line delimiter at the end. Splitting them should look like this: data.split("\n");

This does not seem like a good idea, however. Mainly because you can have a very large data set and split is an expensive operation.

Why not create an ArrayList<String> and call list.add("student: " + studentno + " Time: " + date) or some other more efficient structure?

Code:

List<String> list = new ArrayList<String>();

String studentno=cursor.getString(1);
String date=cursor.getString(2);
list.add("student: " + studentno + " Time: " + date);
Smajl
  • 7,555
  • 29
  • 108
  • 179
1

This makes no sense. If you want to store the data in an array, don't store it in a StringBuffer in the first place. Store it directly in the array.

You must have some loop in which you read the data :

String[] arr = new String [...];
int count = 0;
while (cursor.next() && count < arr.length) {
    String studentno=cursor.getString(1);
    String date=cursor.getString(2);
    arr[count] = "student: "+studentno+"  Time:"+date+"\n";
    count++;
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • How can you explain me in detail. I used data.split("\n"); its working now Eran. – subramaniam Mar 12 '15 at 13:06
  • its working Eran. but i cant know the string array size. we cant give predefine size.we dont know how many data will come from db. how can i give dynamic size. if i am wrong, pls correct me. – subramaniam Mar 12 '15 at 13:20
  • @subramaniam In that case, you can add the data to an ArrayList (whose capacity is dynamic) and then convert to an array with the toArray method. – Eran Mar 12 '15 at 13:22
  • @Eran i have same problem can u solve it plz.......http://stackoverflow.com/questions/40948014/how-to-convert-single-string-to-jsonarray-in-android – Secret_Volcano Dec 04 '16 at 11:00
0

You could try to replace your split call with this:

String[] values = data.split("\n");
teemann
  • 106
  • 1
  • 4