RejectedExecutionException when loading bitmaps for ListView with asyncTask - java

I'm trying to create a ListView with bitmaps that are generated on demand. I'm using https://github.com/chrisbanes/Android-BitmapCache to cache the bitmaps
I'm using a SimpleAdapter, with this :
setViewBinder(new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object object,String string) {
if( string.startsWith("ClassName:") ){
final ImageView yourImageView=(ImageView) view;
AsyncTask<String, Void, Bitmap> imageLoadAsyncTask = new AsyncTask<String, Void, Bitmap>() {
String cname;
#Override
protected Bitmap doInBackground(String... classnames) {
cname=classnames[0];
return db.getCharIcon(classnames[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
yourImageView.setImageBitmap(bitmap);
}
};
imageLoadAsyncTask.execute(string.substring(TextUtils.getTrimmedLength("ClassName:")));
return true;
}
return false;
}
}
the getCharIcon function is here :
Bitmap getCharIcon(String classname){
Bitmap modBmp;
CacheableBitmapDrawable cacheBmp=mCache.get(classname);
if(cacheBmp==null)
{
modBmp=createCharIcon(classname);
mCache.put(classname,modBmp);
}
else
{
modBmp=cacheBmp.getBitmap();
}
return modBmp;
}
where createCharIcon generates the bitmap this way (I have yet to implement the final version that selects the good portion of the image):
Bitmap createCharIcon(String classname)
{
Bitmap modBmp = Bitmap.createBitmap(srcBmp,0,0,60,60);
return modBmp;
}
Sadly I am getting this error :
07-02 14:13:04.248 11592-11592/com.lectem.gecharacters E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.util.concurrent.RejectedExecutionException
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1876)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:774)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1295)
at android.os.AsyncTask.execute(AsyncTask.java:394)
at com.lectem.gecharacters.CharFragment$1.setViewValue(CharFragment.java:110)
at android.widget.SimpleAdapter.bindView(SimpleAdapter.java:168)
at android.widget.SimpleAdapter.createViewFromResource(SimpleAdapter.java:126)
at android.widget.SimpleAdapter.getView(SimpleAdapter.java:114)
at android.widget.AbsListView.obtainView(AbsListView.java:1294)
at android.widget.ListView.makeAndAddView(ListView.java:1730)
at android.widget.ListView.fillDown(ListView.java:655)
at android.widget.ListView.fillSpecific(ListView.java:1287)
at android.widget.ListView.layoutChildren(ListView.java:1573)
at android.widget.AbsListView.onLayout(AbsListView.java:1147)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1252)
at android.widget.LinearLayout.layoutHorizontal(LinearLayout.java:1241)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1047)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1252)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1128)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1045)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.view.ViewRoot.performTraversals(ViewRoot.java:1045)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
I get this error when I scroll the list back too fast, so I suppose it is linked with the number of asyncTasks I can use...
I'm really not sure if this is how I should do it or not, but the library bitmapLruCache needs to be ran on something else than the main thread.

Usually, that error means that you are trying to use too many AsyncTasks at once. In an AdapterView, this can occur if you are forking an AsyncTask for every item (e.g., every row in a ListView) without taking into account row recycling, and the user flings the list.
Quoting the library's documentation:
If you wish for the library and recycling feature to work, you MUST use the bundled CacheableImageView wherever possible.
Since you appear to be using this in an AdapterView, please make sure that you are using CacheableImageView.

Related

Crash caused by animation cancel()

I have 2 animations, slide[1] and slide[3], and when I try to cancel them when the animation repeats itself, it causes a crash. here is some relevant code:
slide[1].setDuration(500); slide[1].setStartDelay(500);
slide[3].setDuration(500); slide[3].setStartDelay(500);
slide[1].addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
if (!start) {
table[2][2].setBackgroundResource(R.drawable.black);
slide[1].setDuration(1000);
slide[1].setStartDelay(0);
slide[3].setDuration(1000);
slide[3].setStartDelay(0);
slide[1].removeAllListeners();
slide[3].cancel();
slide[1].cancel();
}
}
#Override
public void onAnimationEnd(Animator animation) {
}
}); slide[1].start(); slide[3].start();
The line which causes the crash is "slide[1].cancel();", and I don't know why.
Apparently the crash is being caused when the phone is running on JellyBean, but not Marshmallow for example.
How can I solve this problem?
Thanks!
UPDATE: here is the logcat:
03-13 16:18:01.943 1623-1623/com.example.ohad.squerz E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at android.animation.ValueAnimator$AnimationHandler.doAnimationFrame(ValueAnimator.java:603)
at android.animation.ValueAnimator$AnimationHandler.run(ValueAnimator.java:639)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
at android.view.Choreographer.doCallbacks(Choreographer.java:555)
at android.view.Choreographer.doFrame(Choreographer.java:524)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
This crash has been fixed in AOSP in this commit.
If you want to support API 16, you need to cancel your animations somewhere else than in onAnimationUpdate/onAnimationRepeat.
In your case (if it matters, because this answer comes a long time after your question), you probably want to avoid the repeat on your first animator, using setRepeatCount(0).

