java.lang.RuntimeException: Unable to start activity - android

I have just launched my First Android Application on the Play Store name Indian Logo Quiz
And I am receiving certain crash reports. Of which one is This :
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.indian.logoquiz/com.indian.logoquiz.Play}:
android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2247)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2297)
at android.app.ActivityThread.access$700(ActivityThread.java:152)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1282)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5328)
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:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:619)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java: 56)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:666)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:691)
at android.view.LayoutInflater.inflate(LayoutInflater.java:467)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:327)
at android.app.Activity.setContentView(Activity.java:1928)
at com.indian.logoquiz.Play.onCreate(Play.java:39)
at android.app.Activity.performCreate(Activity.java:5250)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
... 11 more
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at android.view.LayoutInflater.createView(LayoutInflater.java:593)
... 23 more
Caused by: java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:596)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:817)
at android.content.res.Resources.loadDrawable(Resources.java:2854)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.view.View.<init>(View.java:3460)
at android.view.ViewGroup.<init>(ViewGroup.java:446)
at android.widget.LinearLayout.<init>(LinearLayout.java:176)
at android.widget.LinearLayout.<init>(LinearLayout.java:172)
... 26 more
My play.xml is as follows :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/playpage">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.33"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp">
<Button
android:id="#+id/lvl1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.33"
android:alpha="0.85"
android:text=""
/>
<Button
android:id="#+id/lvl2"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.33"
android:alpha="0.85"
android:text=""
/>
<Button
android:id="#+id/lvl3"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.34"
android:alpha="0.85"
android:text="" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.33"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp" >
<Button
android:id="#+id/lvl4"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.33"
android:alpha="0.85"
android:text="" />
<Button
android:id="#+id/lvl5"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.33"
android:alpha="0.85"
android:text="" />
<Button
android:id="#+id/lvl6"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.34"
android:alpha="0.85"
android:text="" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.33"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp">
<Button
android:id="#+id/lvl7"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.33"
android:alpha="0.85"
android:text="" />
<Button
android:id="#+id/lvl8"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.33"
android:alpha="0.85"
android:text="" />
<Button
android:id="#+id/lvl9"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.34"
android:alpha="0.85"
android:text="" />
</LinearLayout>
</LinearLayout>
The app is getting crashed on pressing level 1 button ....
Can it be because of nested weight in any case ??
Please help !....

You are getting Out of Memory Exception for Images in your Activity.
When any device with small heap or buffer size uses application it may get Memory exception because you may have used High resolution images.
try below code to reduce memory usage of application bitmaps.
private Bitmap decodeFile(File f){
Bitmap b = null;
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int)Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE /
(double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
return b;
}
Hope it Helps!!

Other answers have talked about Out of Memory Exception, but since you've talked about nested weight's here is something which might help in understanding that better. It might not solve your problem but clear few things.
In general there are two parameters which are used together many a times:
android:weightSum="1" and android:layout_weight. If you don't specify the weightSum in the outer layout, its considered to be 1. The sum of all android:layout_weight inside an outerlayout should be equal to the weight sum of that outer layout. Eg:
If you have 3 Buttons inside a LinearLayout and you want to define equal weights to them, then you can do it as follows.
<LinearLayout
...
android:weightSum="3"
>
<Button
...
android:layout_weight="1"
/>
<Button
...
android:layout_weight="1"
/>
<Button
...
android:layout_weight="1"
/>
</LinearLayout>
Similarly you can do for layouts:
<LinearLayout
android:weightSum="3"
>
<LinearLayout
...
android:layout_weight="1"
/>
<LinearLayout
...
android:layout_weight="1"
/>
<LinearLayout
...
android:layout_weight="1"
/>
</LinearLayout>

you forgot to put end tag for parent Layout in last. </LinearLayout>

It is good practice to remove Bitmaps from memory as soon as you do not need them.
A way you can do it by recycling the Bitmap:
Bitmap newImage = Bitmap.createBitmap(wid, hgt, Bitmap.Config.ARGB_8888);
// Use here your newImage...
newImage.recycle();
newImage = null;

Related

android.content.res.Resources$NotFoundException, android.view.InflateException with ImageButton

