NoSuchElementException while Iterating - java

I have been struck with Iterator for past few hours.
While I execute Iterator, am getting NoSuchElementException
Code
new Thread() {
#Override
public void run() {
System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
final HashSet<String> mList = new HashSet<String>();
for (SomeList sList : refList) { // <-- 72 Items
if (sList.isTrue()) {
mList.add(sList.getName());
}
}
System.out.println("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww");
System.out.println("sList " + sList.size()); // <-- 3 Items
final Iterator<String> iterator = mList.iterator();
while (iterator.hasNext()) { // Check if has next element
runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println("zzzzzzzzzzzzzz");
System.out.println("\n-------------------- " + (String) iterator.next()); //move to next element
}
});
}
}
}.start();
Logcat
D/dalvikvm(25527): start new thread
D/dalvikvm(25527): threadid=13: notify debugger
D/dalvikvm(25527): threadid=13 (Thread-4167): calling run()
I/System.out(25527): xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
I/System.out(25527): wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
I/System.out(25527): mList 3 <-- Size of List
I/System.out(25527): yyyyyyyyyyyyyyyyyyyyyy
I/System.out(25527): yyyyyyyyyyyyyyyyyyyyyy
// Prints around 80 times removed for better readability
I/System.out(25527): yyyyyyyyyyyyyyyyyyyyyy
I/System.out(25527): yyyyyyyyyyyyyyyyyyyyyy
I/System.out(25527): zzzzzzzzzzzzzz
I/System.out(25527): -------------------- abc <-- data 1
I/System.out(25527): yyyyyyyyyyyyyyyyyyyyyy
I/System.out(25527): zzzzzzzzzzzzzz
I/System.out(25527): -------------------- efg <-- data 2
I/System.out(25527): zzzzzzzzzzzzzz
I/System.out(25527): -------------------- hij <-- data 3
I/System.out(25527): zzzzzzzzzzzzzz
D/AndroidRuntime(25527): Shutting down VM
W/dalvikvm(25527): threadid=1: thread exiting with uncaught exception (group=0x41c5c9a8)
D/dalvikvm(25527): threadid=13: exiting
D/dalvikvm(25527): threadid=13: bye!
E/AndroidRuntime(25527): FATAL EXCEPTION: main
E/AndroidRuntime(25527): java.util.NoSuchElementException
E/AndroidRuntime(25527): at java.util.HashMap$HashIterator.nextEntry(HashMap.java:794)
E/AndroidRuntime(25527): at java.util.HashMap$KeyIterator.next(HashMap.java:819)
E/AndroidRuntime(25527): at xxx.xxx.xxxxxx.models.YYYYY$1$1.run(YYYYY.java:62) <-- Here is the exception.
E/AndroidRuntime(25527): at android.os.Handler.handleCallback(Handler.java:725)
E/AndroidRuntime(25527): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(25527): at android.os.Looper.loop(Looper.java:153)
E/AndroidRuntime(25527): at android.app.ActivityThread.main(ActivityThread.java:5299)
E/AndroidRuntime(25527): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(25527): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(25527): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
E/AndroidRuntime(25527): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
E/AndroidRuntime(25527): at dalvik.system.NativeStart.main(Native Method)
Line 62 in my code is
System.out.println("\n-------------------- " + (String) iterator.next());
Before posting this question I searched for NoSuchElementException, Iterator, tried most of the results but did not succeed.

There is a concurrency issue here:
while (iterator.hasNext()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
(String) iterator.next();
}
});
}
Because hasNext and next are not called on the same thread, you cannot be guaranteed that there will actually be a next when you call next().
The loop will run several times without the iterator being advanced, resulting in more creation of Runnables than items in the iterator, which in turn results in next being called more times than should be.
You can solve it using the following:
while (iterator.hasNext()) {
final String nextValue = (String) iterator.next();
runOnUiThread(new Runnable() {
#Override
public void run() {
// Do stuff with nextValue
}
});
}
which calls hasNext and next in the same thread, making sure each hasNext is immediately matched by a call to next

Related

java.util.ArrayList$ArrayListIterator.next android

