Scaling bitmap resulting in NullPointerException in Android - java

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

Related

Android java.lang.NullPointerException error with BroadcastReceiver

Everytime the application gets to my second activity it crashes, giving the error.
My activity:
public class SecondActivity extends AppCompatActivity {
EditText barcodeText = findViewById(R.id.barcodeText);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
IntentFilter filter = new IntentFilter();
filter.addCategory(Intent.CATEGORY_DEFAULT);
filter.addAction(getResources().getString(R.string.activity_intent_filter_action));
registerReceiver(myBroadcastReceiver, filter);
}
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle b = intent.getExtras();
if (action.equals(getResources().getString(R.string.activity_intent_filter_action))) {
try {
displayScanResult(intent);
} catch (Exception e) {
}
}
}
};
private void displayScanResult(Intent initiatingIntent)
{
String decodedSource = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_source));
String decodedData = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_data));
String decodedLabelType = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_label_type));
barcodeText.setText(decodedData);
}
}
Logcat:
07-01 12:37:03.373 349-349/com.example.provatimer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.provatimer, PID: 349
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.provatimer/com.example.provatimer.SecondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5256)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:149)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
at android.content.Context.obtainStyledAttributes(Context.java:438)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.provatimer.SecondActivity.<init>(SecondActivity.java:14)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5256) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
I think it may have something to do with the context in the BroadcastReceiver, but I tried to declare it in the onCreate method but nothing changed.
Maybe I don't initialize correctly the intent in which the data should be stored, if so, how can I do it correctly?
All the Strings should be correct int the string.xml file, if the error may come from that I'll write them.
I think the error is happening here:
EditText barcodeText = findViewById(R.id.barcodeText);
You are invoking findViewById() directly in the class member declaration.
You have invoke findViewById() after setContentView()
EditText barcodeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
barcodeText = findViewById(R.id.barcodeText);
}

NullPointer exception while setting Bitmap in ImageView [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I wanted to load an image into an imageview of the app from my mobile storage. Just to be sure, I kept the image in both internal and external storage. But while compiling, I am getting a null pointer exception. I also placed the same image in drawable folder and tried to set the imageview from there. But faced the same issue. Can anyone help me here!. I am adding the code snippets that I tried.
Method-1:
File imageFile = new File(Environment.getExternalStorageDirectory(),"golden_eagle.jpg");
if(imageFile.exists()) {
Log.v(LOGTAG, "Image file exists");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap outputImageBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);
ImageView imageView = (ImageView)findViewById(R.id.sample_image);
imageView.setImageBitmap(outputImageBitmap);
}
Method-2:
Bitmap bitimage;
bitimage = BitmapFactory.decodeResource(getResources(), R.drawable.golden_eagle);
if(bitimage == null)
Log.v(LOGTAG,"bitimage is empty");
else
Log.v(LOGTAG,"bitimage is not empty");
ImageView imageView = (ImageView)findViewById(R.id.sample_image);
imageView.setImageBitmap(bitimage);
Method-3:
ImageView imageView = (ImageView)findViewById(R.id.sample_image);
int resid = getResources().getIdentifier("golden_eagle","drawable",getPackageName());
imageView.setImageResource(resid);
//imageView.setImageResource(R.drawable.golden_eagle);
Method 4:
//Some class extending AppCompatActivity
asyncTask.execute();
//some asyncTask
onpostExecute(){
//Method:1
//Method:2
//Method:3
}
All the above methods ended with same compilation error
12-24 20:16:42.520 1349-1349/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.home.BequestProto, PID: 1349
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.home.BequestProto/com.example.home.BequestProto.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1494)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at com.example.home.BequestProto.MainActivity.onCreate(MainActivity.java:75)
at android.app.Activity.performCreate(Activity.java:6582)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2532)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1494)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
The Error is occurring at at the line where I am setting image to imageview.
I know that It is a null pointer exception because some where I forgot to initialize the required object. I want to know which one.
"Method 4:" Shows that you are executing with async task. I guess the layout changed and it tryed to set the image after.
ImageView imageView = (ImageView)findViewById(R.id.sample_image);
if (imageView != null)
imageView.setImageBitmap(outputImageBitmap);
This will set the image only if View is present
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
This would appear to be from "Method-3", where you are calling setImageResource().
This error means that this line is where your problem lies:
ImageView imageView = (ImageView)findViewById(R.id.sample_image);
imageView is null in all four cases, because findViewById() cannot find this widget.
Double check if you have ImageView with id sample_image. It's not found in your layout