My AsyncTask in another class is causing NullPointerException when it is called in this class

I am quite new to android development and I am facing a NullPointerException when I am trying to call an AsyncTask which is an inner class in another class.
I believe it is the way I am instantiating it but this is what I have:
// This onClick is in my adapter class - which is a separate Java File and class
#Override
public void onClick(View v) {
UploadRes uploadRes = new UploadRes();
UploadRes.UploadResConfirm uploadResConfirm = uploadRes.new UploadResConfirm(v.getContext());
uploadResConfirm.execute(fileName, filePath);
}
public class UploadResConfirm extends AsyncTask<String, String, String> {
Dialog dialog;
Context context;
public UploadResConfirm(Context context){
this.context = context;
}
#Override
protected void onPreExecute(){
dialog = new Dialog(UploadRes.this);
dialog.setTitle("Currently uploading");
dialog.show();
}
I believe it has got something to do with the dialog box itself being instantiated in the AsyncTask class.
The error stack trace on Logcat - its the Dialog, I think its in the wrong place...
java.lang.NullPointerException
at codeman.androapp.UploadRes$UploadResConfirm.onPreExecute(UploadRes.java:246)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
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:5103)
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)
Some help if any would be much obliged.
Instead of dialog = new Dialog(UploadRes.this);
Try
dialog = new Dialog(context);
your are passing a wrong context to create dialog.

ListViewAnimation insert() NullPointerException on notifyDataSetChanged()

I'm using the ListViewAnimation library and been trying to do the add-item animation for my ListView.
In order to implement such animation, their documentation says that I should do this:
To use this functionality, simply let your adapter implement Insertable, and call one of the insert methods on the DynamicListView:
MyInsertableAdapter myAdapter = new MyInsertableAdapter(); // MyInsertableAdapter implements Insertable
mDynamicListView.setAdapter(myAdapter);
mDynamicListView.insert(0, myItem); // myItem is of the type the adapter represents.
So here's what I did:
I had my Listview be a DynamicListView(I'm using ButterKnife) and set it to use my adapter
#InjectView(R.id.flow_list)
DynamicListView mFlowList;
mFlowListAdapter = new FlowListAdapter(getActivity(), mItems);
mFlowList.setAdapter(mFlowListAdapter);
Made my adapter implement the 'Insertable' interface and overridden its abstract method:
#Override
public void add(int i, #NonNull Object o) {
Item newItem = (Item)o;
mList.add(Item);
notifyDataSetChanged();
}
Call insert() on my ListView
#OnClick(R.id.done)
void addItem() {
...
mFlowList.insert(0,item);
}
But when I ran my app and clicked that done button that triggers the insert() of my ListView I got a NullPointerException saying:
09-15 11:51:41.046 14660-14660/com.jezer.MyApp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.nhaarman.listviewanimations.itemmanipulation.animateaddition.AnimateAdditionAdapter$HeightUpdater.onAnimationUpdate(AnimateAdditionAdapter.java:352)
at com.nineoldandroids.animation.ValueAnimator.animateValue(ValueAnimator.java:1178)
at com.nineoldandroids.animation.ValueAnimator.animationFrame(ValueAnimator.java:1139)
at com.nineoldandroids.animation.ValueAnimator.setCurrentPlayTime(ValueAnimator.java:545)
at com.nineoldandroids.animation.ValueAnimator.start(ValueAnimator.java:928)
at com.nineoldandroids.animation.ValueAnimator.start(ValueAnimator.java:951)
at com.nineoldandroids.animation.AnimatorSet.start(AnimatorSet.java:502)
at com.nineoldandroids.animation.AnimatorSet.start(AnimatorSet.java:502)
at com.nhaarman.listviewanimations.itemmanipulation.animateaddition.AnimateAdditionAdapter.getView(AnimateAdditionAdapter.java:318)
at android.widget.AbsListView.obtainView(AbsListView.java:2232)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1253)
at android.widget.ListView.onMeasure(ListView.java:1162)
at android.view.View.measure(View.java:15775)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:681)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:15775)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4942)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15775)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4942)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15775)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:850)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:15775)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4942)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2193)
at android.view.View.measure(View.java:15775)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2212)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1291)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1486)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1181)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4942)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
at android.view.Choreographer.doCallbacks(Choreographer.java:579)
at android.view.Choreographer.doFrame(Choreographer.java:548)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5391)
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:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
I'm not getting this exception when I commented out the notifyDataSetChanged() on the add() method. However that's the only way I know to refresh my listview and hopefully see an addition animation to it.
Are you perhaps doing this:
convertView = inflater.inflate(R.layout.cell, null);
Instead of this? convertView = inflater.inflate(R.layout.page_cell, parent, false);