I have update from database using set status method when click button to getting error i have send to array list to next activity while getting error
I'm new in android programming
ImageButton ibAddMore = (ImageButton) findViewById(R.id.ibAddMore);
ibAddMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper db = new DataBaseHelper(getApplicationContext());
for (People people : alertList) {//In this Line getting error
if (people.getStatus() == 1) {
db.setStatus(people.getId(), "0");
alertList.add(people);
} else {
db.setStatus(people.getId(), "1");
}
}
Intent intent = new Intent(AlertList.this, AlertListAll.class);
startActivity(intent);
}
}
);
Set Status Method
public int setStatus(String peopleId, String status) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(STATUS, status);
return sqLiteDatabase.update(TABLE_PEOPLE, values, ID + "=?",
new String[]{peopleId});
}
Exception:
java.util.ConcurrentModificationException
at java.util.AbstractList$SimpleListIterator.next(AbstractList.java:62)
at com.Jaydeep.alertme.activity.AlertList$1.onClick(AlertList.java:67)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5136)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
you can't modify the same collection you are looping on directly. But you can do it using a ListIterator. E.g.
for (ListIterator<People> iterator = alertList.listIterator(); iterator.hasNext(); ) {//In this Line getting error
People people = iterator.next();
if (people.getStatus() == 1) {
db.setStatus(people.getId(), "0");
iterator.add(people);
} else {
db.setStatus(people.getId(), "1");
}
}
You are adding elements to the same list while you are iterating. It's more java than android.
Btw why you want to add the same element again to the list you are iterating thru ?

OutOfMemoryError in android while change in orientation?

I am new in android.i am loading data from json. While on orientation change destroy and recreate the activity so the json loading everytime orientation changing..
I am getting the following error:
{
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.OutOfMemoryError at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:94)
at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:145)
at java.lang.StringBuilder.append(StringBuilder.java:202)
at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
at org.json.JSONTokener.nextValue(JSONTokener.java:97)
at org.json.JSONTokener.readObject(JSONTokener.java:362)
at org.json.JSONTokener.nextValue(JSONTokener.java:100)
at org.json.JSONTokener.readObject(JSONTokener.java:385)
at org.json.JSONTokener.nextValue(JSONTokener.java:100)
at org.json.JSONTokener.readArray(JSONTokener.java:430)
at org.json.JSONTokener.nextValue(JSONTokener.java:103)
at org.json.JSONTokener.readObject(JSONTokener.java:385)
at org.json.JSONTokener.nextValue(JSONTokener.java:100)
at org.json.JSONObject.<init>(JSONObject.java:154)
at org.json.JSONObject.<init>(JSONObject.java:171)
at com.ProjectName.activities.MainActivity.get_Project_Json(MainActivity.java:238)
at com.ProjectName.activities.MainActivity.onCreate(MainActivity.java:115)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3692)
at android.app.ActivityThread.access$700(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1240)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
}
especially in JellyBean and KitKat (Device:3.2 to 4.0inches)
{
public void get_Json_Assets() {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open("Somejson.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (OutOfMemoryError e) {
e.fillInStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (Exception e) {
e.fillInStackTrace();
}
}
all_Point_Json = sb.toString();
}
}
{`public void get_Project_Json() {
get_Json_Assets();
try {
JSONObject point_Json= new JSONObject(all_Point_Json);
JSONArray point_Chapter =point_Json.getJSONArray("chapter");
for (int i = 0; i < point_Chapter.length(); i++) {
HashMap<String, String> mPoint_Details = new HashMap<>();
mPoint_Details.put("mPoint", (String) point_Chapter.get(i));
mPoint_Details.put("mPoint_No", String.valueOf(i + 1));
All_Point.add(mPoint_Details);
}
} catch (JSONException e) {
e.fillInStackTrace();
}
}`}
First of all, your code is very messy. You should clean it up. Moreover, I don't know in which part of Activity life cycle are you calling this code. I suppose, you're doing it in onResume() or onCreate() method. Probably this *.json file contains a lot of data and you are allocating memory for it. During screen rotation, you're doing it again, after next rotation, memory is allocated again and so on. You should clean memory in onPause() method or load this data in a different way (e.g. in the Service and then pass it to Activity). In addition, you should avoid loading large files at once. You can consider loading parts of that file successively and for sure load this data in a separate thread (e.g. with AsyncTask or RxJava if you're familiar with it), because it's non-deterministic and probably a long operation.

Exception : Caused by: java.lang.NullPointerException: asset