I receive the error below, mostly on Android 4.1 and 4.4:
java.lang.RuntimeException: Unable to create service se.weblink.weblinkunified.services.FloatingWindowService: android.view.InflateException: Binary XML file line #68: Error inflating class <unknown>
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2406)
at android.app.ActivityThread.access$1700(ActivityThread.java:134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1306)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4867)
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:1007)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #68: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:619)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:666)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:691)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:752)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.inflate(LayoutInflater.java:495)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at se.weblink.weblinkunified.services.FloatingWindowService.addViewToWindow(FloatingWindowService.java:122)
at se.weblink.weblinkunified.services.FloatingWindowService.onCreate(FloatingWindowService.java:92)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2396)
... 10 more
The addViewToWindow function:
final LayoutInflater layoutInflater = LayoutInflater.from(this);
popupWindow = layoutInflater.inflate(R.layout.window_floating_call, null);
final WindowManager.LayoutParams params = setupLayoutParams();
final View.OnClickListener clickListener = getViewClickListener();
final View.OnTouchListener touchListener = getTouchListener(params);
popupWindow.setOnClickListener(clickListener);
popupWindow.setOnTouchListener(touchListener);
final View overlayView = popupWindow.findViewById(R.id.overlay_view);
overlayView.setOnClickListener(clickListener);
overlayView.setOnTouchListener(touchListener);
final View topContainer = popupWindow.findViewById(R.id.call_top_container);
buttonContainer = (LinearLayout) popupWindow.findViewById(R.id.call_bottom_container);
buttonContainer.addView(getActiveCallButtons());
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
final Resources resources = getResources();
topContainer.setBackgroundColor(sharedPreferences.getInt(Constants.THEME_COLOR_PRIMARY, resources.getColor(R.color.accent_color_default)));
setupCloseButton();
windowManager.addView(popupWindow, params);
popupWindow.setTranslationY(Tools.getDensityIndependentSize(-120, resources));
popupWindow.setVisibility(View.GONE);
And the xml file "window_floating_call":
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<RelativeLayout
android:id="#+id/call_top_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:background="#color/accent_color_default"
>
<ImageView
android:id="#+id/contact_image"
android:layout_width="54dp"
android:layout_height="54dp"
android:layout_marginRight="10dp"
android:src="#drawable/ic_contact_picture"
/>
<TextView
android:id="#+id/contact_initial_label"
android:layout_width="55dp"
android:layout_height="55dp"
android:gravity="center"
android:layout_marginRight="10dp"
android:textSize="25dp"
android:fontFamily="sans-serif-light"/>
<TextView
android:id="#+id/incoming_call_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/contact_image"
android:textColor="#color/text_color_bright"
android:text="#string/incoming_call"
android:textSize="10sp"
android:fontFamily="sans-serif"/>
<TextView
android:id="#+id/contact_name_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/incoming_call_label"
android:layout_marginTop="4dp"
android:layout_toRightOf="#+id/contact_image"
android:textColor="#color/text_color_bright"
android:textSize="18sp"
android:fontFamily="sans-serif"/>
<TextView
android:id="#+id/contact_number_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/contact_image"
android:gravity="top"
android:layout_below="#+id/contact_name_label"
android:fontFamily="sans-serif-light"
android:textSize="14sp"
android:textColor="#color/text_color_bright"/>
<View
android:id="#+id/overlay_view"
android:layout_width="match_parent"
android:layout_height="54dp"/>
<ImageButton
android:id="#+id/close_button"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_alignParentRight="true"
android:src="#drawable/ic_action_cancel"
android:alpha="0.7"
style="#style/Base.Widget.AppCompat.ActionButton"/>
</RelativeLayout>
<LinearLayout
android:id="#+id/call_bottom_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/call_top_container"
android:orientation="vertical"
android:weightSum="1"
>
</LinearLayout>
I can't figure out what causes the error. The problem does not occur on Android 5.1. And I don't seem to get why this code wouldn't be able to run on Android 4.1, 4.2, 4.4.
I appreciate if someone could help me. Thanks in advance!
Forgot to include the android.content.res.Resources$NotFoundException error. But the exception says that the resource file is not a drawable. I have the image ic_action_cancel in all other drawable folders (drawable-hdpi, drawable-mdpi etc.) except the main drawable folder(drawable). I tried adding the .png file to the main folder but it did not work.
I've faced the same problem as yours.I firstly used my inflateUtils that write by myself.
The code is:
public static View inflate(int id) {
return View.inflate(getContext(), id, null);
}
And the getContext() method return a applicationContext. And it occurred InflateExcepition.
And now I change to use View.inflate(context, resId, null), and the context is my activity. And it worked fun now! hope that can help you.
sorry for my poor English!

