I want to create 2 buttons : when I click to button1 the model1 is initialized and when I click on button2 the model2 is initialized so I created new activity (MainSecond.java) where I created the 2 buttons and send their ids to MainActivity where the 2 models initialized
the problem is when I click on any of the two buttons the 2 models are initialized
this is my code :
MainSecond.java
public class MainSecond extends Activity {
public Button button1;
public Button button2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BackToMain(R.id.button1);
// BackToMain(view);
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BackToMain(R.id.button1);
}
});
}
public void BackToMain(int button_id) {
Intent intent = new Intent(MainSecond.this, MainActivity.class);
intent.putExtra("name",button_id);
intent.putExtra("name",button_id);
startActivity(intent);
}
MainActivity.java
initialization of 2 models
public class InitializeModelAsyncTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... voids) {
final boolean ret = DeeplabModel.initialize();
Logger.debug("initialize deeplab model: %s", ret);
return ret;
}
}
public class InitializeModelAsyncTask2 extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... voids) {
final boolean ret2 = DeeplabModel2.initialize();
Logger.debug("initialize deeplab model: %s", ret2);
return ret2;
}
}
getting buttons ids :
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buckyButton = findViewById(R.id.buckysButton);
// src_img =(ImageView) findViewById(R.id.src_img) ;
Intent mIntent=getIntent();
int intval=mIntent.getIntExtra("buttonid",0);
if(intval==R.id.button1){
initModel();
}
if(intval==R.id.button2){
initModel2();
}
}
private void syncUIWithPermissions(boolean requestIfNeed) {
final boolean granted = checkRequiredPermissions(requestIfNeed);
setPickImageEnabled(granted);
setPickImageEnabled2(granted);
if (granted && !DeeplabModel.isInitialized()) {
initModel();
}
else if (granted && !DeeplabModel2.isInitialized()) {
initModel2();
}
}
private boolean checkRequiredPermissions() {
return checkRequiredPermissions(false);
}
private boolean checkRequiredPermissions(boolean requestIfNeed) {
final boolean writeStoragePermGranted =
ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED;
Logger.debug("storage permission granted: %s", writeStoragePermGranted);
if (!writeStoragePermGranted
&& requestIfNeed) {
requestRequiredPermissions();
}
return writeStoragePermGranted;
}
private void requestRequiredPermissions() {
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
},
REQUEST_REQUIRED_PERMISSION);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
Logger.debug("requestCode = 0x%02x, permission = [%s], grant = [%s]",
requestCode,
ArrayUtils.stringArrayToString(permissions, ","),
ArrayUtils.intArrayToString(grantResults));
if (requestCode == REQUEST_REQUIRED_PERMISSION) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Logger.debug("permission granted, initialize model.");
initModel();
initModel2();
}
the initMode() and intitModel2() functions are :
private void initModel() {
new InitializeModelAsyncTask().execute((Void)null);
}
private void initModel2() {
new InitializeModelAsyncTask2().execute((Void)null);
}
this is the code that is used to show the 2 models on the screen
public class SegmentBitmapsLoader extends AbsAsyncDataLoader<List<SegmentBitmap>> {
private Uri mImageUri;
public SegmentBitmapsLoader(Context context, Uri imageUri) {
super(context);
mImageUri = imageUri;
}
#Nullable
#Override
public List<SegmentBitmap> loadInBackground() {
final Context context = getContext();
if (context == null) {
return null;
}
final Resources res = context.getResources();
if (res == null) {
return null;
}
if (mImageUri == null) {
return null;
}
final String filePath = FilePickUtils.getPath(context, mImageUri);
Logger.debug("file to mask: %s", filePath);
if (TextUtils.isEmpty(filePath)) {
return null;
}
boolean vertical = checkAndReportDimen(filePath);
final int dw = res.getDimensionPixelSize(
vertical ? R.dimen.image_width_v : R.dimen.image_width_h);
final int dh = res.getDimensionPixelSize(
vertical ? R.dimen.image_height_v : R.dimen.image_height_h);
Logger.debug("display image dimen: [%d x %d]", dw, dh);
Bitmap bitmap = decodeBitmapFromFile(filePath, dw, dh);
if (bitmap == null) {
return null;
}
List<SegmentBitmap> bitmaps = new ArrayList<>();
bitmaps.add(new SegmentBitmap(R.string.label_original, bitmap));//important note
final int w = bitmap.getWidth();
final int h = bitmap.getHeight();
Logger.debug("decoded file dimen: [%d x %d]", w, h);
EventBus.getDefault().post(new ImageDimenEvent(mImageUri, w, h));
float resizeRatio = (float) DeeplabModel.INPUT_SIZE / Math.max(bitmap.getWidth(), bitmap.getHeight());
float resizeRatio2 = (float) DeeplabModel2.INPUT_SIZE / Math.max(bitmap.getWidth(), bitmap.getHeight());
int rw = Math.round(w * resizeRatio);
int rh = Math.round(h * resizeRatio);
int rw2 = Math.round(w * resizeRatio2);
int rh2 = Math.round(h * resizeRatio2);
Logger.debug("resize bitmap: ratio = %f, [%d x %d] -> [%d x %d]",
resizeRatio, w, h, rw, rh);
Logger.debug("resize bitmap: ratio = %f, [%d x %d] -> [%d x %d]",
resizeRatio2, w, h, rw2, rh2);
Bitmap resized = ImageUtils.tfResizeBilinear(bitmap, rw, rh);
Bitmap resized2 = ImageUtils.tfResizeBilinear(bitmap, rw2, rh2);
Bitmap mask = DeeplabModel.segment(resized);
Bitmap mask2 = DeeplabModel2.segment(resized2);
if (mask != null) {
mask = BitmapUtils.scaleBitmap(mask, w, h);
bitmaps.add(new SegmentBitmap(R.string.label_mask, mask));
final Bitmap cropped = cropBitmapWithMask(bitmap, mask);
bitmaps.add(new SegmentBitmap(R.string.label_cropped, cropped));
}
else {
bitmaps.add(new SegmentBitmap(R.string.label_mask, (Bitmap) null));
bitmaps.add(new SegmentBitmap(R.string.label_cropped, (Bitmap) null));
}
if(mask2 != null){
mask2 = BitmapUtils.scaleBitmap(mask2, w, h);
bitmaps.add(new SegmentBitmap(R.string.label_mask, mask2));
final Bitmap cropped = cropBitmapWithMask(bitmap, mask2);
bitmaps.add(new SegmentBitmap(R.string.label_cropped, cropped));
}
else {
bitmaps.add(new SegmentBitmap(R.string.label_mask, (Bitmap)null));
bitmaps.add(new SegmentBitmap(R.string.label_cropped, (Bitmap)null));
}
return bitmaps;
}
private boolean checkAndReportDimen(String filePath) {
if (TextUtils.isEmpty(filePath)) {
return false;
}
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
final int width = options.outWidth;
final int height = options.outHeight;
Logger.debug("original image dimen: %d x %d", width, height);
EventBus.getDefault().post(new ImageDimenEvent(mImageUri, width, height));
return (height > width);
}
private Bitmap cropBitmapWithMask(Bitmap original, Bitmap mask) {
if (original == null
|| mask == null) {
return null;
}
final int w = original.getWidth();
final int h = original.getHeight();
if (w <= 0 || h <= 0) {
return null;
}
Bitmap cropped = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(cropped);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
canvas.drawBitmap(original, 0, 0, null);
canvas.drawBitmap(mask, 0, 0, paint);
paint.setXfermode(null);
return cropped;
}
public static Bitmap decodeBitmapFromFile(String filePath,
int reqWidth,
int reqHeight) {
if (TextUtils.isEmpty(filePath)) {
return null;
}
// 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);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
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;
}
}
Well you are sending the same button id for both the buttons...
When you call BacktoMain method for both the buttons you are sending button1 id.
Change the line inside button2.onClickListener from
BackToMain(R.id.button1);
to
BackToMain(R.id.button2);
Do this...
public void BackToMain(int button_id) {
Intent intent = new Intent(MainSecond.this, MainActivity.class);
intent.putExtra("name",button_id);
intent.putExtra("name",button_id); //remove this line y do the same thing twice
startActivity(intent);
}
And...
Intent mIntent=getIntent();
int intval=mIntent.getIntExtra("name",0);
//should give you the button id and returns 0 if
//value for the key "name" was not given
if(intval==R.id.button1){
initModel();
}
if(intval==R.id.button2){
initModel2();
}
Try these changes and lemme know if it works..
Related
I am creating a moving animation for my Card Game, for this i have created a custom surface view, while calling invalidate method inside my Surface View i am getting following exception
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
My code:
Thread Class
class MySurfaceViewThread:BaseThread
{
private MySurfaceView mysurfaceview;
private ISurfaceHolder myThreadSurfaceHolder;
bool running;
public MySurfaceViewThread(ISurfaceHolder paramSurfaceHolder, MySurfaceView paramSurfaceView)
{
mysurfaceview = paramSurfaceView;
myThreadSurfaceHolder = paramSurfaceHolder;
}
public override void RunThread()
{
Canvas c;
while (running)
{
c = null;
try
{
c = myThreadSurfaceHolder.LockCanvas(null);
mysurfaceview.Render(c);
mysurfaceview.PostInvalidate();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
finally
{
if (c != null)
{
myThreadSurfaceHolder.UnlockCanvasAndPost(c);
}
// running = false;
}
}
}
public override void SetRunning(bool paramBoolean)
{
running = paramBoolean;
}
}
Surface View Class
class MySurfaceView : SurfaceView, ISurfaceHolderCallback
{
ISurfaceHolder holder;
MySurfaceViewThread thread;
Context context;
Deck DealtDeck;
DisplayMetrics metrics;
int Screen_Center_X;
int Screen_Center_Y;
int Screen_Width;
int Screen_Height;
int Screen_Top_Middle_X;
int Screen_Top_Middle_Y;
int Screen_Bottom_Middle_X;
int Screen_Bottom_Middle_Y;
float density;
int Card_Width;
int Card_Height;
int Down_Card_Gap;
Deck DiscardedDeck;
Deck MainPlayer;
int localdownanimationvalue=0;
Bitmap localimage;
Bitmap rotatedimage;
Cards localcard;
public MySurfaceView(Context context):base(context)
{
this.context = context;
metrics = Resources.DisplayMetrics;
SetWillNotDraw(false);
Init();
}
public MySurfaceView(Context context, IAttributeSet attrs):base(context, attrs)
{
this.context=context;
metrics = Resources.DisplayMetrics;
SetWillNotDraw(false);
Init();
}
private void Init()
{
Console.WriteLine("Init method start");
// SurfaceView surfaceview = this;
holder = Holder;
holder.AddCallback(this);
this.thread = new MySurfaceViewThread(holder,this);
Focusable=true;
}
public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
{
//throw new NotImplementedException();
}
public void SurfaceCreated(ISurfaceHolder holder)
{
this.thread.SetRunning(true);
this.thread.Start();
Initializevariable();
AllocatedCardList();
SetWillNotDraw(false);
}
private void Initializevariable()
{
Screen_Width = metrics.WidthPixels;
Screen_Height = metrics.HeightPixels;
density = metrics.Density;
Card_Width = (int)(125.0F * density);
Card_Height = (int)(93.0F * density);
Screen_Center_X = Screen_Width / 2;
Screen_Center_Y = Screen_Height / 2;
Screen_Top_Middle_X = Screen_Center_X - Card_Width;
Screen_Top_Middle_Y = Screen_Center_Y - Card_Height;
Screen_Bottom_Middle_X = Screen_Center_X - Card_Width/2;
Screen_Bottom_Middle_Y = Screen_Height - Card_Height;
DealtDeck = new Deck();
MainPlayer = new Deck();
// FaceDownDeck = new Deck(Screen_Center_X - Card_Width/2, Screen_Center_Y- Card_Height/2);
}
public void SurfaceDestroyed(ISurfaceHolder holder)
{
bool retry = true;
this.thread.SetRunning(false);
while(retry)
{
thread.Join();
retry = false;
}
}
void AllocatedCardList()
{
Cards localcard;
//Allocate all cards to dealtdeck first
for (int i = 1; i <= 13; i++)
{
for (int j = 1; j <= 4; j++)
{
DealtDeck.Add(new Cards((Cards.Rank)i, (Cards.SuitType)j, true, (Screen_Center_X - Card_Width / 2), (Screen_Center_Y - Card_Height / 2)));
}
}
//Allocate to bottom player starting card should be bottom-center
localcard = DealtDeck.RemoveCard();
localcard.current_X = Screen_Bottom_Middle_X;
localcard.current_Y = Screen_Bottom_Middle_Y;
MainPlayer.Add(localcard);
}
public void Render(Canvas paramCanvas)
{
try
{
//
localcard = DealtDeck.getCard();
if (localdownanimationvalue <= Screen_Height)
{
paramCanvas.DrawColor(Android.Graphics.Color.Transparent, PorterDuff.Mode.Clear);
localimage = DecodeSampledBitmapFromResource(Resources, localcard.GetImageId(context), Card_Width, Card_Height);
rotatedimage = RotateBitmap(localimage, 180);
paramCanvas.DrawBitmap(rotatedimage, Screen_Center_X, localdownanimationvalue, null);
Updatedowncardvalue();
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
protected override void OnDraw(Canvas paramCanvas)
{
}
private void Updatedowncardvalue()
{
const int updatevalue = 50;
if (localdownanimationvalue + updatevalue > Screen_Height)
localdownanimationvalue = Screen_Height;
else
localdownanimationvalue = localdownanimationvalue + updatevalue;
Invalidate();
}
private Bitmap DecodeSampledBitmapFromResource(Resources resources, int cardid, int card_Width, int card_Height)
{
BitmapFactory.Options options = new BitmapFactory.Options
{
InJustDecodeBounds = true
};
Bitmap image = BitmapFactory.DecodeResource(resources, cardid,options);
options.InSampleSize = CalculateInSampleSize(options, card_Width, card_Height);
options.InJustDecodeBounds = false;
return BitmapFactory.DecodeResource(resources, cardid, options);
}
private int CalculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
{
// Raw height and width of image
int width = options.OutWidth;
int height = options.OutHeight;
int samplesize = 1;
if(height > reqHeight || width > reqWidth)
{
// Calculate ratios of height and width to requested height and width
int heightratio = (int)Math.Round((double)height / reqHeight);
int widthratio = (int)Math.Round((double)width / reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
samplesize = heightratio < widthratio ? widthratio : heightratio;
}
return samplesize;
}
private Bitmap RotateBitmap(Bitmap localimage, float angle)
{
Matrix matrix = new Matrix();
matrix.PostRotate(angle);
Bitmap resized= Bitmap.CreateBitmap(localimage, 0, 0, localimage.Width, localimage.Height, matrix, true);
localimage.Recycle();
return resized;
}
}
Stacktrace:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6462)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:932)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:4692)
at android.view.View.invalidateInternal(View.java:11806)
at android.view.View.invalidate(View.java:11770)
at android.view.View.invalidate(View.java:11754)
Only the original thread that created a view hierarchy can touch its views.
You need to use RunOnUiThread from within your thread code whenever you update your views:
RunOnUiThread (() => {
someView.SomeProperty = "SO";
});
re: https://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)
I created two activities (MainSecond.java) which contents my 2 buttons and (SegmentBitmapsLoader.java)that contents my segmentation model what I want to make is : when I click on button1 it sends button id to (SegmentBitmapsLoader.java) and then initialize model1 and the same thing with button2 and model2 the problem is : when I tried to use getIntent().getStringExtra(); in the (SegmentBitmapsLoader.java) it gives me error because this class doesn't extend Activity what should I do ?
(MainSecond.java)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BackToMain2(view);
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BackToMain2(view);
}
});
}
public void BackToMain2(View view) {
Intent intent2 = new Intent(MainSecond.this, SegmentBitmapsLoader.class);
intent2.putExtra("name","button1");
intent2.putExtra("name","button2");
startActivity(intent2);
}
}
SegmentBitmapsLoader.java
public class SegmentBitmapsLoader extends AbsAsyncDataLoader<List<SegmentBitmap>> {
private Uri mImageUri;
public SegmentBitmapsLoader(Context context, Uri imageUri) {
super(context);
mImageUri = imageUri;
}
#Nullable
#Override
public List<SegmentBitmap> loadInBackground() {
final Context context = getContext();
if (context == null) {
return null;
}
final Resources res = context.getResources();
if (res == null) {
return null;
}
if (mImageUri == null) {
return null;
}
final String filePath = FilePickUtils.getPath(context, mImageUri);
Logger.debug("file to mask: %s", filePath);
if (TextUtils.isEmpty(filePath)) {
return null;
}
boolean vertical = checkAndReportDimen(filePath);
final int dw = res.getDimensionPixelSize(
vertical ? R.dimen.image_width_v : R.dimen.image_width_h);
final int dh = res.getDimensionPixelSize(
vertical ? R.dimen.image_height_v : R.dimen.image_height_h);
Logger.debug("display image dimen: [%d x %d]", dw, dh);
Bitmap bitmap = decodeBitmapFromFile(filePath, dw, dh);
if (bitmap == null) {
return null;
}
List<SegmentBitmap> bitmaps = new ArrayList<>();
bitmaps.add(new SegmentBitmap(R.string.label_original, bitmap));//important note
final int w = bitmap.getWidth();
final int h = bitmap.getHeight();
Logger.debug("decoded file dimen: [%d x %d]", w, h);
EventBus.getDefault().post(new ImageDimenEvent(mImageUri, w, h));
float resizeRatio = (float) DeeplabModel.INPUT_SIZE / Math.max(bitmap.getWidth(), bitmap.getHeight());
float resizeRatio2 = (float) DeeplabModel2.INPUT_SIZE / Math.max(bitmap.getWidth(), bitmap.getHeight());
int rw = Math.round(w * resizeRatio);
int rh = Math.round(h * resizeRatio);
int rw2 = Math.round(w * resizeRatio2);
int rh2 = Math.round(h * resizeRatio2);
Logger.debug("resize bitmap: ratio = %f, [%d x %d] -> [%d x %d]",
resizeRatio, w, h, rw, rh);
Logger.debug("resize bitmap: ratio = %f, [%d x %d] -> [%d x %d]",
resizeRatio2, w, h, rw2, rh2);
Bitmap resized = ImageUtils.tfResizeBilinear(bitmap, rw, rh);
Bitmap resized2 = ImageUtils.tfResizeBilinear(bitmap, rw2, rh2);
Bitmap mask = DeeplabModel.segment(resized);
Bitmap mask2 = DeeplabModel2.segment(resized2);
if (mask != null) {
mask = BitmapUtils.scaleBitmap(mask, w, h);
bitmaps.add(new SegmentBitmap(R.string.label_mask, mask));
final Bitmap cropped = cropBitmapWithMask(bitmap, mask);
bitmaps.add(new SegmentBitmap(R.string.label_cropped, cropped));
} else {
bitmaps.add(new SegmentBitmap(R.string.label_mask, (Bitmap) null));
bitmaps.add(new SegmentBitmap(R.string.label_cropped, (Bitmap) null));
}
if(mask2 != null){
mask2 = BitmapUtils.scaleBitmap(mask2, w, h);
bitmaps.add(new SegmentBitmap(R.string.label_mask, mask2));
final Bitmap cropped = cropBitmapWithMask(bitmap, mask2);
bitmaps.add(new SegmentBitmap(R.string.label_cropped, cropped));
}else {
bitmaps.add(new SegmentBitmap(R.string.label_mask, (Bitmap)null));
bitmaps.add(new SegmentBitmap(R.string.label_cropped, (Bitmap)null));
}
return bitmaps;
}
private boolean checkAndReportDimen(String filePath) {
if (TextUtils.isEmpty(filePath)) {
return false;
}
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
final int width = options.outWidth;
final int height = options.outHeight;
Logger.debug("original image dimen: %d x %d", width, height);
EventBus.getDefault().post(new ImageDimenEvent(mImageUri, width, height));
return (height > width);
}
private Bitmap cropBitmapWithMask(Bitmap original, Bitmap mask) {
if (original == null
|| mask == null) {
return null;
}
final int w = original.getWidth();
final int h = original.getHeight();
if (w <= 0 || h <= 0) {
return null;
}
Bitmap cropped = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(cropped);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
canvas.drawBitmap(original, 0, 0, null);
canvas.drawBitmap(mask, 0, 0, paint);
paint.setXfermode(null);
return cropped;
}
public static Bitmap decodeBitmapFromFile(String filePath,
int reqWidth,
int reqHeight) {
if (TextUtils.isEmpty(filePath)) {
return null;
}
// 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);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
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;
}
}
You are not sending the button id, if you want to do so, you have to change your method to this :
private void backToMain2(int button_id) {
Intent intent2 = new Intent(MainSecond.this, SegmentBitmapsLoader.class);
intent2.putExtra("button_id",button_id);
startActivity(intent2);
}
And when you click to button do this :
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
backToMain2(R.id.button1);
}
});
But I do now know why you are doing startActivity(), SegmentBitMapsLoader it's not an Activity and startActivity() as documentatio says :
Launch a new activity. You will not receive any information about when the activity exits. This implementation overrides the base version, providing information about the activity performing the launch. Because of this additional information, the Intent.FLAG_ACTIVITY_NEW_TASK launch flag is not required; if not specified, the new activity will be added to the task of the caller.
You have to think other way to comunicate your MainSecond Activity to that SegmentBitmapsLoader.class.
when I tried to use getIntent().getStringExtra(); in the (SegmentBitmapsLoader.java) it gives me error because this class doesn't extend Activity what should I do ?
You could add on its constructor the button id of Button clicked, so you can do stuff with that, for example you could so something like :
SegmentBitmapsLoader segmentBitmapsLoader = new SegmentBitmapsLoader(this,YOUR_URI,YOUR_BUTTON_ID);
And then doing segmentBitmapsLoader. you can acces to its methods.
Your questions is quite unclear, so I tried my best to understand your problem and try to guide you.
the gridview in the below code still does not hold images in memory and load them using the LRUCache once the user scrolls. The view still gets recycled.
I am following best practices like using AsyncTask and ViewHolder from the Google Docs. Also, loading about 400 high quality pictures is still taking about 10 seconds before the first image is shown. What can I do to fix the recycling issue and speed the loading of the high-res images up?
public class CustomGridOfFilesEXIFDataAdapter extends ArrayAdapter<EXIFDataMarkerHolder> {
private LayoutInflater layoutInflater;
public int position;
private LruCache<String, Bitmap> mMemoryCache;
ArrayList<Uri> imageList;
//http://www.coderzheaven.com/2013/09/01/faster-loading-images-gridviews-listviews-android-menory-caching-complete-implemenation-sample-code/
public CustomGridOfFilesEXIFDataAdapter(Context context, ArrayList<EXIFDataMarkerHolder> listOfFiles) {
super(context, 0, listOfFiles);
layoutInflater = LayoutInflater.from(context);
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in bytes rather than number
// of items.
return bitmap.getByteCount();
}
};
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderItems viewHolder;
EXIFDataMarkerHolder fileExifData = getItem(position);
if(convertView==null){
convertView = layoutInflater.inflate(R.layout.maps_image_grid_single, null);
viewHolder = new ViewHolderItems();
viewHolder.vhImage = (ImageView) convertView.findViewById(R.id.img);
viewHolder.vhImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
viewHolder.position = position;
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolderItems) convertView.getTag();
}
if (viewHolder.vhImage != null) {
final String imageKey = fileExifData.filepath;
final Bitmap bm = getBitmapFromMemCache(imageKey);
if (bm == null) {
if (cancelPotentialDownload(fileExifData.filepath, viewHolder.vhImage)) {
ImageConfiguratorAsyncTask task = new ImageConfiguratorAsyncTask(viewHolder.vhImage);
DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task);
viewHolder.vhImage.setImageDrawable(downloadedDrawable);
task.execute(fileExifData.filepath);
}
}
}
return convertView;
}
static class ViewHolderItems {
ImageView vhImage;
int position;
}
//region "Async File Retrieval"
class ImageConfiguratorAsyncTask extends AsyncTask<String, ViewHolderItems, Bitmap> {
private String filepath;
private final WeakReference<ImageView> imageViewReference;
public ImageConfiguratorAsyncTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... params) {
Bitmap b = downloadBitmap(params[0]);
addBitmapToMemoryCache(String.valueOf(params[0]), b);
return b;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
ImageConfiguratorAsyncTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);
if (this == bitmapDownloaderTask) {
imageView.setImageBitmap(bitmap);
}
}
}
private Bitmap downloadBitmap(String filepath) {
try {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filepath, options);
options.inSampleSize = ImageManipulation.calculateInSampleSize(options, 125, 125);
options.inJustDecodeBounds = false;
Bitmap scaledDownFile = BitmapFactory.decodeFile(filepath, options);
scaledDownFile = Bitmap.createScaledBitmap(scaledDownFile, 125, 125, true);
//scaledDownFile = ImageManipulation.decodeBitmapFromFile(filepath, 50, 50);
return scaledDownFile;
} catch (Exception e) {
} finally {
}
return null;
}
}
static class DownloadedDrawable extends ColorDrawable {
private final WeakReference<ImageConfiguratorAsyncTask> bitmapDownloaderTaskReference;
public DownloadedDrawable(ImageConfiguratorAsyncTask bitmapDownloaderTask) {
super(Color.WHITE);
bitmapDownloaderTaskReference =
new WeakReference<ImageConfiguratorAsyncTask>(bitmapDownloaderTask);
}
public ImageConfiguratorAsyncTask getBitmapDownloaderTask() {
return bitmapDownloaderTaskReference.get();
}
}
private static boolean cancelPotentialDownload(String url, ImageView imageView) {
ImageConfiguratorAsyncTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);
if (bitmapDownloaderTask != null) {
String bitmapUrl = bitmapDownloaderTask.filepath;
if ((bitmapUrl == null) || (!bitmapUrl.equals(url))) {
bitmapDownloaderTask.cancel(true);
} else {
// The same URL is already being downloaded.
return false;
}
}
return true;
}
private static ImageConfiguratorAsyncTask getBitmapDownloaderTask(ImageView imageView) {
if (imageView != null) {
Drawable drawable = imageView.getDrawable();
if (drawable instanceof DownloadedDrawable) {
DownloadedDrawable downloadedDrawable = (DownloadedDrawable)drawable;
return downloadedDrawable.getBitmapDownloaderTask();
}
}
return null;
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
return (Bitmap) mMemoryCache.get(key);
}
//endregion
}
public class ImageManipulation {
public static Bitmap decodeBitmapFromFile(String filepath, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filepath, options);
// Calculate inSampleSize
options.inSampleSize = ImageManipulation.calculateInSampleSize(options, 20, 20);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap scaledDownFile = BitmapFactory.decodeFile(filepath, options);
scaledDownFile = ImageManipulation.getResizedBitmap(scaledDownFile, 100);
return scaledDownFile;
}
public static Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float)width / (float) height;
if (bitmapRatio > 0) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
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;
}
}
I'm creating a dynamic button to capture photo from android. The dynamic button is located in a different class from main activity. I got Can't resolve error on my startActivityForResult here is my code
I'll appreciate any help. Thank you.
Try this way,hope this will help you to solve your problem.
Keep mind custom class can not override onActivityResult() only Activity extended class override onActivityResult() so you have to override onActivityResult() in your Actitvity and given call back to your custom class like below
public class MainActivity extends Activity {
private JsonGuiImageView jsonGuiImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
jsonGuiImageView = new JsonGuiImageView(this);
setContentView(jsonGuiImageView);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == jsonGuiImageView.CAMERA_REQUEST && resultCode == Activity.RESULT_OK){
jsonGuiImageView.setPhoto();
}
}
}
public class JsonGuiImageView extends LinearLayout {
private ImageView imageView;
private ImageButton button;
private Intent cameraIntent;
private Bitmap photo;
private Context context;
public static int CAMERA_REQUEST = 1777;
private String imagePath;
public JsonGuiImageView(Context context){
super(context);
this.context = context;
this.setOrientation(VERTICAL);
this.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
this.setGravity(Gravity.CENTER);
button = new ImageButton(this.context);
button.setLayoutParams(new ViewGroup.LayoutParams(60, 60));
button.setImageResource(R.drawable.ic_launcher);
button.setMaxHeight(60);
button.setMinimumHeight(60);
button.setMaxWidth(60);
button.setMinimumWidth(60);
button.setOnClickListener(AddImage);
this.addView(button);
}
public JsonGuiImageView(Context context, AttributeSet attributeSet){
super(context, attributeSet);
}
OnClickListener AddImage = new OnClickListener() {
#Override
public void onClick(View view) {
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
imagePath = file.getAbsolutePath();
cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(file));
if (cameraIntent.resolveActivity(((Activity)context).getPackageManager()) != null) {
((Activity)context).startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
};
public void setPhoto(){
photo = decodeSampledBitmapFromFile(imagePath, 480, 640);
imageView = new ImageView(getContext());
imageView.setMaxHeight(60);
imageView.setMinimumHeight(60);
imageView.setMaxWidth(60);
imageView.setMinimumWidth(60);
imageView.setImageBitmap(photo);
this.addView(imageView);
}
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{
Bitmap decode, rotatedBitmap = null;
//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 = 8;
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;
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
try{
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotation = 0;
switch (orientation){
case ExifInterface.ORIENTATION_ROTATE_90 :
rotation = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180 :
rotation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270 :
rotation = 270;
break;
default: break;
}
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
decode = BitmapFactory.decodeFile(path, options);
rotatedBitmap = Bitmap.createBitmap(decode, 0, 0, decode.getWidth(), decode.getHeight(), matrix, true);
} catch (IOException e){
e.printStackTrace();
}
return rotatedBitmap;
}
}
I am needing some help with resizing a bitmap before sending it to the wallpaper manager so that when the user sets it as their wallpaper, it fits reasonably, 100% would be preferred.
I am using wallpaper manager and am getting the image from an ImageView.
The issue I am having is the wallpaper is really zoomed in. Before, when I set the wallpaper straight from the drawable directory, it looked fine and you could see a lot more of the image, not 1/4 of it. I have changed my code up since then and have found a lot more of an effective way to get my images and set the wallpaper.
I have looked at This link here and am trying to figure out how to implement the answer that shows you how to resize the image before sending it to the wallpaper manager.
Any help would be appreciated, cheers.
Relative code to question:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.image_detail_fragment,
container, false);
int Measuredwidth = 0;
int Measuredheight = 0;
WindowManager w = getActivity().getWindowManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
w.getDefaultDisplay().getSize(Size);
Measuredwidth = Size.x;
Measuredheight = Size.y;
} else {
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
mImageView = (RecyclingImageView) v.findViewById(R.id.imageView);
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
BitmapDrawable drawable = (BitmapDrawable) mImageView
.getDrawable();
Bitmap bitmap = drawable.getBitmap();
WallpaperManager myWallpaperManager = WallpaperManager
.getInstance(getActivity());
try {
myWallpaperManager.setBitmap(bitmap);
;
Toast.makeText(getActivity(),
"Wallpaper Successfully Set!", Toast.LENGTH_LONG)
.show();
} catch (IOException e) {
Toast.makeText(getActivity(), "Error Setting Wallpaper",
Toast.LENGTH_LONG).show();
}
}
My whole class:
public class ImageDetailFragment extends Fragment {
private static final String IMAGE_DATA_EXTRA = "extra_image_data";
private static final Point Size = null;
private String mImageUrl;
private RecyclingImageView mImageView;
private ImageFetcher mImageFetcher;
public static ImageDetailFragment newInstance(String imageUrl) {
final ImageDetailFragment f = new ImageDetailFragment();
final Bundle args = new Bundle();
args.putString(IMAGE_DATA_EXTRA, imageUrl);
f.setArguments(args);
return f;
}
public ImageDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mImageUrl = getArguments() != null ? getArguments().getString(
IMAGE_DATA_EXTRA) : null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.image_detail_fragment,
container, false);
int Measuredwidth = 0;
int Measuredheight = 0;
WindowManager w = getActivity().getWindowManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
w.getDefaultDisplay().getSize(Size);
Measuredwidth = Size.x;
Measuredheight = Size.y;
} else {
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
mImageView = (RecyclingImageView) v.findViewById(R.id.imageView);
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
BitmapDrawable drawable = (BitmapDrawable) mImageView
.getDrawable();
Bitmap bitmap = drawable.getBitmap();
WallpaperManager myWallpaperManager = WallpaperManager
.getInstance(getActivity());
try {
myWallpaperManager.setBitmap(bitmap);
;
Toast.makeText(getActivity(),
"Wallpaper Successfully Set!", Toast.LENGTH_LONG)
.show();
} catch (IOException e) {
Toast.makeText(getActivity(), "Error Setting Wallpaper",
Toast.LENGTH_LONG).show();
}
}
});
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (Batmanark.class.isInstance(getActivity())) {
mImageFetcher = ((Batmanark) getActivity()).getImageFetcher();
mImageFetcher.loadImage(mImageUrl, mImageView);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mImageView != null) {
// Cancel any pending image work
ImageWorker.cancelWork(mImageView);
mImageView.setImageDrawable(null);
}
}
}
if you want to fit the wallpaper with the divice screen, then you have to follow the steps bellow:
get the height and width of the divice screen
sample the bitmap image
resize the bitmap
before setting the bitmap as wallpaper, recycle the previous bitmap
code:
step 1:
int Measuredwidth = 0;
int Measuredheight = 0;
Point size = new Point();
// if you are doing it from an activity
WindowManager w = getWindowManager();
// otherwise use this
WindowManager w = context.getWindowManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
w.getDefaultDisplay().getSize(size);
Measuredwidth = size.x;
Measuredheight = size.y;
} else {
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
step 2+3:
public Bitmap resizeBitmap(Resources res, int reqWidth, int reqHeight,
InputStream inputStream, int fileLength) {
Bitmap bitmap = null;
InputStream in = null;
InputStream in2 = null;
InputStream in3 = null;
try {
in3 = inputStream;
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream out2 = new ByteArrayOutputStream();
copy(in3,out,fileLength);
out2 = out;
in2 = new ByteArrayInputStream(out.toByteArray());
in = new ByteArrayInputStream(out2.toByteArray());
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, options);
if(options.outHeight == -1 || options.outWidth == 1 || options.outMimeType == null){
return null;
}
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeStream(in2, null, options);
if(bitmap != null){
bitmap = Bitmap.createScaledBitmap(bitmap, reqWidth, reqHeight, false);
}
in.close();
in2.close();
in3.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
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;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee a final image
// with both dimensions larger than or equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
public int copy(InputStream input, OutputStream output, int fileLength) throws IOException{
byte[] buffer = new byte[8*1024];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
publishProgress((int) (count * 100 / fileLength));
}
return count;
}
step 4:
to recycle the bitmap use:
bitmap.recycle();
bitmap = null;
call the function like resizeBitmap(context.getResources(), Measuredwidth, Measuredheight,
THE_INPUTSTREAM_FROM_WHERE_YOU_ARE_DOWNLOADING_THE_IMAGE,
FILELENGTH_FROM_THE_INPUTSTREAM);.
if you are calling the function from an activity the call it like: resizeBitmap(getResources(), Measuredwidth, Measuredheight,
THE_INPUTSTREAM_FROM_WHERE_YOU_ARE_DOWNLOADING_THE_IMAGE, FILELENGTH_FROM_THE_INPUTSTREAM);
the function will return resized bitmap which will fit with the divice resulation.
if you have already setted a bitmap as wallpaper, then don't forget to recycle the bitmap before you set a new bitmap as wallpaper.
Please see the function and change the size according to your need. Thanks
public Bitmap createScaledImage(Bitmap bit) {
Bitmap bitmapOrg = bit;
int width = bitmapOrg.getWidth();
int height = bitmapOrg.getHeight();
int newWidth = 0, newHeight = 0;
if (MyDevice.getInstance().getDeviceSize().equals("XLARGE")) {
MyDevice.getInstance().SCALE = 65;
newWidth = 65;
newHeight = 65;
} else if (MyDevice.getInstance().getDeviceSize().equals("LARGE")) {
MyDevice.getInstance().SCALE = 60;
newWidth = 60;
newHeight = 60;
}
else if (MyDevice.getInstance().getDeviceSize().equals("NORMAL")) {
MyDevice.getInstance().SCALE = 50;
newWidth = 50;
newHeight = 50;
if (h > 800) {
MyDevice.getInstance().SCALE = 60;
newWidth = 60;
newHeight = 60;
}
} else if (MyDevice.getInstance().getDeviceSize().equals("SMALL")) {
MyDevice.getInstance().SCALE = 30;
newWidth = 30;
newHeight = 30;
}
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width,
height, matrix, true);
return resizedBitmap;
}
Where MyDevice is a singleton class here. You can change it as you want. getdevicesize method determines what device it is.