I am reading the .OBJ file which is in asset folder. But I am getting exception while reading the file. Even I debug the project on eclipse but I could find the reason for this.
Please help me
Thanks in advance.
/**
* Load Object Asynchronous.
* #author Ajay
*/
private class ObjLoaderAsync extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
try {
progressDialog = new ProgressDialog(localContext);
progressDialog.setTitle(localContext
.getString(R.string.app_name));
progressDialog.setMessage(localContext
.getString(R.string.please_wait));
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
progressDialog.show();
} catch (Exception e) {
}
}
#Override
protected Void doInBackground(Void... arg0) {
try {
mr[getCurrentPosition()] = new ModelRenderer(localContext,
localContext.getAssets().open(RendererView.objName));
} catch (java.io.IOException e) {
Log.v("DemoRendererView", "loading model: " + e);
}
return null;
}
#Override
protected void onPostExecute(Void param) {
try {
progressDialog.cancel();
} catch (Exception e) {
}
}
}
public ModelRenderer(Context paramContext, InputStream localFileInputStream) throws FileNotFoundException {
ModelStaticClassTransfer.value = -777.0F;
while (true) {
try {
i = localFileInputStream.read();
if (i != -1)
continue;
localFileInputStream.close();
if ((char) i == 'v') {
i = localFileInputStream.read();
if ((char) i != ' ')
continue;
this.verticeCounter = (1 + this.verticeCounter);
continue;
}
if ((char) i == 'f') {
i = localFileInputStream.read();
if ((char) i != ' ')
continue;
this.indexCounter = (1 + this.indexCounter);
continue;
}
int j = localFileInputStream.read();
i = j;
} catch (IOException localIOException) {
localIOException.printStackTrace();
return;
}
}
}
Error Trace
09-12 12:54:57.516: E/AndroidRuntime(29949): FATAL EXCEPTION: AsyncTask #2
09-12 12:54:57.516: E/AndroidRuntime(29949): java.lang.RuntimeException: An error occured while executing doInBackground()
09-12 12:54:57.516: E/AndroidRuntime(29949): at android.os.AsyncTask$3.done(AsyncTask.java:278)
09-12 12:54:57.516: E/AndroidRuntime(29949): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
09-12 12:54:57.516: E/AndroidRuntime(29949): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
09-12 12:54:57.516: E/AndroidRuntime(29949): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
09-12 12:54:57.516: E/AndroidRuntime(29949): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-12 12:54:57.516: E/AndroidRuntime(29949): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
09-12 12:54:57.516: E/AndroidRuntime(29949): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
09-12 12:54:57.516: E/AndroidRuntime(29949): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
09-12 12:54:57.516: E/AndroidRuntime(29949): at java.lang.Thread.run(Thread.java:856)
09-12 12:54:57.516: E/AndroidRuntime(29949): Caused by: java.lang.NullPointerException: asset
09-12 12:54:57.516: E/AndroidRuntime(29949): at android.content.res.AssetManager.readAssetChar(Native Method)
09-12 12:54:57.516: E/AndroidRuntime(29949): at android.content.res.AssetManager.access$200(AssetManager.java:35)
09-12 12:54:57.516: E/AndroidRuntime(29949): at android.content.res.AssetManager$AssetInputStream.read(AssetManager.java:548)
09-12 12:54:57.516: E/AndroidRuntime(29949): at com.amplimesh.models.ModelRenderer.<init>(ModelRenderer.java:64)
09-12 12:54:57.516: E/AndroidRuntime(29949): at com.amplimesh.models.ModelGLRenderer$ObjLoaderAsync.doInBackground(ModelGLRenderer.java:138)
09-12 12:54:57.516: E/AndroidRuntime(29949): at com.amplimesh.models.ModelGLRenderer$ObjLoaderAsync.doInBackground(ModelGLRenderer.java:1)
09-12 12:54:57.516: E/AndroidRuntime(29949): at android.os.AsyncTask$2.call(AsyncTask.java:264)
09-12 12:54:57.516: E/AndroidRuntime(29949): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-12 12:54:57.516: E/AndroidRuntime(29949): ... 5 more
I think you are mistaken with the meaning of the continue keyword. This keyword means that the loop jumps immediately to the next iteration without executing the rest of the code in the loop block.
In your case, it means that this code
i = localFileInputStream.read();
if (i != -1)
continue;
localFileInputStream.close();
if ((char) i == 'v') {
i = localFileInputStream.read();
closes the inputStream, and then tries to read from it. You algorithm is not very clear because of all the continues, so I can't really tell you how to fix that.
#Override
protected void onPostExecute(Void param) {
try {
mr[getCurrentPosition()] = new ModelRenderer(localContext,
localContext.getAssets().open(RendererView.objName));
dialog.cancle();
} catch (java.io.IOException e) {
Log.v("DemoRendererView", "loading model: " + e);
}
}
please check this...
you start with
try {
i = localFileInputStream.read();
if (i != -1)
continue;
localFileInputStream.close();
so, you are closing the stream and after that you are trying to read again from it. Also you are running this inside an infinite loop and exit from it only in a the catch section. Consider closing the stream after you are done reading it.

IndexOutOfBound Exception throwing Android

i have make one android application in that data is coming from server so it's time consuming process so i have created one progress dialog box..
below is my code
#Override
protected void onResume() {
super.onResume();
if (placesListItems != null)
placesListItems.clear();
new LoadPlaces().execute();
}
#Override
public void onPause() {
super.onPause();
if (pDialog != null)
pDialog.dismiss();
}
class LoadPlaces extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
GooglePlaces googlePlaces = new GooglePlaces();
try {
double radius = 1000; // 10000 meters
// get nearest places
if (query != null) {
nearPlaces = googlePlaces.search(lat, lon, radius, query);
if (nearPlaces != null) {
for (Place p : nearPlaces.results) {
reference = p.reference;
lat = p.geometry.location.lat;
lon = p.geometry.location.lng;
break;
}
}
}
String types = "bar|restaurant|night_club|gym|health|food|shopping_mall|hospital";
if (reference != null) {
PlaceDetails placeDetails = googlePlaces.getPlaceDetails(reference);
if (placeDetails != null) {
String status = placeDetails.status;
// check place deatils status
// Check for all possible status
if (status.equals("OK")) {
if (placeDetails.result != null) {
lat = placeDetails.result.geometry.location.lat;
lon = placeDetails.result.geometry.location.lng;
nearDeals = googlePlaces.search(lat, lon, radius, types);
In below code if i press home button or screen goes of during fetching data from server (You can say progress dialog box is running) and if i come back to my application i got an error ARRAY INDEX OUT OF BOUND
// int total = ;
for (int i = nearDeals.results.size() - 1; i >= 0; i--) {
// Log.i("WHAT THE HELL",nearPlaces.results.get(i).name);
if (getResult(nearDeals.results.get(i).name, nearDeals.results.get(i).geometry.location.lat,
nearDeals.results.get(i).geometry.location.lng) == 0) {
// nearDeals.results.add(nearPlaces.results.get(i));
nearDeals.results.remove(i);
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
below is logcat
09-25 18:23:13.429: W/System.err(4375): java.lang.IndexOutOfBoundsException: Invalid index 15, size is 15
09-25 18:23:13.429: W/System.err(4375): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
09-25 18:23:13.429: W/System.err(4375): at java.util.ArrayList.get(ArrayList.java:311)
09-25 18:23:13.429: W/System.err(4375): at com.eheuristics.android.diegodeals.googleplacesandmaps.MainActivity$LoadPlaces.doInBackground(MainActivity.java:204)
09-25 18:23:13.429: W/System.err(4375): at com.eheuristics.android.diegodeals.googleplacesandmaps.MainActivity$LoadPlaces.doInBackground(MainActivity.java:1)
09-25 18:23:13.429: W/System.err(4375): at android.os.AsyncTask$2.call(AsyncTask.java:185)
09-25 18:23:13.439: W/System.err(4375): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
09-25 18:23:13.439: W/System.err(4375): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
09-25 18:23:13.439: W/System.err(4375): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
09-25 18:23:13.439: W/System.err(4375): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
09-25 18:23:13.439: W/System.err(4375): at java.lang.Thread.run(Thread.java:1019)
if i do not press home key, or do not screen goes off during progress dialog box is running then everything is working fine
//After getting solution from all of you, i have done blow like all suggest but i got another error like blow
LoadPlaces ob;
protected void onResume() {
super.onResume();
if (placesListItems != null)
placesListItems.clear();
ob.execute();
}
#Override
public void onPause() {
super.onPause();
if(ob!=null)
if(ob.getStatus() == AsyncTask.Status.RUNNING){
ob.cancel(true);
}
if (pDialog != null)
pDialog.dismiss();
}
then i got error like below
09-25 18:53:30.609: E/AndroidRuntime(4674): java.lang.RuntimeException: Unable to resume activity {com.eheuristics.android.diegodeals/com.eheuristics.android.diegodeals.googleplacesandmaps.MainActivity}: java.lang.IllegalStateException: Cannot execute task: the task is already running.
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2241)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2256)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:965)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.os.Handler.dispatchMessage(Handler.java:99)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.os.Looper.loop(Looper.java:130)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.ActivityThread.main(ActivityThread.java:3835)
09-25 18:53:30.609: E/AndroidRuntime(4674): at java.lang.reflect.Method.invokeNative(Native Method)
09-25 18:53:30.609: E/AndroidRuntime(4674): at java.lang.reflect.Method.invoke(Method.java:507)
09-25 18:53:30.609: E/AndroidRuntime(4674): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
09-25 18:53:30.609: E/AndroidRuntime(4674): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
09-25 18:53:30.609: E/AndroidRuntime(4674): at dalvik.system.NativeStart.main(Native Method)
09-25 18:53:30.609: E/AndroidRuntime(4674): Caused by: java.lang.IllegalStateException: Cannot execute task: the task is already running.
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.os.AsyncTask.execute(AsyncTask.java:380)
09-25 18:53:30.609: E/AndroidRuntime(4674): at com.eheuristics.android.diegodeals.googleplacesandmaps.MainActivity.onResume(MainActivity.java:137)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.Activity.performResume(Activity.java:3832)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2231)
09-25 18:53:30.609: E/AndroidRuntime(4674): ... 10 more
You are starting the asynctask every time you show your activity. So, you should cancel the task when exiting (AsyncTask.cancel(true)), or check if it is still running in the onResume method.
In the cases where you get the error onResume() gets called again, starting a new AsyncTask. Now you have multiple AsyncTask simultanously accessing and altering the size of nearDeals.results (you call remove on it). When one asyncTask removes an item from the list, the second asyncTask may run into the ArrayIndexOutOfBounds since the list size has changed.
EDIT: It's actually not the removal of an item, but that you set a new instance of the list in googlePlaces.search and this list may have a different size than the one used by the old asynctask.
Solution: call cancel on your running async tasks in onPause (or in onResume before starting
the new task)

Running out of Memory - bitmap size exceeds VM budget

I have searched a lot for a solution for my up and down buttons and can't seem to get anything working. When using the ImageButtons in the program, I am able to press three ImageButtons before I get OutOfMemoryError. Please any help will be great.
for(int i = 0; i < keys.length; i++)
{
keys[i].setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
for(int down = 0; down < keys.lenght; down++)
{
if(v == keys[down])
{
keys[down].keys[down].setImageResource(drawIDDOWN[down]);
keys[down].setAdjustViewBounds(true);
}
}
}
if(event.getAction() == MotionEvent.ACTION_UP)
{
for(int up = 0; up < keys.length; up++)
{
if(v == keys[up])
{
keys[up].setImageResource(drawIDUP[up]);
keys[up].setAdjustViewBounds(true);
}
}
}
return false;
}
});
}
Here is the LogCat:
threadid=1: thread exiting with uncaught exception
FATAL EXCEPTION: main
java.lang.OutOfMemoryError: bitmap size exceeds VM budget
android.graphics.Bitmap.nativeCreate(Native Method)
android.graphics.Bitmap.createBitmap(Bitmap.java:477)
android.graphics.Bitmap.createBitmap(Bitmap.java:444)
android.graphics.Bitmap.createScaledBitmap(Bitmap.java:349)
android.graphics.BitmapFactory.finishDecode(BitmapFactory.java:498)
android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:473)
android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:336)
android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:697)
android.content.res.Resources.loadDrawable(Resources.java:1709)
android.content.res.Resources.getDrawable(Resources.java:581)
android.widget.ImageView.resolveUri(ImageView.java:501)
android.widget.ImageView.setImageResource(ImageView.java:280)
f7kidzCalc.com.KidzCalcActivity$1.onTouch(KidzCalcActivity.java:253)
android.view.View.dispatchTouchEvent(View.java:3881)
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent
(PhoneWindow.java:1691)
com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent
(PhoneWindow.java:1125)
android.app.Activity.dispatchTouchEvent(Activity.java:2096)
com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent
(PhoneWindow.java:1675)
android.view.ViewRoot.deliverPointerEvent(ViewRoot.java:2194)
android.view.ViewRoot.handleMessage(ViewRoot.java:1878)
android.os.Handler.dispatchMessage(Handler.java:99)
android.os.Looper.loop(Looper.java:123)
android.app.ActivityThread.main(ActivityThread.java:3683)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:507)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
dalvik.system.NativeStart.main(Native Method)
Is there an easy way to garbage collect, recycle images or just anything? I'm stuck..
Make sure you are not storing the activities or context in any other part of your program. This really messes with your memory management and causes lots of leaks.
You can send pointers to it using methods such as:
Good Form
public void doSomethingtoContext(Context c){
c.getApplicationContext()....//Variable 'c' only lasts for the length of the method
}
Bad Form
public static Context cOnText;
public void doSomethingtoContext(Context c){
cOnText = c; //DO NOT STORE THIS VALUE HERE
}
Basically, what I am trying to say is that, most of the times the image size aren't the problem, but instead something easy to overlook like this case.
Hope this helps.
Good luck!
Reduce the size of the image you are using. I had the exact problem. Image i was using was >500kB. Reduced size is around 50-60kB.

Categories

Resources