返回活动后的java.lang.OutOfMemoryError

时间:2019-05-28 20:20:12

标签: java android android-viewpager

我正在尝试使用Android Studio中的viewPager进行幻灯片放映。我使用BitmapFactory.Options来调整图像的大小(如果图像太大),并且在清单中使用以下代码android:largeHeap="true" android:allowBackup="true"

如果我不使用BitmapFactory.Options调整图像大小,我想指定以上代码在我的情况下不起作用。我收到错误java.lang.OutOfMemoryError。

这是适配器的代码

public class SlideShowAdapter extends PagerAdapter {

private Context context;
private LayoutInflater inflater;
private final int HEIGHT_IMGAE = 230;

private int [] images = {
        R.drawable.img1,
        R.drawable.img2,
        R.drawable.img3
};

public SlideShowAdapter(Context context) {
    this.context = context;
}

@Override
public int getCount() {
    return images.length;
}

@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
    return (view == object);
}

@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View view = inflater.inflate(R.layout.slide_show_layout, container, false);

    ImageView img = view.findViewById(R.id.sile_show_layout_imageView);

    DisplayMetrics displayMetrics = new DisplayMetrics();
    ((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    int width = displayMetrics.widthPixels;

    img.setImageBitmap(
            decodeSampledBitmapFromResource(context.getResources(), images[position], width, HEIGHT_IMGAE));

    container.addView(view);
    return view;
}

@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
    container.removeView((LinearLayout)object);
}


private static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) >= reqHeight
                && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}



private static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                     int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

}

一切在main上都正常

public class MainActivity extends AppCompatActivity {

private ViewPager slideShow;
private SlideShowAdapter adapter ;

private int currentPage = 0;
Timer timer;
final long DELAY_MS = 3000; //delay in milliseconds before task is to be executed
final long PERIOD_MS = 5000; // time in milliseconds between successive task executions.



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    slideShow = findViewById(R.id.main_activity_viewPager_slideshow);
    adapter = new SlideShowAdapter(this);
    slideShow.setAdapter(adapter);
    this.doSlideShow();

}
public void doSlideShow(){
    final Handler handler = new Handler();
    final Runnable Update = new Runnable() {
        public void run() {
            if (currentPage == adapter.getCount()) {
                currentPage = 0;
            }
            slideShow.setCurrentItem(currentPage++, true);
        }
    };

    timer = new Timer(); // This will create a new Thread
    timer.schedule(new TimerTask() { // task to be scheduled
        @Override
        public void run() {
            handler.post(Update);
        }
    }, DELAY_MS, PERIOD_MS);
}

public void luchAdminActivity(View view) {
    startActivity(new Intent(this,SingupActivity.class));
}

public void luchMainActivity(View view) {
    startActivity(new Intent(this,MainActivity.class));
}
public void luchMenuActivity(View view) {
    startActivity(new Intent(this,MainActivity.class));
}

}

但是当我转到另一个活动并尝试返回到主活动(有幻灯片放映的地方)时,出现以下错误

Process: bogdan.yourwaiter, PID: 25647
java.lang.OutOfMemoryError: Failed to allocate a 156487692 byte allocation with 16768376 free bytes and 114MB until OOM
    at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
    at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
    at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:700)
    at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:535)
    at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:558)
    at bogdan.yourwaiter.adapter.SlideShowAdapter.decodeSampledBitmapFromResource(SlideShowAdapter.java:111)
    at bogdan.yourwaiter.adapter.SlideShowAdapter.instantiateItem(SlideShowAdapter.java:61)
    at androidx.viewpager.widget.ViewPager.addNewItem(ViewPager.java:1010)
    at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1224)
    at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1092)
    at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1622)
    at android.view.View.measure(View.java:21121)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6462)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
    at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1117)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:642)
    at android.view.View.measure(View.java:21121)
    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
    at android.view.View.measure(View.java:21121)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6462)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
    at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
    at android.view.View.measure(View.java:21121)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6462)
    at androidx.appcompat.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:401)
    at android.view.View.measure(View.java:21121)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6462)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
    at android.view.View.measure(View.java:21121)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6462)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
    at android.view.View.measure(View.java:21121)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6462)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
    at com.android.internal.policy.DecorView.onMeasure(DecorView.java:872)
    at android.view.View.measure(View.java:21121)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2625)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1677)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1928)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1550)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7190)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:959)
    at android.view.Choreographer.doCallbacks(Choreographer.java:734)
    at android.view.Choreographer.doFrame(Choreographer.java:670)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:945)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6776)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)

0 个答案:

没有答案