my app is throwing outofmemory exceptions to lots of people using it. my app creates a bitmap of the current screen then animates it to transition between pages.
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4222)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4217)
... 10 more
Caused by: android.view.InflateException: Binary XML file line #118: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:640)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:55)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:689)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:748)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:821)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at com.de_veloper.businessbuilder.MainActivity.premiumMenu(MainActivity.java:558)
... 13 more
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
at android.view.LayoutInflater.createView(LayoutInflater.java:614)
... 23 more
Caused by: java.lang.OutOfMemoryError: Failed to allocate a 8683212 byte allocation with 6867876 free bytes and 6MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:726)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:547)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1014)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:3723)
at android.content.res.Resources.loadDrawable(Resources.java:3596)
at android.content.res.TypedArray.getDrawable(TypedArray.java:750)
at android.widget.ImageView.<init>(ImageView.java:151)
at android.widget.ImageView.<init>(ImageView.java:140)
at android.widget.ImageView.<init>(ImageView.java:136)
... 26 more
the code that creates the bitmap
public static Bitmap loadBitmapFromView(View v) {
Bitmap bitmap;
v.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v.getDrawingCache());
bitmap.setHasAlpha(false);
v.setDrawingCacheEnabled(false);
return bitmap;
}
the code that animates the bitmap
public void mainMenu(View view) {
$isonfirstpage = 0;
$isonmainmenu = 1;
$isonpremiummenu = 0;
final RelativeLayout backgroundLayout = (RelativeLayout) findViewById(R.id.activity_background);
LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout newLayout = (RelativeLayout)inflate.inflate(R.layout.main_menu, null);
Bitmap bitmap = loadBitmapFromView(backgroundLayout);
Drawable d = new BitmapDrawable(getResources(), bitmap);
backgroundLayout.removeAllViewsInLayout();
View mainmenuView = findViewById(R.id.mainmenuView);
View firstpageView = findViewById(R.id.firstpageView);
final ImageView screenie = new ImageView(getApplicationContext());
screenie.setImageDrawable(d);
backgroundLayout.addView(newLayout);
backgroundLayout.addView(screenie);
screenie.animate()
.translationY(backgroundLayout.getHeight())
.setDuration(300);
new Handler().postDelayed(new Runnable() {
public void run() {
backgroundLayout.removeView(screenie);
}
}, 1500);
}
when ever the Bitmap size is huse then you will get OutOfMemory Exception you can decode/scale the bitmap when ever you are setting it to the imageview.
public Bitmap decodeUri(Uri path) throws FileNotFoundException
{
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(path),null,o);
int REQUIRED_SIZE = 100;
int width_temp = o.outWidth;
int height_temp = o.outHeight;
int scale = 1;
while (true)
{
if(width_temp/2 < REQUIRED_SIZE || height_temp/2<REQUIRED_SIZE)
{
break;
}
width_temp/=2;
height_temp/=2;
scale*=2;
}
BitmapFactory.Options o1 =new BitmapFactory.Options();
o1.inSampleSize = scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(path),null,o1);
}
you can covert your image path to Uri as follows
decodeUri(Uri.fromFile(new File("your file path")))
Related
I am trying to scale a bitmap image. However, when I scale it, I get an error. This is my full stack trace:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nodomain.speedtap2, PID: 3113
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nodomain.speedtap2/com.nodomain.speedtap2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Bitmap.setHasAlpha(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3322)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3418)
at android.app.ActivityThread.access$1100(ActivityThread.java:231)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1823)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7422)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Bitmap.setHasAlpha(boolean)' on a null object reference
at android.graphics.Bitmap.createBitmap(Bitmap.java:979)
at android.graphics.Bitmap.createBitmap(Bitmap.java:946)
at android.graphics.Bitmap.createBitmap(Bitmap.java:877)
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:753)
at com.nodomain.speedtap2.MainMenu.<init>(MainMenu.java:47)
at com.nodomain.speedtap2.MainActivity$GameView.<init>(MainActivity.java:54)
at com.nodomain.speedtap2.MainActivity.onCreate(MainActivity.java:33)
at android.app.Activity.performCreate(Activity.java:6904)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3269)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3418)
at android.app.ActivityThread.access$1100(ActivityThread.java:231)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1823)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7422)
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) `
But didn't I already make a Bitmap with BitmapFactory.decodeResource(...)? This is my code:
public class MainMenu {
private Bitmap playButton;
public MainMenu (Context context) {
playButton = BitmapFactory.decodeResource(context.getResources(), R.drawable.play_button);
float aspectRatio = 421/475;
int playButtonWidth = MainActivity.screenX / 5;
int playButtonHeight = (int)(MainActivity.screenX / (aspectRatio));
playButton = Bitmap.createScaledBitmap(playButton, playButtonWidth, playButtonHeight, false);
}
Maybe I'm not fully understanding the error...
public class MainMenu {
public static Bitmap playButton;
Context mcontext;
public static Bitmap MainMenu(Context context) {
playButton = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);
float aspectRatio = 421/475;
int playButtonWidth = MainActivity.screenX / 5;
int playButtonHeight = (int)(MainActivity.screenX / (aspectRatio));
playButton = Bitmap.createScaledBitmap(playButton, 100, 100, false);
return playButton;
}
}
the issue is that your playButtonWidth ,playButtonHeight returns null. so it crash please share how you getting MainActivity.screenX , try this
I am developing an app that show all album image covers. But it crashes with this error:
11-10 18:08:48.148 16187-16187/com.xrobot.andrew.musicalbums E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.xrobot.andrew.musicalbums, PID: 16187
java.lang.OutOfMemoryError: Failed to allocate a 1459276 byte allocation with 421736 free bytes and 411KB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:635)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:611)
at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:391)
at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:417)
at android.graphics.drawable.Drawable.createFromPath(Drawable.java:1230)
at com.xrobot.andrew.musictest2.SongAdapter.getView(SongAdapter.java:73)
at android.widget.AbsListView.obtainView(AbsListView.java:2346)
at android.widget.ListView.makeAndAddView(ListView.java:1875)
at android.widget.ListView.fillDown(ListView.java:702)
at android.widget.ListView.correctTooLow(ListView.java:1484)
at android.widget.ListView.fillGap(ListView.java:676)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5036)
at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:4584)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:603)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Partial code in the onCreate method:
...
while(...){
String thisCover = getCoverArtPath(cursor.getLong(6), getApplicationContext());
songList.add(new Song(thisId, thisTitle, thisArtist, thisPath, thisDuration, thisCover));
}
SongAdapter songAdt = new SongAdapter(getApplicationContext(), songList);
...
Code that I use to get the album image cover:
private static String getCoverArtPath(long albumId, Context context) {
Cursor albumCursor = context.getContentResolver().query(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Albums.ALBUM_ART},
MediaStore.Audio.Albums._ID + " = ?",
new String[]{Long.toString(albumId)},
null
);
boolean queryResult = albumCursor.moveToFirst();
String result = null;
if (queryResult) {
result = albumCursor.getString(0);
}
albumCursor.close();
return result;
}
Layout AlbumCover :
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/song_cover"
android:scaleType = "fitXY"
android:src="#drawable/note"
android:background="#171717"
android:padding="1dp"
android:layout_marginLeft="3dp" />
getView in the Adapter:
#Override
public View getView(View convertView, ViewGroup parent) {
RelativeLayout songLay = (RelativeLayout)songInf.inflate
(R.layout.song_layout, parent, false);
ImageView coverView = (ImageView)songLay.findViewById(R.id.song_cover);
//get song using position
Song currSong = songs.get(position);
if (Drawable.createFromPath(currSong.getCover()) != null) {
Drawable img = Drawable.createFromPath(currSong.getCover());
coverView.setImageDrawable(img);
}
//set position as tag
songLay.setTag(position);
return songLay;
}
EDIT:
I have tryed glide as suggested, but I still get the same error:
if (Drawable.createFromPath(currSong.getCover()) != null) {
Drawable img = Drawable.createFromPath(currSong.getCover());
Glide.with(mContext).load("").placeholder(img).override(50,50).into(coverView);
}
This is the new error:
11-11 11:05:55.866 11120-11120/com.xrobot.andrew.musicalbumsE/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.xrobot.andrew.musicalbums, PID: 11120
java.lang.OutOfMemoryError: OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack trace available
I have an issue with setting a bitmap in an Alert dialog. I created a barcode in another class and I want to show the barcode in a dialog. It keeps showing an error. From the logs, the barcode is being created successfully. The problem keeps pointing to the qrCodeImageView.setImageBitmap(bitmap); line. Please help.
This is the method in the activity.
public void showQRCode(final Bundle bundle){
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
barcodeUtil = new BarcodeUtil();
Bitmap bitmap = barcodeUtil.createQRCcode(ContactDetailActivity.this, bundle);
AlertDialog.Builder builder = new AlertDialog.Builder(ContactDetailActivity.this);
Log.i(Constants.TAG_GBACARD, "Bmp in Dialog: " + bitmap);
LayoutInflater inflater = getLayoutInflater();
View dialogLayout = inflater.inflate(R.layout.custom_dialog, null);
builder.setView(dialogLayout);
final ImageView qrCodeImageView = (ImageView) findViewById(R.id.qrCode);
qrCodeImageView.setImageBitmap(bitmap);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog b = builder.create();
b.show();
} catch (Exception e){
e.printStackTrace();
}
}
});
}
This is the method that creates the barcode
public Bitmap createQRCcode(final Context context, final Bundle bundle) {
Bitmap bitmap = null;
try {
//Find screen size
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int width = point.x;
int height = point.y;
int smallerDimension = width < height ? width : height;
smallerDimension = smallerDimension * 3 / 4;
//Encode with a QR Code image
qrCodeEncoder = new QRCodeEncoder(null,
bundle,
Contents.Type.CONTACT,
BarcodeFormat.QR_CODE.toString(),
smallerDimension);
bitmap = qrCodeEncoder.encodeAsBitmap();
Log.i(Constants.TAG_GBACARD, "QR Encoded");
Log.i(Constants.TAG_GBACARD, "Bitmap: " + bitmap);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
This is the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at newgbacard.gbacard.com.gbacard.activities.ContactDetailActivity$10.run(ContactDetailActivity.java:336)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at android.app.Activity.runOnUiThread(Activity.java:5575)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at newgbacard.gbacard.com.gbacard.activities.ContactDetailActivity.showQRCode(ContactDetailActivity.java:316)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at newgbacard.gbacard.com.gbacard.activities.ContactDetailActivity$5.onClick(ContactDetailActivity.java:168)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at android.view.View.performClick(View.java:5184)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at android.view.View$PerformClick.run(View.java:20910)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at android.os.Looper.loop(Looper.java:145)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5942)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at java.lang.reflect.Method.invoke(Native Method)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Please Help. Thanks
Please replace this
final ImageView qrCodeImageView = (ImageView) findViewById(R.id.qrCode);
with this
final ImageView qrCodeImageView = (ImageView) dialogLayout.findViewById(R.id.qrCode);
My app keep crashing, and I can't understand what's wrong with it, been searching for answer everywhere, from what I understood, people said it is because of the device is out of memory, but I don't understand what is causing this ?
Is it because I have too many images in my res/drawable folder ?
Is it because I have one quite high resolution image in my res/drawable folder ?
If the problem is one of the above, what is the solution ? put the images in assets folder or what ? Below is the error stacks.
Thank you.
MainActivity.java
public class MainActivity extends Activity {
Class <? extends Activity> classVariable;
int last_level;
TextView text_play, text_level, game_title;
RelativeLayout playBtn, levelBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playBtn = (RelativeLayout) findViewById(R.id.playBtn);
levelBtn = (RelativeLayout) findViewById(R.id.levelBtn);
game_title = (TextView) findViewById(R.id.game_title);
text_play = (TextView) findViewById(R.id.text_play);
text_level = (TextView) findViewById(R.id.text_level);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/snap-itc.ttf");
text_play.setTypeface(tf);
text_level.setTypeface(tf);
game_title.setTypeface(tf);
// Check if file exists
File file = getBaseContext().getFileStreamPath("levels.json");
if (file.exists()) {
// Get the JSON Object from the data
JSONObject parent = this.parseJSONData();
try {
last_level = parent.getInt("level");
} catch (JSONException e) {
e.printStackTrace();
}
}
switch (last_level) {
case 1:
classVariable = Level002Activity.class;
break;
case 2:
classVariable = Level003Activity.class;
break;
case 3:
classVariable = Level004Activity.class;
break;
case 5:
classVariable = Level005Activity.class;
break;
default:
classVariable = Level001Activity.class;
}
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
Level002Activity.class);
startActivity(i);
}
});
levelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(getApplicationContext(),
Level001Activity.class);
startActivity(in);
}
});
}
public JSONObject parseJSONData() {
String JSONString = null;
JSONObject jsonObject = null;
try {
// Open the inputStream to the file
FileInputStream fin = openFileInput("levels.json");
int sizeOfJSONFile = fin.available();
// array that will store all the data
byte[] bytes = new byte[sizeOfJSONFile];
// reading data into the array from the file
fin.read(bytes);
// close the input stream
fin.close();
JSONString = new String(bytes, "UTF-8");
jsonObject = new JSONObject(JSONString);
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JSONException x) {
x.printStackTrace();
return null;
}
return jsonObject;
}
}
It keeps showing that error when calling ChooseLevelActivity.class
ChooseLevelActivity.java
public class ChooseLevelActivity extends Activity implements View.OnClickListener {
ImageView level001, level002, level003, level004, level005;
int last_level, best_move;
String best_time, level_selected;
TextView levelName, bestMove, bestTime;
Class <? extends Activity> classVariable;
Button playBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choose_level);
level001 = (ImageView) findViewById(R.id.level001);
level002 = (ImageView) findViewById(R.id.level002);
level003 = (ImageView) findViewById(R.id.level003);
level004 = (ImageView) findViewById(R.id.level004);
level005 = (ImageView) findViewById(R.id.level005);
levelName = (TextView) findViewById(R.id.level_name);
bestMove = (TextView) findViewById(R.id.best_move);
bestTime = (TextView) findViewById(R.id.best_time);
playBtn = (Button) findViewById(R.id.playBtn);
// Get the JSON Object from the data
JSONObject parent = parseJSONData("levels.json");
// Array of ImageView
final ImageView[] levelsArray = {level001, level002, level003, level004, level005};
// This will store all the values inside "best_move and time" in an element string
try {
last_level = parent.getInt("level");
} catch (JSONException e) {
e.printStackTrace();
}
for(int i = 0; i < last_level; i++) {
levelsArray[i].setVisibility(View.VISIBLE);
levelsArray[i].setOnClickListener(this);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.level001:
level_selected = "level001";
classVariable = Level001Activity.class;
break;
case R.id.level002:
level_selected = "level002";
classVariable = Level002Activity.class;
break;
case R.id.level003:
level_selected = "level003";
classVariable = Level003Activity.class;
break;
case R.id.level004:
level_selected = "level004";
classVariable = Level004Activity.class;
break;
case R.id.level005:
level_selected = "level005";
classVariable = Level005Activity.class;
break;
}
String fileName = "record_" + level_selected + ".json";
// Get the JSON Object from the data
JSONObject parents = parseJSONData(fileName);
// This will store all the values inside "best_move and time" in an element string
try {
best_move = parents.getInt("best_move");
best_time = parents.getString("best_time");
} catch (JSONException e) {
// e.printStackTrace();
}
levelName.setText("Level " + level_selected.substring(5));
bestMove.setText("Best Move: " + best_move);
bestTime.setText("Best Time: " + best_time);
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
classVariable);
startActivity(i);
finish();
}
});
}
public JSONObject parseJSONData(String file) {
String JSONString = null;
JSONObject jsonObject = null;
try {
// Open the inputStream to the file
FileInputStream fin = openFileInput(file);
int sizeOfJSONFile = fin.available();
// array that will store all the data
byte[] bytes = new byte[sizeOfJSONFile];
// reading data into the array from the file
fin.read(bytes);
// close the input stream
fin.close();
JSONString = new String(bytes, "UTF-8");
jsonObject = new JSONObject(JSONString);
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JSONException x) {
x.printStackTrace();
return null;
}
return jsonObject;
}
}
Error Stacks:
Process: com.example.ed.pieces, PID: 12939
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ed.pieces/com.example.ed.pieces.Level001Activity}: android.view.InflateException: Binary XML file line #289: Binary XML file line #289: Error inflating class <unknown>
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #289: Binary XML file line #289: Error inflating class <unknown>
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:393)
at android.app.Activity.setContentView(Activity.java:2166)
at com.example.ed.pieces.Level001Activity.onCreate(Level001Activity.java:62)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #289: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:645)
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:694)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:762)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:393)
at android.app.Activity.setContentView(Activity.java:2166)
at com.example.ed.pieces.Level001Activity.onCreate(Level001Activity.java:62)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance(Native Method)
at android.view.LayoutInflater.createView(LayoutInflater.java:619)
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
Caused by: java.lang.OutOfMemoryError: Failed to allocate a 10240012 byte allocation with 4194304 free bytes and 7MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1080)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:2635)
at android.content.res.Resources.loadDrawable(Resources.java:2540)
at android.content.res.TypedArray.getDrawable(TypedArray.java:870)
at android.view.View.<init>(View.java:3948)
at android.widget.ImageView.<init>(ImageView.java:145)
at android.widget.ImageView.<init>(ImageView.java:140)
at android.widget.ImageView.<init>(ImageView.java:136)
Out of Memory Error
Out of memory error is very common error when you are developing for a application that deals with multiple images sets or large bitmaps or some Animation stuff. In this case we have to be very careful and efficient while handling the images or object allocation and deallocation. OOM error comes when the allocation crosses the heap limit or your process demand a amount of memory that crosses the heap limit.
In Android, every application runs in a Linux Process. Each Linux Process has a Virtual Machine (Dalvik Virtual Machine) running inside it. There is a limit on the memory a process can demand and it is different for different devices and also differs for phones and tablets. When some process demands a higher memory than its limit it causes a error i.e Out of memory error.
Try this may help you add this tag in your manifest file.
android:largeHeap="true"
it will allocate large heap for your app
To convert Drawable into Bitmap,Use this,
Drawable myDrawable = getResources().getDrawable(R.drawable.logo);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
Using this method,you can decode your image
public static Bitmap decodeImageFile(File f,int WIDTH,int HIGHT){
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_WIDTH=WIDTH;
final int REQUIRED_HIGHT=HIGHT;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
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;
}
Then call this method where you using this:
Bitmap b = decodeImageFile(f, 1280, 720);
if your image resolution is high, i suggested you loading image with buffer.
String defCoverPath = "drawable/" + "def_cover" + ".png";
yourView.setBackgroundDrawable(LoadResourceImage(defCoverPath));
public static BitmapDrawable LoadResourceImage(String resPath){
AssetManager assets = MyApp.GetContext().getResources().getAssets();
BitmapDrawable bitmapDrawable = new BitmapDrawable();
try {
InputStream buffer = new BufferedInputStream((assets.open(resPath)));
Bitmap bitmap = BitmapFactory.decodeStream(buffer);
bitmapDrawable = new BitmapDrawable(MyApp.GetContext().getResources(), bitmap);
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmapDrawable;
}
I keep getting this error and i'm not sure why. I've tried googling it but no luck there.
04-21 15:43:24.822 2461-2461/com.example.s.myapplication D/AndroidRuntime﹕ Shutting down VM
04-21 15:43:24.823 2461-2461/com.example.s.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.s.myapplication, PID: 2461
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.s.myapplication/com.example.s.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3539)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
at com.example.s.myapplication.MainActivity.onActivityResult(MainActivity.java:46)
at android.app.Activity.dispatchActivityResult(Activity.java:6139)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3535)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
a
This is my main activity. What the application is meant to do is:
Take a photo
Save the photo in a tmp location
load the photo into a imageview
.
package com.example.s.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
public class MainActivity extends Activity {
static final int REQUEST_IMAGE_CAPTURE = 1;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openCamera();
setContentView(R.layout.activity_main);
}
public void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Check that request code matches ours:
if (requestCode == REQUEST_IMAGE_CAPTURE) {
//Get our saved file into a bitmap object:
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
imageView.setImageBitmap(image);
}
}
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) {
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight) {
inSampleSize = Math.round((float) height / (float) reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth) {
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float) width / (float) reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
public void capture_btn(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
imageView = (ImageView)findViewById(R.id.imageView2);
This worked for me:
I wrote wrong the id of my imageView. It supposed to be imageView2
imageView = findViewById(R.id.imageView2);
if above solutions did not work for you check
oncreate method again it should be like this
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);imageView=findViewById(R.id.imageView);
setContentView(R.layout.activity_main);
imageView=findViewById(R.id.imageView);
}