ColorDrawable cannot be cast to android.support.v7.widget.RoundRectDrawableWithShadow

The issue I am having is basically what is found in this answer but I will still explain below. I am testing on a device with android 5.0.1 and another with 4.2.2. On my device with 5.0.1 I get no errors and everything behaves as expected. On my 4.2.2 device I get the following error:
java.lang.ClassCastException: android.graphics.drawable.ColorDrawable cannot be cast to android.support.v7.widget.RoundRectDrawableWithShadow
at android.support.v7.widget.CardViewEclairMr1.getShadowBackground(CardViewEclairMr1.java:159)
at android.support.v7.widget.CardViewEclairMr1.getMinWidth(CardViewEclairMr1.java:150)
at android.support.v7.widget.CardView.onMeasure(CardView.java:181)
at android.view.View.measure(View.java:15696)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:681)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:15696)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4851)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15696)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4851)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:15696)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4851)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2261)
at android.view.View.measure(View.java:15696)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2225)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1290)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1527)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1190)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4860)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:766)
at android.view.Choreographer.doCallbacks(Choreographer.java:575)
at android.view.Choreographer.doFrame(Choreographer.java:542)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:751)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5751)
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:1083)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
at dalvik.system.NativeStart.main(Native Method)
with the error occurring at this line: card1.setBackgroundColor(getResources().getColor(R.color.White));
Now as suggested by the linked answer I have tried using setCardBackgroundColor however this causes the error to be produced on both my devices. Any suggestions?
The CardView I am attempting to use is a android.support.v7.widget.CardView
This is the layout producing the error:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/MainLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#bbbbb5"
android:orientation="vertical"
android:weightSum="100">
<ImageView
android:id="#+id/imageView"
android:layout_width="fill_parent"
android:layout_height="400dp"
android:layout_gravity="center_vertical|top"
android:layout_marginBottom="50dp"
android:layout_marginTop="-65dp"
android:layout_toRightOf="#+id/prem_BACK"
android:layout_weight="0"
android:clickable="true"
android:paddingBottom="0dp"
android:src="#drawable/plane1" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView"
android:layout_alignEnd="#+id/imageView"
android:layout_alignRight="#+id/imageView"
android:layout_marginBottom="40dp"
android:layout_marginRight="5dp"
android:src="#drawable/ic_navigate_next_white_48dp" />
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view1"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="280dp"
android:clickable="true"
android:onClick="card1ClickMethod"
card_view:cardCornerRadius="4dp">
<TextView
android:id="#+id/choice_text1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:onClick="card1ClickMethod"
android:text="Loret ipsum sample"
android:textColor="#212121" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view2"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="340dp"
android:clickable="true"
android:onClick="card2ClickMethod"
card_view:cardCornerRadius="4dp">
<TextView
android:id="#+id/choice_text2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:gravity="center"
android:onClick="card2ClickMethod"
android:textColor="#212121" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view3"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="400dp"
android:clickable="true"
android:onClick="card3ClickMethod"
card_view:cardCornerRadius="4dp">
<TextView
android:id="#+id/choice_text3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:gravity="center"
android:onClick="card3ClickMethod"
android:textColor="#212121" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view4"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="460dp"
android:clickable="true"
android:onClick="card4ClickMethod"
card_view:cardCornerRadius="4dp">
<TextView
android:id="#+id/choice_text4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:gravity="center"
android:onClick="card4ClickMethod"
android:textColor="#212121" />
</android.support.v7.widget.CardView>
<TextView
android:id="#+id/resulttext3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/progressBar1"
android:layout_alignParentStart="true"
android:layout_gravity="center_vertical|left"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:textSize="15dp" />
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/fab"
android:layout_gravity="right|center_vertical"
android:layout_marginTop="20dp" />
<ImageView
android:id="#+id/prem_BACK"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="0dp"
android:layout_marginTop="0dp"
android:src="#drawable/background4"
android:visibility="gone" />
After reading through the issue described here I noticed that it has since been closed. As far as I am aware I am using the most updated version of the platform tools and sdk tools and I still have this issue.
After some further testing, I have discovered that the emulator I am using does not have GooglePlayServices. I do not currently have access to a physical device with less than Android 6.0 to test on. Is it a possibility that not having GooglePlayServices could cause this issue?
This is working for me for cardview inside recycleview
((CardView)viewholder.itemView).setCardBackgroundColor(Color.WHITE);
You could also keep both versions of android happy by giving them what they want rather than trying to force and cast something:
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
// below lillipop
view.setCardBackgroundColor(Color.WHITE);
// working for lower questions as per another answer posted here
} else {
// lollipop and above
card1.setBackgroundColor(getResources().getColor(R.color.White));
// known to be working for lillipop as per your question
}
Basically call different and working methods for each of the android versions.
To correctly identify android versions above and below lollipop use LILLIPOP_MR1 (Soruce)
You can use:
card1.setBackgroundColor(Color.rgb(255, 255, 255));
instead of:
card1.setBackgroundColor(getResources().getColor(R.color.White));
The easiest way to do what you want is using color filter, I guess. I tried this on 4.2.2 and it works fine.
cardView.getBackground().setColorFilter(Color.BLUE, PorterDuff.Mode.MULTIPLY);
By using setBackgroundColor(int color) you are actually calling a method on View, switching the background. The CardView expects a RoundRectDrawableWithShadow, which you did just overwrite. Hence the exception.
CardView view = (CardView) findViewById(R.id.card);
view.setCardBackgroundColor(Color.RED);
Be sure to call cardView.setCardBackgroundColor(int) and it works. It works on 4.2.2, and by looking through the cardView source code I'm confident about other apis as well. If this also leads to a crash, it must be a different reason.
Probably this resolved by using PublicRoundRectDrawableWithShadow.
Create PublicRoundRectDrawableWithShadow.
package android.support.v7.widget;
import android.content.res.Resources;
public class PublicRoundRectDrawableWithShadow extends RoundRectDrawableWithShadow {
public PublicRoundRectDrawableWithShadow(Resources resources, CardView cardView, int backgroundColor) {
super(resources, backgroundColor, cardView.getRadius(), cardView.getCardElevation(), cardView.getMaxCardElevation());
}
}
And setBackground() like this.
final CardView cardView = (CardView) findViewById(R.id.card_view);
if (Build.VERSION_CODES.LOLLIPOP <= Build.VERSION.SDK_INT) {
cardView.setBackgroundColor(Color.RED);
} else {
cardView.setBackgroundDrawable(new PublicRoundRectDrawableWithShadow(getResources(), cardView, Color.RED));
}
Please try below specific line to set background color of card view object:
cardView.setCardBackgroundColor(Color.WHITE);

