Reputation: 1241
I am developing application using the SQLite database. I have the following code for getting the database all the values.
ArrayList<String> values=new ArrayList<String>();
String[] ColumnNames;
String selectQuery="SELECT * FROM "+tableName;
Cursor cursor=sDataBase.rawQuery(selectQuery, null);
if(cursor!=null && cursor.getColumnCount()>0 && cursor.getCount()>0){
ColumnNames=cursor.getColumnNames();
if (cursor.moveToFirst()){
do{
String value="";
for(int i=0;i<cursor.getColumnCount();i++){
if(value!="")
value=value +", \\\""+ColumnNames[i]+"\\\":\\\"" + cursor.getString(i)+"\\\"";
else
value= "\\\""+ ColumnNames[i] +"\\\":\\\"" + cursor.getString(i) +"\\\"";
}
value="{" + value + "}";
values.add(value);
}while(cursor.moveToNext());
}
cursor.close();
}
If the database size is more than 1MB, the app is getting crashed. How can I get the database values more than 1 MB.?
EDIT1:
Logcat values:
10-10 14:46:24.863: E/dalvikvm-heap(3248): Out of memory on a 6612888-byte allocation.
EDIT2:
Code using the stringbuffer
if(cursor!=null && cursor.getColumnCount()>0 && cursor.getCount()>0)
{
ColumnNames=cursor.getColumnNames();
if (cursor.moveToFirst()){
do{
StringBuffer value= new StringBuffer();
value.append("{");
for(int i=0;i<cursor.getColumnCount();i++)
{
if(value.length()>1)
value.append(", \\\""+ColumnNames[i]+"\\\":\\\"" + cursor.getString(i)+"\\\"");
else
value.append("\\\""+ ColumnNames[i] +"\\\":\\\"" + cursor.getString(i) +"\\\"");
}
value.append(value + "}");
values.add(value);
}while(cursor.moveToNext());
}
cursor.close();
}
Length of the value StringBuffer is 4860024.
Upvotes: 0
Views: 1066
Reputation: 60681
Well, it's clear that you're just running out of memory. You are building up a String representation of the database using a series of immutable String
objects.
String value="";
Every time you do a string concatenation, value=value +", \\\""
you are creating a new String
object. This is very inefficient in terms of memory usage.
Try using a StringBuilder
instead of a String
, and use its append()
method instead of the string concatenation operator +
. This will allow the string to be built up in a single buffer (which will grow as needed), which makes it much more likely to fit in the available heap memory.
Upvotes: 1