I'm working on an application that fetches data from a bluetooth device. But sometimes it throws OOM error while performing some operation
Here is the code
The Following way I am storing the data in an ArrayList<String>
private ArrayList<String> dataList;
if (response.compareTo("Some Filter") != 0 //response is of String type
{
dataList.add(response);
}
And in the below for each
loop it throws OOM error
for (String s : dataList) {
if(s.length()>8)
dataList.set(dataList.indexOf(s), s.substring(8));
else
dataList.set(dataList.indexOf(s), "");
}
String downloadedData = "";
for (String s : dataList) {
downloadedData += s; //This one is the 280th line throwing OOM
}
So far I have read this post but it gives solutions for reading data in json or web response
And i know OOM error can't be handled but prevented by following a good Architecture
And there are also these two Callbacks for Android
But i am not sure how to go for the solution !!
The crash Stacktrace is:
java.lang.OutOfMemoryError: Failed to allocate a 106990 byte allocation with 5840 free bytes and 5KB until OOM
at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95)
java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:146)
at java.lang.StringBuilder.append(StringBuilder.java:216)
at Class_name.java:280.
Any help is appreciated :)
First: if (response.compareTo("Some Filter") != 0 )
that is just weird, you can just use equals
method.
Then you are adding response to the list, and then you are reducing length of all responses in a list if they are higher than 8 (also, you did substring(8)
, that trims the first 8 letters and I think you wanted to preserve first 8 letters and delete the rest, if yes then do this substring(0, 8)
).
My answer is: why not just take care of the things you are doing in a for-each
when you are adding it to a list? It would be a lot easier and it would be better performance-wise, and would probably fix your error.
Also, I'm not sure if you are initializing your list, maybe you just forgot to paste it (all you have is private ArrayList<String> dataList;
), but that's how you make a new list:
List<String> list = new ArrayList<String>();
First your loop should use
for (int i = 0; i < dataList.size(); ++i) {
String s = dataList.get(i);
dataList.set(i, s.length() > 8 ? s.substring(8) : "");
}
And the error points in another direction.
Try it is working
ArrayList<String> dataList = new ArrayList<>();
String response = "CVMKVLC";
if (response.compareTo("Some Filter") != 0 ) {
//response is of String type
dataList.add(response);
}
for (String s : dataList) { //This line throws OOM
if(s.length()>8)
dataList.set(dataList.indexOf(s), s.substring(8));
else
dataList.set(dataList.indexOf(s), "");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.