Same code works on phisical device but not in the Android 4 emulator

My app is already using the Google Maps Android API v2 and it is working on my Galaxy Mini (Android 2.3.6). When I try to test in on an emulator using Platform 4.0.3, API level 15 and Google APIs, a get the following error:
01-23 14:26:31.581: ERROR/AndroidRuntime(688): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.remotepark/br.com.remotepark.activities.MainActivity}: android.view.InflateException: Binary XML file line #11: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:697)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:251)
at com.actionbarsherlock.internal.ActionBarSherlockNative.setContentView(ActionBarSherlockNative.java:119)
at com.actionbarsherlock.app.SherlockFragmentActivity.setContentView(SherlockFragmentActivity.java:262)
at br.com.remotepark.activities.MainActivity.onCreate(MainActivity.java:51)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
... 11 more
Caused by: java.lang.NullPointerException
at br.com.remotepark.fragments.MapFragment.initLocation(MapFragment.java:86)
at br.com.remotepark.fragments.MapFragment.onCreateView(MapFragment.java:62)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:845)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1058)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1156)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:270)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:669)
... 22 more
The line that throws the exception is this:
mMap.setInfoWindowAdapter(new MapInfoWindowAdapter(getLayoutInflater(savedInstanceState)));
The MapInfoWindowAdapter constructor is like this:
MapInfoWindowAdapter(LayoutInflater layoutInflater) {
mLayoutInflater = layoutInflater;
mWindow = mLayoutInflater.inflate(R.layout.map_info_window, null);
mContents = mLayoutInflater.inflate(R.layout.map_info_window, null);
}
And the map_info_window.xml is:
<ImageView
android:layout_width="40dip"
android:layout_height="40dip"
android:src="#drawable/ic_remote_park"
android:id="#+id/remotepark_logo"
android:layout_marginLeft="0dip"
android:layout_marginRight="8dip"
android:layout_marginTop="16dip"></ImageView>
<LinearLayout
android:id="#+id/balloon_inner_layout"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1"
android:paddingTop="5dip">
<LinearLayout
android:id="#+id/layout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="0dip">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textColor="#FFF"
android:id="#+id/parking_name_info_window"
android:textSize="7pt"
android:singleLine="true"
android:textStyle="bold"
android:ellipsize="end"/>
</LinearLayout>
<RelativeLayout
android:id="#+id/RelativeLayout2"
android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginTop="2dip">
<RelativeLayout
android:id="#+id/frameLayout1"
android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textColor="#FFF"
android:id="#+id/availability_label_info_window"
android:text="#string/places_str"
android:textStyle="bold"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textColor="#FFF"
android:id="#+id/availability_info_window"
android:layout_toRightOf="#+id/availability_label_info_window"
android:layout_marginLeft="5dip" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/RelativeLayout3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentRight="true">
<TextView
android:id="#+id/price_label_info_window"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:textStyle="bold"/>
<TextView
android:id="#+id/price_symbol_info_window"
android:layout_toRightOf="#+id/price_label_info_window"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/price_symbol_str"
android:textColor="#FFF"
android:layout_marginLeft="5dip"/>
<TextView
android:id="#+id/price_info_window"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:layout_toRightOf="#+id/price_symbol_info_window"
android:layout_marginLeft="2dip"/>
</RelativeLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/RelativeLayout4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="right"
android:layout_marginBottom="5dip">
</RelativeLayout>
</LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/btn_more_info_disabled"
android:id="#+id/more_info_button"
android:layout_marginLeft="10dip"
android:layout_marginRight="8dip"
android:layout_marginTop="16dip"></ImageView></LinearLayout>
Do you have any idea why its not working?
According to Google, Google Play services API's require 'physical development device', so they are not officially supported on the emulators. So, if you are running on an emulator, it is almost certain you are missing the required services. People report getting it to work in emulators, but I have not tried myself. You can view than answers in this post, if you want to look at installing Google Play on an emulator.
You are getting an error when you try to inflate the MapFragment or SupportMapFragment from your xml. It is usually a good idea to check if the device has Google Play services by calling isGooglePlayServicesAvailable(), and make sure it returns ConnectionResult.SUCCESS before proceeding. This allows you to present an error dialog instead of just crashing. Google has even provided an error dialog for some othercodes, you can have them prompted to upgrade/install via getErrorDialog(), like --
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
switch (resultCode) {
case ConnectionResult.SUCCESS: // proceed
break;
case ConnectionResult.SERVICE_MISSING:
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
case ConnectionResult.SERVICE_DISABLED:
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode, this, 1);
dialog.show();
}
Do this before calling setContentView.

Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget

