I'm using the Retrofit to test and learn it as I have a project on it. While I use https://jsonplaceholder.typicode.com/photos for binding the photo into the recycle view. The issue is I can't scroll above 9 images; I mean whenever I scroll down to the 10th image, it is shown and then the app crashes.
img
2020-03-21 15:11:48.286 9426-9426/navneet.com.carsrecyclerview E/AndroidRuntime: FATAL EXCEPTION: main
Process: navneet.com.carsrecyclerview, PID: 9426
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:714)
at com.pkmmte.view.CircularImageView.refreshBitmapShader(CircularImageView.java:341)
at com.pkmmte.view.CircularImageView.invalidate(CircularImageView.java:262)
at android.widget.ImageView.setImageDrawable(ImageView.java:572)
at com.squareup.picasso.PicassoDrawable.setPlaceholder(PicassoDrawable.java:59)
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:728)
at navneet.com.carsrecyclerview.CarsAdapter.onBindViewHolder(CarsAdapter.java:58)
at navneet.com.carsrecyclerview.CarsAdapter.onBindViewHolder(CarsAdapter.java:24)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
at android.support.v7.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:286)
at android.support.v7.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:343)
at android.support.v7.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:359)
at android.support.v7.widget.GapWorker.prefetch(GapWorker.java:366)
at android.support.v7.widget.GapWorker.run(GapWorker.java:397)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
the issue is similar to Android Picasso image loading app crash when scrolling RecyclerView but my point looks different.
Picasso.get().load(carsModels.get(i).getUrl()).noFade().resize(150,150).into(viewHolder.car_image, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
Toast.makeText(context, "An error occurred", Toast.LENGTH_SHORT).show();
}
});
any help will be appriciated. thank you.
It seems to me that the problem may not be with Picasso. It could be with the third party CircularImageView that you are using. You can put a debug breakpoint at the android.graphics.Bitmap.createScaledBitmap(Bitmap.java:714) and see why the Bitmap object is null there. Then, you can go down the stack trace and figure out why it is null. That will give you a better idea of what you need to do to make sure your Bitmap object is instantiated before hitting that piece of code.
If you do find something, please update here so that I can edit this answer after better understanding the reason for your NullPointerException.
I think its better if you just load the image but the resizing happens on the ImageView end
Picasso.get().load(carsModels.get(i).getUrl()).noFade().into(viewHolder.car_image);
In your case, the car_image ImageView in layout XML should have:
android:layout_width="150dp"
android:layout_height="150dp"
android:scaleType="fitCenter"
android:adjustViewBounds="true"
This ensures that the image you are loading inside is size 150x150 density pixels and making sure it doesn't stretch or look disoriented. It will start fitting in center if you have images that are not of equal aspect ratio.
I hope this helps!
Related
MLImageSegmentationSetting analyzerSetting = (new MLImageSegmentationSetting.Factory()).setExact(true).setAnalyzerType(MLImageSegmentationSetting.BODY_SEG).setScene(2).create();
MLImageSegmentationSetting setting = new MLImageSegmentationSetting.Factory().setAnalyzerType(MLImageSegmentationSetting.BODY_SEG).create();
this.analyzer = MLAnalyzerFactory.getInstance().getImageSegmentationAnalyzer(analyzerSetting);//error on this line
error :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.brandpost.brandpro365, PID: 9861
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2001, result=-1, data=Intent { dat=content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/images/media/61/ORIGINAL/NONE/image/png/1980871995 flg=0x1 clip={text/uri-list {U(content)}} }} to activity {com.brandpost.brandpro365/com.mlkit.sample.activity.StillCutPhotoActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:5301)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5340)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:54)
at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference
at com.huawei.agconnect.config.a.c.a(Unknown Source:0)
at com.huawei.agconnect.config.a.g.(Unknown Source:41)
at com.huawei.agconnect.config.a.a.getString(Unknown Source:43)
at com.huawei.agconnect.config.a.a.getString(Unknown Source:1)
at com.huawei.hms.mlsdk.common.AgConnectInfo.(AgConnectInfo.java:53)
at com.huawei.hms.mlsdk.common.MLApplicationSetting.fromResource(MLApplicationSetting.java:262)
at com.huawei.hms.mlsdk.common.MLApplication.initialize(MLApplication.java:180)
at com.huawei.hms.mlsdk.common.MLApplication.getInstance(MLApplication.java:125)
at com.huawei.hms.mlsdk.MLAnalyzerFactory.getInstance(MLAnalyzerFactory.java:53)
at com.mlkit.sample.activity.StillCutPhotoActivity.createImageTransactor(StillCutPhotoActivity.java:149)
at com.mlkit.sample.activity.StillCutPhotoActivity.onActivityResult(StillCutPhotoActivity.java:101)
at android.app.Activity.dispatchActivityResult(Activity.java:8382)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5294)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5340)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:54)
at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Please follow the instuctions for HMS ML SDK : https://developer.huawei.com/consumer/en/doc/development/hiai-Guides/image-segmentation-0000001050040109
First, check the preparations:
Configure App info. in AGC: https://developer.huawei.com/consumer/en/doc/development/hiai-Guides/config-agc-0000001050990353
Enabling the service: https://developer.huawei.com/consumer/en/doc/development/hiai-Guides/enable-service-0000001050038078
Then, as for how to Create an image segmentation analyzer, please refer here: https://developer.huawei.com/consumer/en/doc/development/hiai-Guides/image-segmentation-0000001050040109
// Method 1: Use default parameter settings to configure the image segmentation analyzer.
// The default mode is human body segmentation in fine mode. All segmentation results of human body segmentation are returned (pixel-level label information, human body image with a transparent background, gray-scale image with a white human body and black background, and an original image for segmentation).
MLImageSegmentationAnalyzer analyzer = MLAnalyzerFactory.getInstance().getImageSegmentationAnalyzer();
// Method 2: Use MLImageSegmentationSetting to customize the image segmentation analyzer.
MLImageSegmentationSetting setting = new MLImageSegmentationSetting.Factory()
// Set whether to support fine segmentation. The value true indicates fine segmentation, and the value false indicates fast segmentation.
.setExact(false)
// Set the segmentation mode to human body segmentation.
.setAnalyzerType(MLImageSegmentationSetting.BODY_SEG)
// Set returned result types.
// MLImageSegmentationScene.ALL: All segmentation results are returned (pixel-level label information, human body image with a transparent background, gray-scale image with a white human body and black background, and an original image for segmentation).
// MLImageSegmentationScene.MASK_ONLY: Only pixel-level label information and an original image for segmentation are returned.
// MLImageSegmentationScene.FOREGROUND_ONLY: A human body image with a transparent background and an original image for segmentation are returned.
// MLImageSegmentationScene.GRAYSCALE_ONLY: A gray-scale image with a white human body and black background and an original image for segmentation are returned.
.setScene(MLImageSegmentationScene.FOREGROUND_ONLY)
.create();
MLImageSegmentationAnalyzer analyzer = MLAnalyzerFactory.getInstance().getImageSegmentationAnalyzer(setting);
i have made a recyclerview adapter where i am showing many things in recyclerview. and i am also showing some image in a view with viewpager. its working fine but when i am adding viewPagerArrowIndicator library for viewpager indicator its showing above error during i scroll back to up from bottom. i have tried solutions with stackoverflow but there are no similar error or solution
logcat:
Process: com.systechdigital.webadeal, PID: 30287
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:4659)
at android.view.ViewGroup.addView(ViewGroup.java:4495)
at android.view.ViewGroup.addView(ViewGroup.java:4436)
at android.view.ViewGroup.addView(ViewGroup.java:4409)
at com.sembozdemir.viewpagerarrowindicator.library.ViewPagerArrowIndicator.arrange(ViewPagerArrowIndicator.java:107)
at com.sembozdemir.viewpagerarrowindicator.library.ViewPagerArrowIndicator.bind(ViewPagerArrowIndicator.java:82)
at com.systechdigital.webadeal.NewsFeedAdapter.onBindViewHolder(NewsFeedAdapter.java:197)
at com.systechdigital.webadeal.NewsFeedAdapter.onBindViewHolder(NewsFeedAdapter.java:38)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6310)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6343)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5289)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5552)
at android.support.v7.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:270)
at android.support.v7.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:324)
at android.support.v7.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:337)
at android.support.v7.widget.GapWorker.prefetch(GapWorker.java:344)
at android.support.v7.widget.GapWorker.run(GapWorker.java:370)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
my adapter code:
//image slider
if(newsFeedClassArrayList.get(position).getImageList()!=null){
holder.viewPager.setVisibility(View.VISIBLE);
viewPagerAdapter=new ViewPagerAdapter(context,newsFeedClassArrayList.get(position).getImageList());
holder.viewPager.setAdapter(viewPagerAdapter);
**//error showing below on line**
holder.viewPagerArrowIndicator.bind(holder.viewPager);
holder.viewPagerArrowIndicator.setArrowIndicatorRes(R.drawable.arrow_left_black_24dp,R.drawable.arrow_right_black_24dp);
viewPagerAdapter.notifyDataSetChanged();
}else {
holder.viewPager.setVisibility(View.GONE);
}
holder.timeStampTvId.setText(newsFeedClass.getTimeStamp());
xml code:
<com.sembozdemir.viewpagerarrowindicator.library.ViewPagerArrowIndicator
android:id="#+id/viewPagerArrowIndicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:layout_width="wrap_content"
android:layout_height="180dp"
android:id="#+id/viewPagerId_imageView"
android:minHeight="0dp"
>
</android.support.v4.view.ViewPager>
</com.sembozdemir.viewpagerarrowindicator.library.ViewPagerArrowIndicator>
Try to use another library, even if you don't want to use that just use it for testing.
Maybe you can try this - https://github.com/ongakuer/CircleIndicator
Do you know good practices to avoid memory leaks ?
I am currently working on an app which has few memory leaks, that I struggle to fix, mainly because I don't know the habits that I need to take to be able to avoid them.
For instance, at the moment I get this issue
Fatal Exception: java.lang.OutOfMemoryError
Failed to allocate a 1627572 byte allocation with 1293760 free bytes and 1263KB until OOM
Raw Text
dalvik.system.VMRuntime.newNonMovableArray (VMRuntime.java)
android.view.LayoutInflater.inflate (LayoutInflater.java:429)
com.XX.Dialog.PopupDialog.onCreateView (PopupDialog.java:50)
Which comes from the inflater.inflate(R.layout.dialog_popup, container, false); in the onCreateView !
Here is the DialogFragment concerned :
public final class PopupDialog extends DialogFragment {
public PopupDialog()
{
}
#Override
public void onSaveInstanceState(Bundle outState) {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
View view = inflater.inflate(R.layout.dialog_popup, container, false);
return view;
}
The layout is quite long, but basically it got 5 ImageViews . Here is an sample :
<ImageView
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="#+id/popup_top_bg_iv"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="false"
android:layout_alignParentStart="false"
android:src="#drawable/popup_top_bg"
android:scaleType="fitXY"
android:background="#color/transparent" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/popup_top_bg_iv"
android:background="#ffffff"
android:layout_alignBottom="#+id/popup_bottom_ll" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/popup_top_iv"
android:src="#drawable/popup_0_top"
android:scaleType="fitCenter"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" />
....
So .... I was wondering if you know :
1. What could lead to this memory leak error from this dialogFragment ?
2. Any good practices in android to avoid memory leaks ?
For instance for that file, should I call
imageView.setImageDrawable(null);
On every Imageview when the popup is closed / Activity is closed (R.drawable.* ) ? Or just when I load an image from an URL (with Glide for instance) dynamically ?
Should I always resize an image to the dimension of my Imageview ?
What exactly do I need to clean after the Fragment/Activity is closed ?
What do you think ?
After a bit of digging I came with these solutions :
you can use Leak canary to track your memory leak (https://github.com/square/leakcanary)
Or the Memory monitor of Android studio : https://developer.android.com/studio/profile/am-memory.html
Use a library to load your images such as Picasso or Glide. Personally I prefer Glide.
https://medium.com/#multidots/glide-vs-picasso-930eed42b81d
Never keep references of Activity of context in static. NEVER!
Otherwise your references might still be there even if you need it.
Avoid keeping references of ImageViews. Recycle / Clear the bitmap inside when your destroy the view.
If you need to have a reference of the context, please use context.getApplicationContext();
Don't use context.getApplicationContext(); for LayoutInflater.from(context); but directly the context.
(in case if you need to inflate a view or need a context for something).
If you use the context.getApplicationContext() it can lead to some design issues if you create views dynamically.
If you get some OutOfMemory error, think to compress your images ! It actually saves me lot of OutOfMemory error. You can use https://tinypng.com/.
Don't put by default your images into the folder drawable-xhdpi but drawable-mdpi instead as drawable-mdpi is the default one.
So for my issue I just need to compress the images and put them back in the drawable-mdpi folder ! All good now !
I am using fersco library for loading local image. Initially i am displaying placeholder image in each item.Once the image is downloaded then i am storing that image in to local path and then load image via setImageUri function. If i am scrolling fast at the time of downloading image it display different image and re-appearing some time keep on changing if i am stop scrolling.
My SimpleDraweeView :
<com.facebook.drawee.view.SimpleDraweeView
android:id="#+id/fake_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center|center_horizontal|center_vertical"
android:adjustViewBounds="true"
android:contentDescription="#string/app_name"
android:scaleType="centerInside" />
My Adapter Code is :
GenericDraweeHierarchy hierarchy = setHierarchyForDraweeView(mImageView, 300);
hierarchy.setFailureImage(mContext.getResources().getDrawable(R.drawable.broken_image_black));
mSimpleDraweeView.setImageURI(Uri.fromFile(new File(mPath/local path/)));
SetHierarchyForDraweeView Function :
private GenericDraweeHierarchy setHierarchyForDraweeView(SimpleDraweeView draweeView, int duration) {
if (draweeView != null) {
if (draweeView.getHierarchy() == null) {
GenericDraweeHierarchyBuilder builder = new GenericDraweeHierarchyBuilder(mContext.getResources());
GenericDraweeHierarchy hierarchy = builder
.setFadeDuration(duration)
.setPlaceholderImage(new AsyncColorDrawable(mContext.getResources()))
.setFailureImage(mContext.getResources().getDrawable(R.drawable.broken_image_black))
.build();
draweeView.setHierarchy(hierarchy);
} else {
GenericDraweeHierarchy hierarchy = draweeView.getHierarchy();
hierarchy.setFadeDuration(duration);
return hierarchy;
}
}
return null;
}
AsyncColorDrawable Class :
private class AsyncColorDrawable extends ColorDrawable {
public AsyncColorDrawable(Resources res) {
super(res.getColor(R.color.RED));
}
}
I am doing anything wrong ?
I see several things that should be fixed, but none of which would explain incorrect loading. I will be able to help, but I'll need the logcat logs as explained here. Also, there is one thing I don't fully understand. From your description it seems that you are downloading your images manually, saving them to disk and when they are downloaded you set the Uri. Why not using Fresco to automatically download and disk-cache images for you? Can you provide this piece of code as well, because the issue might very well be there.
Things that should be fixed:
adjustViewBounds and scaleType attributtes are not supported by SimpleDraweeView. Drawee operates on several images at once (placeholder, failure image, actual image, etc.) Each can have its own scale type so you need to use Drawee atrributes as explained here.
If you are inflating your view from XML, draweeView.getHierarchy should never be null. You would have a NullPointerException anyway because you are not returning hierarchy from that if-branch. So, you can specify your failure image via XML too, no need to do that programmatically. Same for the fade duration if you always use the same value.
I'm developing a VR video viewer using Android Cardboard SDK and RajawaliVR (https://github.com/Rajawali/RajawaliVR)
On some devices I have this crash when returning from sleep (others just show black screen):
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.opengl.GLSurfaceView$GLThread.surfaceCreated()' on a null object reference
at android.opengl.GLSurfaceView.surfaceCreated(GLSurfaceView.java:523)
at android.view.SurfaceView.updateWindow(SurfaceView.java:580)
at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:176)
at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:944)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1970)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5891)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
As you can see the crash is in the android code, how do I start debugging it?
You have access to the source code, so start with that.
Assuming you're using Lollipop, it's failing on this line:
mGLThread.surfaceCreated();
The error message indicates that mGLThread is null. Doing a simple search for the assignment ("mGLThread =") with the web browser reveals two instances, the most interesting of which is this one:
public void setRenderer(Renderer renderer) {
...
mGLThread = new GLThread(mThisWeakRef);
Setting some of the complexities aside, mGLThread should be non-null so long as setRenderer() is called. So the first thing to do is check to see if your application is calling setRenderer() (typically in onCreate()).
If you're following along the Android Developer OpenGL tutorial, it's possible that Android Studio corrected this definition in your Activity class constructor:
mGLView = new MyGLSurfaceView(this);
and changed it to
mGLView = new GLSurfaceView(this);
because the class MyGLSurfaceView had not been coded yet...skipping the MyGLSurfaveView constructor which is where setRenderer(...) is called. Mr. fadden's answer above is excellent, explains how to diagnose the problem.