How to make activity which shows introduction images when android app is launched for the first time?
I have 4 images that describe the app. So I want those images to show up when the app runs for the first time and user can swipe from one image to the next in order to unblock working part of the app.
For checking if app is lunched first time use SharedPreferences and for displaying images you have to use Bitmap, because without it you will get memory errors.
Add this code in your activity class.(Not in onCreate method)
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
After in your onCreate method check if app lunched first time and add images to imageView widget.
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
ImageView imageView = (ImageView) findViewById(R.id.imageView);
ImageView imageView2 = (ImageView) findViewById(R.id.imageView2);
imageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(),R.drawable.image1,350,350));
imageView2.setImageBitmap(decodeSampledBitmapFromResource(getResources(),R.drawable.image2,350,350));
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
}
Save a flag in sharedPreferences the first time you access the tutorial, then check it on launch.
If no flag:
LauncherActivity -> TutorialActivity (shows four images) save flag -> MainActivity
If flagged:
Launcher Activity -> MainActivity
Check android dev guide for sharepreferences help.
Also Im not sure what you mean about showing during installation. If you mean during loading, then just go ahead and display the images during loading?
This is called Appintro. Which runs first time when app launches
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
public boolean isFirstStart;
Context mcontext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// Intro App Initialize SharedPreferences
SharedPreferences getSharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
// Create a new boolean and preference and set it to true
isFirstStart = getSharedPreferences.getBoolean("firstStart", true);
// Check either activity or app is open very first time or not and do action
if (isFirstStart) {
// Launch application introduction screen
Intent i = new Intent(MainActivity.this, MyIntro.class);
startActivity(i);
SharedPreferences.Editor e = getSharedPreferences.edit();
e.putBoolean("firstStart", false);
e.apply();
}
}
});
t.start();
}
}
http://www.viralandroid.com/2016/10/android-appintro-slider-example.html
http://www.androidhive.info/2016/05/android-build-intro-slider-app/
https://github.com/apl-devs/AppIntro
Related
I use these two functions, slightly modified from Google's code in the Android docs to use filepaths:
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromFilePath(String pathName, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(pathName, options);
}
With the idea being to use a scaled-down version of the Bitmap to be mapped onto an ImageView rather than the full-thing, which is wasteful.
mImageView.setImageBitmap(decodeSampledBitmapFromFilePath(pathToFile, 100, 100));
I implemented a thing where you press a button and it rotates to the next image, but there's still a significant lag (it takes a moment for the ImageView to populate) on my phone compared to my emulator. And then occasionally my phone app will crash and I can't replicate it on my emulator.
Is there a problem with this code I've posted above? Is there a problem with the way I am using the code?
Example:
public void reloadPic() {
new Thread(new Runnable() {
#Override
public void run() {
final Bitmap bm = decodeSampledBitmapFromFilePath(filepath, mImageViewWidth, mImageViewHeight);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mImageView.setImageBitmap(bm);
}
});
}
}).start();
}
Your code is jumping between threads several times. First you launch a thread. Then you wait for it to be scheduled You decode on that thread. Then you post a command to the UI thread and wait for it to be scheduled. THen you post a draw command to the ui thread (that's part of what setImageBitmap does). Then you have to process any other commands that came in first. Then you actually draw the screen. There's really only 3 ways to speed this up:
1) Get rid of the thread. You shouldn't decode lots of images on the UI thread, but decoding 1 isn't too bad.
2)Store the images in the right size to begin with. This may mean creating thumbnails of the images ahead of time. Then you don't need to scale.
3)Preload your images. If there's only one button and you know what image it will load, load it before you need it, so when the button is pressed you have it ready. Wastes a bit of memory, but only 1 image worth. (This isn't a viable solution if you have a lot of possible next images).
Using Xamarin and MvvmCross, I'm writing an Android application that is loading the images from an album into an MvxGridView with a custom binding:
<MvxGridView
android:id="#+id/grid_Photos"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:numColumns="3"
android:verticalSpacing="4dp"
android:horizontalSpacing="4dp"
android:stretchMode="columnWidth"
android:fastScrollEnabled="true"
local:MvxBind="ItemsSource AllPhotos"
local:MvxItemTemplate="#layout/item_photo_thumbnail" />
Which uses item_photo_thumbnail.axml:
<ImageView
local:MvxBind="PicturePath PhotoPath"
style="#style/ImageView_Thumbnail" />
Here is the binding class:
public class PicturePathBinding : MvxTargetBinding
{
private readonly ImageView _imageView;
public PicturePathBinding(ImageView imageView)
: base(imageView)
{
_imageView = imageView;
}
public override MvxBindingMode DefaultMode
{
get { return MvxBindingMode.OneWay; }
}
public override Type TargetType
{
get { return typeof(string); }
}
public override void SetValue(object value)
{
if (value == null)
{
return;
}
string path = value as string;
if (!string.IsNullOrEmpty(path))
{
Java.IO.File imgFile = new Java.IO.File(path);
if (imgFile.Exists())
{
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.InJustDecodeBounds = true;
BitmapFactory.DecodeFile(imgFile.AbsolutePath, options);
// Calculate inSampleSize
options.InSampleSize = CalculateInSampleSize(options, 100, 100);
// Decode bitmap with inSampleSize set
options.InJustDecodeBounds = false;
Bitmap myBitmap = BitmapFactory.DecodeFile(imgFile.AbsolutePath, options);
_imageView.SetImageBitmap(myBitmap);
}
}
}
protected override void Dispose(bool isDisposing)
{
if (isDisposing)
{
var target = Target as ImageView;
if (target != null)
{
target.Dispose();
target = null;
}
}
base.Dispose(isDisposing);
}
private int CalculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
{
// Raw height and width of image
int height = options.OutHeight;
int width = options.OutWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth)
{
int halfHeight = height / 2;
int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight &&
(halfWidth / inSampleSize) > reqWidth)
{
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
The problem I'm having is that it is very sluggish and slow. I would love for the each image to load asynchronously. I don't know how to do that. In .net (XAML), their GridView control does everything automatically (with virtualization), but I'm realizing that in Android, it might have to be manually handled?
Can someone help me with this?
I am currently working with remote images, instead of local, so I have been using the Download Cache plugin that gives you the MvxImageView class. That in itself may give you some benefit.
So far my experience with Android is that everything runs if foreground by default, for the most part. Right now, with all of the calculation code inside of the binding class, that is almost certainly going to be run in the foreground.
What I would do to make this run faster is:
Use something like an ObservableCollection for your ItemsSource.
Kick off another thread in the start (or Start) of your View Model to add your items to the ObservableCollection. You can accomplish this easily with Task.Run()
Try to process as much as possible in that background thread with each item before adding it to the ObservableCollection
When updating ObservableCollection from the background thread, the actual update itself has to be done on the UI thread. This is easily done if you are using MvxViewModel as your base for your view model.
this.InvokeOnMainThread(() => myObservableCollection.Add(myItem) );
Following that pattern should actually help you Windows based clients as well.
Updated
I'm trying to display bitmaps efficiently for a wallpaper app which holds 50 wallpapers.
The images I'm using are each 400kb # 1080x1920
I've researched and read I should load a scaled down version of each wallpaper into memory when the app loads instead of loading each wallpaper when it is pressed.
I've read this http://developer.android.com/training/displaying-bitmaps/load-bitmap.html#read-bitmap
How would I implement this using my current code? I've got here from this tutorial on YouTube http://www.youtube.com/watch?v=SxGYGYBFrOM
Here is the updated code, ive included the whole of my MainActivity class
package com.example.ultimateabstractwallpaperhd;
import java.io.IOException;
public class MainActivity extends Activity implements OnClickListener {
// Two classes you mentioned I put here.
ImageView display;
int toPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// check if next two lines are necessary
requestWindowFeature(Window.FEATURE_NO_TITLE); // gets rid of app title
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (android.os.Build.VERSION.SDK_INT>=11) {
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
}
setContentView(R.layout.wallpaper);
toPhone = R.drawable.one;
display = (ImageView) findViewById(R.id.IVdisplay);
ImageView one = (ImageView) findViewById(R.id.IVimage1);
ImageView two = (ImageView) findViewById(R.id.IVimage2);
ImageView three = (ImageView) findViewById(R.id.IVimage3);
ImageView four = (ImageView) findViewById(R.id.IVimage4);
ImageView five = (ImageView) findViewById(R.id.IVimage5);
Button setWall = (Button) findViewById(R.id.BsetWallpaper);
one.setOnClickListener(this);
two.setOnClickListener(this);
three.setOnClickListener(this);
four.setOnClickListener(this);
five.setOnClickListener(this);
setWall.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.IVimage1:
display.setImageResource(R.drawable.one);
toPhone = R.drawable.one;
break;
case R.id.IVimage2:
display.setImageResource(R.drawable.two);
toPhone = R.drawable.two;
break;
case R.id.IVimage3:
display.setImageResource(R.drawable.three);
toPhone = R.drawable.three;
break;
case R.id.IVimage4:
display.setImageResource(R.drawable.four);
toPhone = R.drawable.four;
break;
case R.id.IVimage5:
display.setImageResource(R.drawable.five);
toPhone = R.drawable.five;
break;
case R.id.BsetWallpaper:
InputStream yeaaaa = getResources().openRawResource(toPhone);
Bitmap whatever = decodeSampledBitmapFromResource(getResources(), R.id.IVimage1, 1080, 1500)
try {
getApplicationContext().setWallpaper(whatever);
}catch(IOException e){
e.printStackTrace();
}
break;
}
}
}
EDIT:
Ok, my resources are in the drawable-hpdi folder.
I've still got a few errors, which eclipse has flagged. I've put them in bold.
1)
public static Bitmap decodeSampledBitmapFromResource(**Resources** res, int resId,
int reqWidth, int reqHeight) {
Eclipse explanation: Says resource cannot be resolved into a type
2)
int resId = getResources().**getIdentifier**(R.drawable.one, "drawable", getPackageName());
Bitmap whatever = **decodeSampledBitmapFromResource**(getResources(), R.id.IVimage1, 1080, 1500);
Eclipse explanation:
Method getIdentifier not applicable for arguments list (Sorry if I've simple referenced the drawable incorrectly)
Method decodeSampledBitmapFromResource from the type MainActivity refers to the missing type resources.
Thanks so much for your help so far, it's fantastic to get such quick responses.
EDIT
Name of resource/s: Multiple Resources, named one, two, three, four, five, all with jpg extensions.
Location of resource/s:
res/drawable-hdpi/one.jpg
res/drawable-hdpi/two.jpg
..
res/drawable-hdpi/two.jpg
alternate answer:
InputStream yeaaaa = getResources().openRawResource(toPhone)
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2; \\1 would be the full resolution, 2 is half the size, 4 a quarter etc..
Bitmap whatever = BitmapFactory.decodeStream(inputStream, null, options);
So if you look at the documention you mentioned, you want to create these 2 methods in your class:
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
then instead of :
Bitmap whatever = BitmapFactory.decodeStream(yeaaaa);
use
Bitmap whatever = decodeSampledBitmapFromResource(getResources(), resourceID, width, height)
don't put the resource in raw put it in your drawables folder so you can use the resource ID
you can get the resourceID like so:
getResources().getIdentifier([what ever your named your drawable] , "drawable", getPackageName());
EDIT
per your ajusted code a few things to take note of..
it looks like you are passing the ImageView not the actual resource of a Bitmap..
this line:
Bitmap whatever = decodeSampledBitmapFromResource(getResources(), R.id.IVimage1, 1080, 1500)
should be:
int resId = getResources().getIdentifier([what ever your named your drawable] , "drawable", getPackageName());
Bitmap whatever = decodeSampledBitmapFromResource(getResources(), resId, 1080, 1500)
I have 20 images in my app. All the images are in 640 * 360 resolution with not more than 60KB each.
I make use of Viewpager to slide the images. And use ViewFlipper inside ViewPager to flip the images.. When the user clicks on it, I show the corresponding text for the image.
The issue is that I get OutOfMemory exception when I swipe back and forth for 5 times. I read various Stackoverflow threads here!, here!, here! and Handling Large Bitmaps Efficiently! but not able to fix the issue,
Here is the code,
In Main_Fragment.java,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
--- some code ---
--- some more code ---
View v = inflater.inflate(R.layout.main_fragment, container,false);
viewAnimator = ((ViewAnimator) v.findViewById(R.id.cardFlipper));
TextView caption_text = (TextView) v.findViewById(R.id.caption_text);
caption_text.setText(caption.toUpperCase());
ImageView main_img = (ImageView) v.findViewById(R.id.main_img);
int mainimg_resID = getResources().getIdentifier(mainimg,"drawable",context.getPackageName());
Bitmap icon = decodeSampledBitmapFromResource(getResources(),mainimg_resID,640,360);
main_img.setImageBitmap(icon);
viewAnimator.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AnimationFactory.flipTransition((ViewAnimator) v,FlipDirection.LEFT_RIGHT);
}
});
return v;
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
Can you please tell me what I'm doing wrong?? This is driving me nuts for the past few days :(
yes, I'm seen something very wrong that you are doing:
Bitmap icon = decodeSampledBitmapFromResource(getResources(),mainimg_resID,640,360);
you got it all wrong: the reqHeight and reqWidth parameters should be the image view width and height, and not the original image dimension!! that's all what calculateInSampleSize() is all about..
so, you should do the following:
Bitmap icon = decodeSampledBitmapFromResource(getResources(),mainimg_resID,main_img.getWidth(), main_img.getHeight());
by decoding bitmap in scale calculated based on the dimensions needed only for display - the result bitmap allocation would be minimal.
and by the way - the fact that the size of the resource you are using is only 60KB does not change anything. in fact - the image memory size (Kilobites/Megas) does not have any impact on the allocated bitmap. it's the resolution only that makes the difference!
EDIT
because the imageView dimentions are still zero at the onCreateView() method - you should prform the decoding only after it got it dimentions:
--- some code ---
--- some more code ---
View v = inflater.inflate(R.layout.main_fragment, container,false);
viewAnimator = ((ViewAnimator) v.findViewById(R.id.cardFlipper));
TextView caption_text = (TextView) v.findViewById(R.id.caption_text);
caption_text.setText(caption.toUpperCase());
final ImageView main_img = (ImageView) v.findViewById(R.id.main_img);
ViewTreeObserver vto = main_img.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
final ViewTreeObserver obs = main_img.getViewTreeObserver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
obs.removeOnGlobalLayoutListener(this);
} else {
obs.removeGlobalOnLayoutListener(this);
}
// do here the image decoding + setting the image to the image view
Bitmap icon = decodeSampledBitmapFromResource(getResources(),mainimg_resID,main_img.getWidth(), main_img.getHeight());
// setImage....
}
});
viewAnimator.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AnimationFactory.flipTransition((ViewAnimator) v,FlipDirection.LEFT_RIGHT);
}
});
return v;
EDIT 2
you should never use wrap_content for ImageView. that's because it forces the view to be in the size of the original image (potentially very large) instead of the opposite. when calculating required scale - the whole point is to compare between the ImageView dimentions to the original image(resource/file/stream) dimentions. that's why it does not make any sense use wrap_content.
I have an android App with plenty of animations.
When I programmatically create animations (using AnimationDrawable) the non-java object (as appears in DDMS Heap tab) grows with every new animation I load and never shrinks back even after my animations get released.
I have only one reference to each AnimationDrawable object from a wrapper object I wrote and I verified this object gets released by overriding the finalize method and making sure it gets called.
Eventually android stops loading images and prints "out of memory" errors to the log.
The interesting thing is that this happens only in some devices (Motorola Xoom, Sony Experia) and not in others (such as the Galaxy S).
This problem is not specific Honeycomb or pre-Honeycomb as you can see from the device examples I gave.
Some of the things I tried:
Calling recycle on each of the frames after I am done with the current animation but it doesn't seem to help.
Assigning null to the AnimationDrawble object
Making sure that there are no static variable related to the class holding the reference to the animation drawable
Make sure the problem disappears once I comment out myAnimation.addFrame(...)
This isn't an exact answer, but rather a helpful hint to find where the exact leak is occurring. Perform a heap-dump after you expect your memory to be reclaimed and see why the objects you think should be dead are still alive.
Make sure you get the memory analyzer tool for eclipse. (http://www.eclipse.org/mat/)
There could be two possible reason, first at the time of creating the bitmap and second when you are converting the bitmap into the BitmapDrawable. As i can see from your comment (new BitmapDrawable(currentFrameBitmap) now this method is depreciated better to use BitmapDrawable(getResources(),currentFrameBitmap) Without the Resources reference, the bitmap may not render properly, even when scaled correctly. To load bitmap efficiently you can scale it properly.
public class BitmapDecoderHelper {
private Context context;
public BitmapDecoderHelper(Context context){
this.context = context;
}
public int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
Log.d("height reqheight width reqwidth", height+"//"+reqHeight+"//"+width+"///"+reqWidth);
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
public Bitmap decodeSampledBitmapFromResource(String filePath,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
Log.d("options sample size", options.inSampleSize+"///");
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
// out of memory occured easily need to catch and test the things.
return BitmapFactory.decodeFile(filePath, options);
}
public int getPixels(int dimensions){
Resources r = context.getResources();
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dimensions, r.getDisplayMetrics());
return px;
}
public String getFilePath(Uri selectedImage){
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
}