In my application when I try to launch it Force Closed and the error pointing the line "setContentView(R.layout.Menu);" of the layout. And in the XML file it show the "OutOfMemoryError" image view in my layout. I am realy confused. Please guide me for further move.
Edited:
My application uses database, and at the very first time it parse some XML data and insert into the Sqlite database. My Outofmemory problem occurs only at the first time. Second time it works fine. I tried System.gc(). Is there any prob on that.
This is my Log:
E/dalvikvm-heap(2712): 105376-byte external allocation too large for this process.
VM won't let us allocate 105376 bytes
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Test/com.Test.Menu}: android.view.InflateException: Binary XML file line #13: Error inflating class <unknown>
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
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:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #13: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:518)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:568)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207)
at android.app.Activity.setContentView(Activity.java:1657)
at com.Test.Menu.onCreate(Menu.java:32)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
... 11 more
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
at android.view.LayoutInflater.createView(LayoutInflater.java:505)
... 23 more
Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:460)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:336)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:697)
at android.content.res.Resources.loadDrawable(Resources.java:1709)
at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
at android.widget.ImageView.<init>(ImageView.java:118)
at android.widget.ImageView.<init>(ImageView.java:108)
This is my XML code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/RL_Title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="8"
android:onClick="onTitleClick" >
<ImageView
android:id="#+id/Img_Title_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="center"
android:src="#drawable/title_bg" />
<Button
android:id="#+id/Btn_Title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:background="#drawable/title_al"
android:drawableRight="#drawable/pro"
android:gravity="center"
android:onClick="onTitleClick" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/RL_MainMenu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" android:onClick="onDoNothing">
<ImageView
android:id="#+id/ImageView01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="4"
android:src="#drawable/main_bg" android:scaleType="centerCrop"/>
<ImageView
android:id="#+id/Img_logo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="4"
android:scaleType="center"
android:src="#drawable/logo_al" />
<LinearLayout
android:id="#+id/LI_Menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/RL_ExtraOption"
android:layout_alignTop="#+id/Img_logo"
android:layout_margin="2dp"
android:orientation="vertical" >
<ImageButton
android:id="#+id/Img_Buyer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#drawable/bt_blink"
android:onClick="Nextclick"
android:scaleType="fitCenter"
android:soundEffectsEnabled="true"
android:src="#drawable/buyer_icon" />
<ImageButton
android:id="#+id/Img_Seller"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#drawable/bt_blink"
android:onClick="Nextclick"
android:scaleType="fitCenter"
android:src="#drawable/seller_icon" />
<ImageButton
android:id="#+id/Img_Lender"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#drawable/bt_blink"
android:onClick="Nextclick"
android:scaleType="fitCenter"
android:src="#drawable/lender_icon" />
<ImageButton
android:id="#+id/Img_myTitleRep"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#drawable/bt_blink"
android:onClick="Nextclick"
android:scaleType="fitCenter"
android:src="#drawable/my_title_rep_icon_al" />
<ImageButton
android:id="#+id/Img_Setup"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#drawable/bt_blink"
android:onClick="Nextclick"
android:scaleType="fitCenter"
android:src="#drawable/setup_icon" />
</LinearLayout>
<RelativeLayout
android:id="#+id/RL_ExtraOption"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#drawable/main_bottom_bg" >
<TextView
android:id="#+id/txt_RepName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:textColor="#color/white"
android:textSize="#dimen/font_size" />
<TableRow
android:id="#+id/TR_ContactRep"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:gravity="center" >
<Button
android:id="#+id/Btn_ContactRep"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="3dp"
android:background="#drawable/contact_rep_blink"
android:onClick="ContactRep_Click" />
<Button
android:id="#+id/Btn_MoreOption"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#drawable/main_more_blink"
android:onClick="onMoreClick" />
</TableRow>
</RelativeLayout>
<LinearLayout
android:id="#+id/ln_Mainmore"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/dialog_bg" android:layout_alignParentBottom="true" android:visibility="gone">
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="3"
android:orientation="vertical" >
</LinearLayout>
<TableLayout
android:id="#+id/TableLayout01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center" >
<TableRow
android:id="#+id/TableRow04"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:layout_marginTop="20dp"
android:gravity="center" >
<Button
android:id="#+id/Btn_Rate"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#drawable/property_blue_blink"
android:onClick="onRate"
android:singleLine="true"
android:text="Rate/Testimonial"
android:textColor="#color/white"
android:textSize="#dimen/font_size"
android:textStyle="bold" />
</TableRow>
<TableRow
android:id="#+id/TableRow01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:gravity="center" >
<Button
android:id="#+id/btn_SubFeature"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#drawable/property_blue_blink"
android:onClick="onSubFeature"
android:singleLine="true"
android:text="Submit A Feature"
android:textColor="#color/white"
android:textSize="#dimen/font_size"
android:textStyle="bold" />
</TableRow>
<TableRow
android:id="#+id/TableRow03"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:gravity="center" >
<Button
android:id="#+id/Btn_ReferFrnd"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#drawable/property_blue_blink"
android:onClick="onReferAFrnd"
android:text="Refer A Friend"
android:textColor="#color/white"
android:textSize="#dimen/font_size"
android:textStyle="bold" />
</TableRow>
<TableRow
android:id="#+id/TableRow02"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:gravity="center" >
<Button
android:id="#+id/Btn_cancel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#drawable/property_cancel_blink"
android:onClick="onClose"
android:text="Cancel"
android:textColor="#color/black"
android:textSize="#dimen/font_size"
android:textStyle="bold" />
</TableRow>
</TableLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="3"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
</RelativeLayout>
I guess the problem is not in your layout; the problem is somewhere else in your code. And you are probably leaking context somewhere.
Other probable reason is that you must be creating bulky multiple objects while parsing your XML (as you mentioned this occurs the first time when you parse XML). Though Java has auto garbage collection approach, but still you can not completely rely on it. It is a good practice to nullify your collection instance or clear your objects content when you don't need them any more.
But still I have prepared a list of important points which you should remember while dealing with bitmaps on Android.
1) You can call recycle on each bitmap and set them to null. (bitmap.recycle() will release all the memory used by this bitmap, but it does not nullify the bitmap object).
2) You can also unbind the drawables associated with layouts when an activity is destroyed. Try the code given below and also have a look at this link link.
private void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
// Call this method from onDestroy()
void onDestroy() {
super.onDestroy();
unbindDrawables(findViewById(R.id.RootView));
System.gc();
}
3) You can convert your hashmaps to WeakHashmaps, so that its memory would get released when the system runs low on memory.
4) You can scale/resize all your bitmaps. To scale bitmaps you can try something like this:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap preview_bitmap=BitmapFactory.decodeStream(is, null, options);
This inSampleSize option reduces memory consumption.
Here's a complete method. First it reads the image size without decoding the content itself. Then it finds the best inSampleSize value; it should be a power of 2. And finally the image is decoded.
// Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
// The new size we want to scale to
final int REQUIRED_SIZE=70;
// Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2 >= REQUIRED_SIZE && o.outHeight/scale/2 >= REQUIRED_SIZE)
scale*=2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
}
catch (FileNotFoundException e) {
}
return null;
}
Have a look at this link..
5) You can override onLowMemory() method in an activity which gets a call when entire system runs low on memory. You can release a few resources there.
6) You can make your objects SoftReference or Weakreference, so that they get released in a low-memory condition.
A very common memory leak that I observed is due to the implementation of inner classes and implementing Handler in Activity. This links talks about the same in more detail.
I hope this helps to eliminate your problem.
This is a typical problem when using Android's ImageView with large images on older devices (even if the file size is only several Kbs). The native graphics library called skia that is used to decode the image allocates native memory based on the image's dimensions, so the file size does not influence this directly.
Even if you omit the src-attribute in the XML layout definition to load the image yourself in your onCreate() method the same error will be triggered. The only way to get around this is to use an inSampleSize in BitmapFactory.decodeStream to perform downsampling directly during decoding (see Strange out of memory issue while loading an image to a Bitmap object for example). This itself raises the question of how to determine this scale factor.
The best solution I found when handling large images is replacing the ImageView with a WebView and load some minimal HTML like this:
webView.loadUrl("file:///android_res/raw/background.html");
where the content of raw/background.html might be something like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<style type="text/css">
body {
margin: 0;
}
img {
width: 100%;
height: auto;
display: block;
}
</style>
</head>
<body>
<img src="file:///android_res/drawable/background.png" />
</body>
The WebKit engine that is used in the WebView performs image loading in a much more efficient way, so that those memory allocation errors should be gone.
You can even use different images for portrait and landscape by putting them in drawable-port and drawable-land. But then you have to call clearCache(false) on the WebView instance in your onDestroy() method because otherwise the image cached on the first load will always be used (disabling caching on the WebView instance does not work).
After spending a lot of time on this problem I found the solution!
All you need to do is ask for more memory.
Place this code inside your android manifest under:
<application>:
Put:
android:largeHeap="true"
Worked great for me!
Please note that this solution works only on API 11 and above.
More info here.
A lot of devices have very limited and restricted memory available to each device. A lot of older devices allocate 16MB of memory to your application, while some more modern devices might allocate 24MB or even 32MB (I've seen a device with only 14MB).
Whenever you load so many images into memory, this space fills up very quickly causing the OutOfMemoryError to be thrown. To overcome this problem, you should (as previous answers have said) shrink the images to thumbnails and only keep the thumbnails in device memory (reduced memory footprint) and have the images saved to SDCARD.
You can see how much memory your program is using from the DDMS layout in Eclipse. I believe you can also override the Application class to listen for a "Low Memory" warning function.
When you read in the Bitmap through the BitmapFactory, set the BitmapFactory.Option inScaled parameter to 2 or 4 (or whatever works for you) to create a smaller, less memory intensive image.
Generally, there is only one solution: use smaller images. If there's no code it's hard to say what's exactly wrong. You may try to lower image size.
in addition to what people have written here , i suggest watching this video of google , which point to some common memory issues and how to find the cause to your memory problem:
Memory management for Android Apps
I had the same problem before and I was debugging on S4 android 4.3.
The solution was : Copy the images from the mdpi folder to hdpi folder (so they are now on both folder)
I know weird! but this solved my problem.
It seams like ur image is big size so u can decode your image and use android:largeHeap="true". inside manifest of Application Tag
you might have gone through all the above solutions, but still give it a try.
I was lost in finding a solution until I got it work.
This might night work for your case (Excuse me in that case).
myIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_TASK); myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
place these before you call your activity.