NullPointerException (GameActivity does not open)

Please check whats the problem with my code here :
Main Activity :
I'm using Android Studio. Import statements are managed for me. It won't be necessary to write them here
public class MainActivity extends Activity implements View.OnClickListener {
SharedPreferences prefs;
String dataName = "MyData";
String intName = "MyString";
int defaultInt = 0;
public static int highScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonPlay = (Button) findViewById(R.id.btnPlay);
TextView textHighScore = (TextView) findViewById(R.id.textHighScore);
buttonPlay.setOnClickListener(this);
prefs = getSharedPreferences(dataName, MODE_PRIVATE);
highScore = prefs.getInt(intName, defaultInt);
textHighScore.setText("High Score: " + highScore);
}
#Override
public void onClick(View view) {
Intent intent;
intent = new Intent(this, GameActivity.class);
startActivity(intent);
}
}
When I run this application Main Activity is loaded but when I hit play button application closes. I have checked the play button's ID is O.K. I had the same problem in GameActivity but at last I figured out that the problem was with the ID but this time I think problem is with the this I used in Intent();. Activity fails to load.
Exception :
06-24 01:34:05.196 12826-12826/com.cruzerblade.memorygame E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.cruzerblade.memorygame, PID: 12826
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.cruzerblade.memorygame/com.cruzerblade.memorygame.GameActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
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.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.view.animation.AnimationUtils.loadAnimation(AnimationUtils.java:75)
at com.cruzerblade.memorygame.GameActivity.<init>(GameActivity.java:55)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
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) 
Please help me out! It took me too much time still I couldn't figure out the problem.
Quoting from your logcat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.res.Resources android.content.Context.getResources()'
on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.view.animation.AnimationUtils.loadAnimation(AnimationUtils.java:75)
at com.cruzerblade.memorygame.GameActivity.<init>(GameActivity.java:55)
This last line is the only line in the trace that is your code:
Look on line 55 of GameActivity.java. It is calling loadAnimation. There is something wrong with the animation it is trying to load (probably a missing resource ID, but it could also be a null or invalid context argument for loadAnimation.)

Fatal exception while starting activity using intent (null pointer exception)

The following piece of code is throwing a null pointer exception in my application.Im trying to invoke an activity through an intent, (some background info on this is that the activity being opened is triggered through the click of a button, thus I have called the startActivity() function in the button's onclickListener itself.
Here's the code:
public class CategoryButtonOnClickListener extends Activity implements View.OnClickListener {
private final int position;
public CategoriesPage categoriesPage;
Context context;
public CategoryButtonOnClickListener(int position, Context contextPassed) {
this.position = position;
this.context = contextPassed;
categoriesPage = new CategoriesPage();
}
public void onClick(View v) {
callCategoryList(this.position);
}
public void callCategoryList(int position) {
String[] categories = categoriesPage.getCategories();
Intent categoriesList = new Intent(this.context,BooksWithCategories.class);
//I tried commenting this code to fix it as seen from another post, didnt work
//categoriesList.putExtra("Category:",categories[position]);
startActivity(categoriesList);
//Toast.makeText(context,categories[position],Toast.LENGTH_LONG).show();
}
}
The error thrown is as follows:
1-17 23:27:15.076 2614-2614/com.dogra.booker E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.dogra.booker, PID: 2614
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.Activity.startActivityForResult(Activity.java:3736)
at android.app.Activity.startActivityForResult(Activity.java:3697)
at android.app.Activity.startActivity(Activity.java:4007)
at android.app.Activity.startActivity(Activity.java:3975)
at com.dogra.booker.UI.Model.CategoryButtonOnClickListener.callCategoryList(CategoryButtonOnClickListener.java:36)
at com.dogra.booker.UI.Model.CategoryButtonOnClickListener.onClick(CategoryButtonOnClickListener.java:29)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java: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)
Any suggestions on what could be the problem are appreciated.
Place this method in your code :
Activity getAct() {
Context context = getContext();
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
return null;
}
and then use it for starting the activity:
Intent categoriesList = new Intent(getAct(),BooksWithCategories.class);
can try this
Intent categoriesList = new Intent(CategoryButtonOnClickListener.this,BooksWithCategories.class);

createBitmap throws outOfMemory exception very often

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")))

Categories

Resources