Create Dialog Box For Checking Internet Connection in Android

I'm implementing to show dialog box when Internet is offline, when i run my app i got "FATAL Exception main" and ClassCastException when when i click on button and application is crash . Can someone tell me what i am doing wrong ? Thanks to you in Advanced.
here is code how i check is internet enabled or not:
public class AndroidDetectInternetConnectionActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStatus = (Button) findViewById(R.id.btn_check);
btnStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isOnline())
{
showNoConnectionDialog(this);
}
}
});
}
public static void showNoConnectionDialog(OnClickListener onClickListener)
{
final Context ctx = (Context) onClickListener;
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setCancelable(true);
builder.setMessage(R.string.no_connection);
builder.setTitle(R.string.no_connection_title);
builder.setPositiveButton(R.string.settings_button_text, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton(R.string.cancel_button_text, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
public boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
{
return true;
}
return false;
}
}
// This is my Log Cat stack trace
11-15 11:57:19.115: D/AndroidRuntime(453): Shutting down VM
11-15 11:57:19.115: W/dalvikvm(453): threadid=1: thread exiting with uncaught exception (group=0x40015560)
11-15 11:57:19.122: E/AndroidRuntime(453): FATAL EXCEPTION: main
11-15 11:57:19.122: E/AndroidRuntime(453): java.lang.ClassCastException: com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity$1
11-15 11:57:19.122: E/AndroidRuntime(453): at com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity.showNoConnectionDialog(AndroidDetectInternetConnectionActivity.java:99)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity$1.onClick(AndroidDetectInternetConnectionActivity.java:64)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.view.View.performClick(View.java:2485)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.view.View$PerformClick.run(View.java:9080)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Handler.handleCallback(Handler.java:587)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Handler.dispatchMessage(Handler.java:92)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Looper.loop(Looper.java:123)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.app.ActivityThread.main(ActivityThread.java:3683)
11-15 11:57:19.122: E/AndroidRuntime(453): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 11:57:19.122: E/AndroidRuntime(453): at java.lang.reflect.Method.invoke(Method.java:507)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-15 11:57:19.122: E/AndroidRuntime(453): at dalvik.system.NativeStart.main(Native Method)
11-15 11:57:24.892: I/Process(453): Sending signal. PID: 453 SIG: 9
change this line
final Context ctx = (Context) onClickListener;
to below one
final Context ctx = AndroidDetectInternetConnectionActivity.this;
basically you are trying to conver onClickListener to Contex which is incorrect and can not be casted.
Either you directly use ActivityName.this wherever you need context instance, or define static Context ctx as a class variable and intialize it in onCreate()by just adding this line ctx =this also remember to intialize it before using it.
Enjoy
There are two ways to solve this problem.
1) showNoConnectionDialog(this); and later on:
public static void showNoConnectionDialog(Context ctx) ...
2) showNoConnectionDialog(); and later on: public void showNoConnectionDialog() { Context ctx = AndroidDetectInternetConnectionActivity.this
You basic problem is generated by the line:
final Context ctx = (Context) onClickListener;
This is simply not a context so trying to force it to be one doesn't work.
I believe that you wanted to do was pass a context (or activity) to this function (as opposed to the local unnamed OnClickListener class that you are now passing)
The easiest solution would be to simple not pass anything to the constructor and use AndroidDetectInternetConnectionActivity.this to access your valid context.

OnListItemClick NullpointerException

Hello I am currently getting error on some of my apps on android market :
This is the stacktrace :
java.lang.NullPointerException
at ****.****.MainActivity.onListItemClick(MainActivity.java:110)
at android.app.ListActivity$2.onItemClick(ListActivity.java:319)
at android.widget.AdapterView.performItemClick(AdapterView.java:284)
at android.widget.ListView.performItemClick(ListView.java:3513)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:1812)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:870)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
at dalvik.system.NativeStart.main(Native Method)
The code part where it goes wrong :
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
mMediaPlayer.stop();
Sound s = (Sound) l.getItemAtPosition(position);
mMediaPlayer = MediaPlayer.create(this, s.getSoundResourceId());
mMediaPlayer.start();
}
Mostly of the time it's working (playing sounds) but sometimes it gives a nullpointerexception and I don't know why maybe something with the MediaPlayer or super.onListItemClick() ?
Thanks in advance
Probably s is null? Can you reproduce/debug?
could you provide the code of getItemAtPosition(position) of your list adapter implementation. and may wrap
if (s != null) {
mMediaPlayer = MediaPlayer.create(this, s.getSoundResourceId());
mMediaPlayer.start();
}
edit. hmm i was on the wrong line. you should wrap starting the media player with a null check because if you read the doc:
Returns
a MediaPlayer object, or null if creation failed
And then try to find out why creation fails.

Categories