Problem with nesting layouts

I have a following situation in my xml:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#drawable/topbar"
>
<TableRow >
<TextView android:minWidth="280sp"
android:id="#+id/header"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_vertical"
android:textColor="#color/path_color"
android:paddingLeft="10px"/>
</TableRow>
</TableLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<org.solid.explorer.HorizontalPager
android:id="#+id/horizontal_pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</org.solid.explorer.HorizontalPager>
<RelativeLayout
android:id="#+id/contextMenu"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone"
>
<org.solid.explorer.ContextOption
android:layout_height="wrap_content"
android:layout_width="wrap_content"
/>
<org.solid.explorer.ContextOption
android:layout_height="wrap_content"
android:layout_width="wrap_content"
/>
<org.solid.explorer.ContextOption
android:layout_height="wrap_content"
android:layout_width="wrap_content"
/>
<org.solid.explorer.ContextOption
android:layout_height="wrap_content"
android:layout_width="wrap_content"
/>
<org.solid.explorer.ContextOption
android:layout_height="wrap_content"
android:layout_width="wrap_content"
/>
</RelativeLayout>
<LinearLayout
android:id="#+id/drag_view"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone">
<ImageView
android:id="#+id/drag_icon"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
<TextView
android:id="#+id/drag_label"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
</LinearLayout>
<!-- <ImageView
android:id="#+id/drag_icon1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:visibility="gone"
/> -->
</RelativeLayout>
</LinearLayout>
The problem is with the LinearLayout with id drag_view.
In program code, I am using ImageView with id drag_icon1 (it is being dragged by finger). Then everything is fine. But i want to add text to this icon so then I need to drag not the ImageView but the LinearLayout with ImageView and TextView inside, am I right?
But when I switch to the LinearLayout and comment the old ImageView (as in presented xml) the program fails at the setContentView method (second line of onCreate(), so further code has nothing common with this problem). WTF? If drag_icon1 is uncommented and used as dragged image then everything is fine, setContentView works (even with drag_view present).
Here is the stack trace:
E/AndroidRuntime(13517): FATAL EXCEPTION: main
E/AndroidRuntime(13517): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.solid.explorer/org.solid.explorer.Explorer}:java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams
E/AndroidRuntime(13517): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1816)
E/AndroidRuntime(13517): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1837)
E/AndroidRuntime(13517): at android.app.ActivityThread.access$1500(ActivityThread.java:132)
E/AndroidRuntime(13517): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1033)
E/AndroidRuntime(13517): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(13517): at android.os.Looper.loop(Looper.java:143)
E/AndroidRuntime(13517): at android.app.ActivityThread.main(ActivityThread.java:4196)
E/AndroidRuntime(13517): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(13517): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(13517): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/AndroidRuntime(13517): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/AndroidRuntime(13517): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(13517): Caused by: java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams
E/AndroidRuntime(13517): at org.solid.explorer.Explorer.onCreate(Explorer.java:126)
E/AndroidRuntime(13517): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
E/AndroidRuntime(13517): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1780)
E/AndroidRuntime(13517): ... 11 more
It suggests that something wrong is with LayoutParams, but with drag_icon1 it works without problems.. I don't have any idea what is wrong.. Thank you for any suggestions
Assuming the layout XML you posted is the complete file, the problems I see are:
You need to have a single root element.
You close a LinearLayout at the bottom of the document that I don't see.
However, if this is true, I'm not sure how you could get it to work by uncommenting the ImageView.

Categories

Resources