I used camera intent for user to capture photo and send it to another Activity for further use. I included EXTRA_OUTPUT part in putExtra method of camera intent, so that I can get full sized image and not thumbnail. The problem is, after capturing image,I am redirected to MainActivity. When I saw in File Manager, I found that the image was saved. Please help.
CameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = timeStamp + ".jpg";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
pictureImagePath = storageDir.getAbsolutePath() + "/" + imageFileName;
file = new File(pictureImagePath);
outputFileUri = Uri.fromFile(file);
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camera.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(camera, REQUEST_IMAGE_CAPTURE);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK && null != data) {
try {
b = MediaStore.Images.Media.getBitmap(this.getContentResolver(), outputFileUri);
String filename123 = "myphoto.jpg";
FileOutputStream out = this.openFileOutput(filename123, Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.close();
b.recycle();
Intent in1 = new Intent(this, ongallery.class);
in1.putExtra("picture", filename123);
startActivity(in1);
}catch(Exception e)
{
Toast.makeText(this,"You got Error!",Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
Toast.makeText(this,"Something went wrong",Toast.LENGTH_SHORT).show();
}
}
//OnaGallery.java
public class ongallery extends Activity {
public ImageView imgView;
int xDim;
int yDim;
String filename;
public Bitmap finale = null ;
public Bitmap bmp = null;
public Bitmap photoEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ongallery);
imgView = (ImageView) findViewById(R.id.imgView);
xDim = imgView.getWidth();
filename = getIntent().getStringExtra("picture");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
Bitmap finalPhoto = decoder(filename,400,400);
imgView.setImageBitmap(finalPhoto);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
}
public Bitmap decoder(String filename, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
String filepath = getFileStreamPath(filename).getPath();
BitmapFactory.decodeFile(filepath, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
finale = BitmapFactory.decodeFile(filepath, options);
return finale;
}
int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight) {
int inSampleSize = 1;
if (options.outHeight > reqHeight || options.outWidth > reqWidth) {
final int halfHeight = options.outHeight / 2;
final int halfWidth = options.outWidth / 2;
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
Class for permission camera permission check
public class Utility {
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission(final Context context)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>=android.os.Build.VERSION_CODES.N)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
}
Now check permission before you fire camera intent
boolean permissionCheck = Utility.checkPermission(getActivity());
if (permissionCheck) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
Now in onActivityResult() look like
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST)
bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
bitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, false);
// Toast.makeText(SignUpActivity.this, String.valueOf(destination), Toast.LENGTH_LONG).show();
imageView.setImageBitmap(bitmap);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getActivity(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
}
Permission in AndroidMenifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Hope this will help you.
If you are running your code on android>=6 you need to give permissions to your app from your device before running it and after installation ? Have you done that ? This can be done from the app info/settings menu.
Go to settings -> Apps ->(Select your app) -> Permissions -> (enable all the permissions)
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
How can I fix my app crash after take a photo in android, I am currently making an application to report to the streets via photos, but I have a problem when the user has taken a picture through the camera, when I press the application button to crash, the following reports of crashes that occur
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.dbothxrpsc119.soppeng/com.dbothxrpsc119.soppeng.LaporanActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4332)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4376)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1670)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6635)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
at com.dbothxrpsc119.soppeng.LaporanActivity.setPic(LaporanActivity.java:262)
at com.dbothxrpsc119.soppeng.LaporanActivity.onCaptureImageResult(LaporanActivity.java:271)
at com.dbothxrpsc119.soppeng.LaporanActivity.onActivityResult(LaporanActivity.java:206)
at android.app.Activity.dispatchActivityResult(Activity.java:7351)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4328)
... 9 more
for the reportactivity code snippet as follows
public class LaporanActivity extends AppCompatActivity {
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private EditText edPesanKirim;
private Button btnUpload;
private ImageView ivImage;
private String userChoosenTask;
String mCurrentPhotoPath;
Uri photoURI;
public static final String UPLOAD_KEY = "image";
public static final String TAG = "Laporan";
private Bitmap bitmap;
private SQLiteDatabase db;
private Cursor c;
String pesan,nama,ktpsim,alamat,hp;
Boolean sudahUpload = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_laporan);
db=openOrCreateDatabase("User", Context.MODE_PRIVATE, null);
ivImage = (ImageView) findViewById(R.id.ivImage);
btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
edPesanKirim = (EditText) findViewById(R.id.edPesanKirim);
btnUpload = (Button) findViewById(R.id.btnUpload);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//check jika data belum lengkap
c = db.rawQuery("SELECT * FROM users",null);
boolean exists = (c.getCount() > 0);
if(exists) {
c.moveToFirst();
pesan = edPesanKirim.getText().toString();
nama = c.getString(1);
ktpsim = c.getString(2);
alamat = c.getString(3);
hp = c.getString(4);
if (!c.getString(0).equals("") || !c.getString(1).equals("") || c.getString(2).equals("")
|| c.getString(3).equals("") || c.getString(4).equals("")) {
if (!pesan.equals("")) {
if (sudahUpload.equals(true)) {
uploadImage("gambar");
} else {
uploadImage("pesan");
}
} else {
Toast.makeText(LaporanActivity.this,"Silahkan isi gambar dan pesan terlebih dahulu",Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LaporanActivity.this,"Silahkan Lengkapi Profil user anda terlebih dahulu",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LaporanActivity.this, ProfileDataActivity.class);
startActivity(intent);
}
} else {
Toast.makeText(LaporanActivity.this,"Silahkan Lengkapi Profil user anda terlebih dahulu",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LaporanActivity.this, ProfileDataActivity.class);
startActivity(intent);
}
c.close();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Ambil Photo"))
cameraIntent();
else if(userChoosenTask.equals("Pilih dari Galery"))
galleryIntent();
} else {
//code for deny
}
break;
}
}
private void selectImage() {
final CharSequence[] items = { "Ambil Photo", "Pilih dari Galery", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(LaporanActivity.this);
builder.setTitle("Tambah Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(LaporanActivity.this);
if (items[item].equals("Ambil Photo")) {
userChoosenTask ="Ambil Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Pilih dari Galery")) {
userChoosenTask ="Pilih dari Galery";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Pilih File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (intent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
photoFile.delete();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d("Photo",ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.dbothxrpsc119.soppeng.fileprovider",
photoFile);
startActivityForResult(intent, REQUEST_CAMERA);
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA) {
onCaptureImageResult();
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "DebotHaxor_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
//mCurrentPhotoPath = "file:" + image.getAbsolutePath();
mCurrentPhotoPath = image.getAbsolutePath();
//mCurrentPhotoPath = image;
return image;
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = photoURI;
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private void setPic() {
// Get the dimensions of the View
int targetW = ivImage.getWidth();
int targetH = ivImage.getHeight();
//Log.d("Photo","Set Pic "+mCurrentPhotoPath);
Bitmap real_bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap_view = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
ivImage.setImageBitmap(bitmap_view);
Log.d("Photo","Tampilkan Foto "+ mCurrentPhotoPath);
//resize
Bitmap resized;
resized = Bitmap.createScaledBitmap(bitmap_view,(int)(real_bitmap.getWidth()*0.4), (int)(real_bitmap.getHeight()*0.4), true);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
resized.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
bitmap = resized;
}
private void onCaptureImageResult() {
galleryAddPic();
setPic();
sudahUpload = true;
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
ivImage.setImageBitmap(bm);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
bitmap = bm;
sudahUpload = true;
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage(String mode){
class UploadImage extends AsyncTask<Bitmap,Void,String> {
ProgressDialog loading;
RequestHandler rh = new RequestHandler();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(LaporanActivity.this, "Kirim Pesan", "Mohon tunggu...",true,true);
loading.setCanceledOnTouchOutside(false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
String msg = "";
if (s.equals("ok")) {
msg = "Pesan sukses terkirim";
clearForm();
} else {
msg = getString(R.string.api_error);
}
Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Bitmap... params) {
HashMap<String,String> data = new HashMap<>();
if (params.length > 0) {
Bitmap bitmap = params[0];
String uploadImage = getStringImage(bitmap);
data.put(UPLOAD_KEY, uploadImage);
}
data.put("pesan", pesan);
data.put("device_id", Utility.uniqDevice(LaporanActivity.this));
String uri = "https://"+ getString(R.string.api_url) + "/path/kirim_pesan";
String result = rh.sendPostRequest(uri,data);
return result;
}
}
UploadImage ui = new UploadImage();
if (mode.equals("gambar"))
ui.execute(bitmap);
else
ui.execute();
}
private void clearForm() {
ivImage.setImageResource(R.drawable.ic_menu_gallery);
edPesanKirim.setText("");
btnSelect.setFocusable(true);
}
}
I believe that the problem is that you create uri for a file to store photo but didn't put it in intent. Please, try following:
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.dbothxrpsc119.soppeng.fileprovider",
photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(intent, REQUEST_CAMERA);
}
I want to make the input image to grayscale . there is some error . can you help me?
public class signindua extends AppCompatActivity {
int REQUEST_CAMERA = 0, SELECT_FILE = 1;
Button btnSelect;
ImageView imageView;
Bitmap bmNormal, bmGrayScale, bm, bitmap_Source;
// ImageView ivImage;
//layout dari button sebelumnya//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signindua);
btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
imageView = (ImageView) findViewById(R.id.imageView);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(signindua.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imageView.setImageBitmap(thumbnail);
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
CursorLoader cursorLoader = new CursorLoader(this, selectedImageUri, projection, null, null,
null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
imageView.setImageBitmap(bm);
}
}
}
//-------don't know-----//
/*
bitmap_Source = BitmapFactory.decodeResource(getResources(), R.drawable.kamera);
imageView.setImageBitmap(getGrayscale_ColorMatrixColorFilter(bitmap_Source));
*/
private Bitmap selectedImagePath (Bitmap src){
int width = src.getWidth();
int height = src.getHeight();
Bitmap dest = Bitmap.createBitmap(width, height,
Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(dest);
Paint paint = new Paint();
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(0); //value of 0 maps the color to gray-scale
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrix);
paint.setColorFilter(filter);
canvas.drawBitmap(src, 0, 0, paint);
return dest;
}
}
I asked a question a couple of days ago that I'm building an app that converts multiple photos from gallery or camera to convert them to a gif file. Someone replied with the following code:
// For multiple images
Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);
startActivityForResult(i, 200);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
adapter.clear();
viewSwitcher.setDisplayedChild(1);
String single_path = data.getStringExtra("single_path");
imageLoader.displayImage("file://" + single_path, imgSinglePick);
} else if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
String[] all_path = data.getStringArrayExtra("all_path");
ArrayList<CustomGallery> dataT = new ArrayList<CustomGallery>();
for (String string : all_path) {
CustomGallery item = new CustomGallery();
item.sdcardPath = string;
dataT.add(item);
}
viewSwitcher.setDisplayedChild(0);
adapter.addAll(dataT);
}
}
When I replace the intent for selecting photos with that intent and onActivityResult code it gets me lots of errors and highlights the code red starting with action.Action_multiple_pick as if there is no such thing in java.
My actual code:
public class MainActivity extends AppCompatActivity {
/**
* this is the destination of the new GIF file, it will be saved directly in the SD card
* (internal storage) in a file named "test.gif"
*/
private static final String IMAGE_PATH = "/sdcard/test.gif";
private static final int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private boolean zoomOut = false;
private Button btnSelect;
private LinearLayout root;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
root = (LinearLayout) findViewById(R.id.ll);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
ImageView ivImage = (ImageView) findViewById(R.id.ivImage);
ivImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (root.getChildCount() == 0) {
return;
}
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(IMAGE_PATH);
outStream.write(generateGIF());
outStream.close();
Toast.makeText(MainActivity.this,
"GIF saved to " + IMAGE_PATH, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outStream != null) {
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/* video/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
Bitmap resized = Bitmap.createScaledBitmap(thumbnail, 800, 150, true);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ImageView ivImage = new ImageView(this);
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xFF00FF00); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(5);
gd.setStroke(1, 0xFF000000);
ivImage.setBackground(gd);
// the following code causes a crash "NullPointerException" :
// Point point = null; // --> the reason for the crash
// getWindowManager().getDefaultDisplay().getSize(point);
// int width = point.x;
// int height = point.y;
//
// ivImage.setMinimumWidth(width);
// ivImage.setMinimumHeight(height);
//
// ivImage.setMaxWidth(width);
// ivImage.setMaxHeight(height);
// ivImage.getLayoutParams().width = 20; // --> another crash happens here
// ivImage.getLayoutParams().height = 20;
ivImage.setLayoutParams(new ActionBar.LayoutParams(
GridLayout.LayoutParams.WRAP_CONTENT,
GridLayout.LayoutParams.MATCH_PARENT));
ivImage.setImageBitmap(thumbnail);
root.addView(ivImage);
// setContentView(root);
// ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
final ImageView ivImage = new ImageView(this);
ivImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (zoomOut) {
Toast.makeText(getApplicationContext(), "NORMAL SIZE!", Toast.LENGTH_LONG).show();
ivImage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ivImage.setAdjustViewBounds(true);
zoomOut = false;
} else {
Toast.makeText(getApplicationContext(), "FULLSCREEN!", Toast.LENGTH_LONG).show();
ivImage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
ivImage.setScaleType(ImageView.ScaleType.FIT_XY);
zoomOut = true;
}
}
});
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
ivImage.setMinimumWidth(width);
ivImage.setMinimumHeight(height);
ivImage.setMaxWidth(width);
ivImage.setMaxHeight(height);
ivImage.setLayoutParams(new ActionBar.LayoutParams(
1000,
1000));
ivImage.setImageBitmap(bm);
root.addView(ivImage);
setContentView(root);
ivImage.setImageBitmap(bm);
}
private byte[] generateGIF() {
ArrayList<Bitmap> bitmaps = new ArrayList<>();
View v;
ImageView iv;
for (int i = 0; i < root.getChildCount(); i++) {
v = root.getChildAt(i);
if (v instanceof ImageView) {
iv = (ImageView) v;
bitmaps.add(((BitmapDrawable) iv.getDrawable()).getBitmap());
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(bos);
for (Bitmap bitmap : bitmaps) {
encoder.addFrame(bitmap);
}
encoder.finish();
return bos.toByteArray();
}
}
Please help me out
I am trying to develop an app where you can take pictures and then display them on screen or upload a picture from your SD card and display on screen. Currently I am app to upload and display it on screen however when i select the option to take a photo I am able to take the photo and click save, however, the photo will not display on the screen nor will it save to the SD card. Please help!
public class UploadActivity extends Fragment {
private Button bt_browse;
private ImageView iv_photo;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private String uploadImagePath = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.upload,
container, false);
bt_browse = (Button) rootView.findViewById(R.id.button1);
iv_photo = (ImageView) rootView.findViewById(R.id.iv_photo);
bt_browse.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
selectImage();
}
});
return rootView;
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"), SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(f.getAbsolutePath(), btmapOptions);
bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
iv_photo.setImageBitmap(bm);
uploadImagePath = f.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri, getActivity());
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
iv_photo.setImageBitmap(bm);
uploadImagePath = tempPath;
}
}
}
#SuppressWarnings("deprecation")
public String getPath(Uri uri, Activity activity) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = activity.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
I have also added the following code to the Manifest file
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
i was handled this Scenario with this methods as:
private void getImageFromCamera() {
Log.i("GalaNotes", "From CAMERA Setting Capture TRUE");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "tmp_avatar_"
+ String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
private void getImageFromGallery() {
Log.i("GalaNotes", "From Gallery Setting Capture TRUE");
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_FROM_FILE);
}
In the onActivityResult() method you can print the Uri or Path where it was stored as follows :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_FROM_CAMERA:
try {
log.i("Stored location of File",getRealPathFromURI(mImageCaptureUri));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
Log.d("PHOTO", "" + mImageCaptureUri.toString()); // UPLOAD FEEDS
// RESPONSE
// doCrop();
Intent i = new Intent(activity, CropActivity.class);
try {
i.putExtra("imgSdcardPath", getRealPathFromURI(mImageCaptureUri));// mImageCaptureUri.toString());
startActivityForResult(i, 212);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}}
If You have any Query then givefeedback on my Post.
Try the standart way to get the photo from onActivityResult:
Bitmap imageBitmap = (Bitmap) data.getExtras().get("data");
// Global Declaration
Intent intent;
String imageFileName,videoFileName;
Uri uri;
private void clickPhotoFromCamera() {
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
imageFileName = "JPEG_" + timeStamp + ".jpg";
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), imageFileName);
uri = Uri.fromFile(imageStorageDir);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, 1);
}
private void captureVideoFromCamera() {
intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
videoFileName = "VID_" + timeStamp + ".mp4";
File videoStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), videoFileName);
uri = Uri.fromFile(videoStorageDir);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, 2);
}
private void uploadMediaFromGallery() {
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/* video/*");
startActivityForResult(intent, 3);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
imagePath = uri.getPath();
// Do whatever you want with image path...
} else if (requestCode == 2) {
videoPath = uri.getPath();
// Do whatever you want with Video path...
} else {
uri = data.getData();
mediaPath = getPath(getApplicationContext(), uri);
}
}
}
// For get Image or video from path...
File mediaFile = new File(mediaPath);
Bitmap bitmap;
if (mediaFile.exists()) {
if (isImage(mediaPath)) {
Bitmap myBitmap = BitmapFactory.decodeFile(mediaFile.getAbsolutePath());
int height = (myBitmap.getHeight() * 512 / myBitmap.getWidth());
Bitmap scale = Bitmap.createScaledBitmap(myBitmap, 512, height, true);
int rotate = 0;
try {
exif = new ExifInterface(mediaFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
rotate = 0;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
Bitmap rotateBitmap = Bitmap.createBitmap(scale, 0, 0, scale.getWidth(), scale.getHeight(), matrix, true);
displayImage.setImageBitmap(rotateBitmap);
} else {
bitmap = ThumbnailUtils.createVideoThumbnail(mediaPath, Thumbnails.MICRO_KIND);
displayImage.setImageBitmap(bitmap);
}
}
public static boolean isImage(String str) {
boolean temp = false;
String[] arr = { ".jpeg", ".jpg", ".png", ".bmp", ".gif" };
for (int i = 0; i < arr.length; i++) {
temp = str.endsWith(arr[i]);
if (temp) {
break;
}
}
return temp;
}
In my widget, I have an imageView that collect an image from the user gallery and then sets that image up as the background in another activity. It works fine, but when I try to add an image file that is too big (such as an image from the camera) or upload many image files, I get an "out of memory" error. After looking around stackoverflow for a while, I noticed that everyone pretty much used the basic method of:
public static Bitmap decodeSampleImage(File f, int width, int height) {
try {
System.gc(); // First of all free some memory
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// The new size we want to scale to
final int requiredWidth = width;
final int requiredHeight = height;
// Find the scale value (as a power of 2)
int sampleScaleSize = 1;
while (o.outWidth / sampleScaleSize / 2 >= requiredWidth && o.outHeight / sampleScaleSize / 2 >= requiredHeight)
sampleScaleSize *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = sampleScaleSize;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (Exception e) {
Log.d(TAG, e.getMessage()); // We don't want the application to just throw an exception
}
return null;
}
I also noticed that people have recycled unused bitmaps as well. I understand how this works but I don't know where I should put it in my coding.
Here are my two classes (Personalize.java where the imageView to collect the background is. It has the imageView and two buttons (one for choosing an image from the gallery where it then displays that image into the imageView and the other to then set that image as the background).
First here is Personalize.java:
package com.example.awesomefilebuilderwidget;
IMPORTS
public class Personalize extends Activity implements View.OnClickListener {
Button button;
ImageView image; //the imageview for setting the background
ImageView image2; //the imageview for setting the icon (not focusing on)
Button btnChangeImage;
Button btnChangeImageForIcon;
Button btnSetBackground;
private static final int SELECT_PICTURE = 1;
private static final int SELECT_PICTURE_2 = 2;
private String selectedImagePath;
Bitmap background;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personalize);
image = (ImageView) findViewById(R.id.imageView1);
image2 = (ImageView) findViewById(R.id.imageView2Icon);
Button btnChangeImage = (Button) findViewById(R.id.btnChangeImage);
btnChangeImage.setOnClickListener(this);
Button btnChangeImageForIcon = (Button) findViewById(R.id.btnChangeImageForIcon);
btnChangeImageForIcon.setOnClickListener(this);
Button btnSetBackground = (Button) findViewById(R.id.btnSetBackground);
btnSetBackground.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnChangeImage:
launchImageChooser();
break;
case R.id.btnChangeImageForIcon:
launchImageChooser();
break;
case R.id.btnSetBackground:
setBackgroundImageInDragAndDrop();
break;
}
}
private void setBackgroundImageInDragAndDrop() {
Log.d("Personalize", "setBackgroundImageInDragAndDrop() called");
Intent i = getIntent();
//Convert bitmap to byte array to send back to activity
// See: http://stackoverflow.com/questions/11010386/send-bitmap-using-intent-android
ByteArrayOutputStream stream = new ByteArrayOutputStream();
background.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[]byteArray = stream.toByteArray();
i.putExtra("myBackgroundBitmap", byteArray);
setResult(RESULT_OK, i);
finish();
}
private void launchImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, SELECT_PICTURE);
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String imagePath = cursor.getString(column_index);
if(cursor != null) {
cursor.close();
}
return imagePath;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE)
{
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
background = getAndDecodeImage(selectedImagePath);
if(background != null){
image.setImageBitmap(background);
}
} else if (requestCode == SELECT_PICTURE_2)
{
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
Bitmap b2 = getAndDecodeImage(selectedImagePath);
if(b2 != null){
image2.setImageBitmap(b2);
}
}
}
}
private Bitmap getAndDecodeImage(String selectedImagePath){
try {
Log.d("Personalize", "selectedImagePath: " + selectedImagePath);
FileInputStream fileis=new FileInputStream(selectedImagePath);
BufferedInputStream bufferedstream=new BufferedInputStream(fileis);
byte[] bMapArray= new byte[bufferedstream.available()];
bufferedstream.read(bMapArray);
Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
if (fileis != null)
{
fileis.close();
}
if (bufferedstream != null)
{
bufferedstream.close();
}
return bMap;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public boolean saveImageToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = this.openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
return false;
}
}
}
Then here is my Drag_and_Drop_App.java (snippet of important parts -- collects bitmap and sets as background):
package com.example.awesomefilebuilderwidget;
IMPORTS
public class Drag_and_Drop_App extends Activity {
private static final int SET_BACKGROUND = 10;
private ListView mListAppInfo;
// Search EditText
EditText inputSearch;
public AppInfoAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set layout for the main screen
setContentView(R.layout.drag_and_drop_app);
// import buttons
Button btnLinkToFeedback = (Button) findViewById(R.id.btnLinkToFeedback);
Button btnLinkToPersonalize = (Button) findViewById(R.id.btnLinkToPersonalize);
// Link to Personalize Screen
btnLinkToPersonalize.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
Personalize.class);
startActivityForResult(i, SET_BACKGROUND);
}
});
}
public Bitmap getThumbnail(String filename) {
Bitmap thumbnail = null;
try {
File filePath = this.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
thumbnail = BitmapFactory.decodeStream(fi);
} catch (Exception ex) {
Log.e("getThumbnail() on internal storage", ex.getMessage());
}
return thumbnail;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("Drag_and_Drop_App", "requestCode: " + requestCode + ", resultCode: " + resultCode);
if(requestCode == SET_BACKGROUND && resultCode == RESULT_OK){
byte[] byteArray = data.getByteArrayExtra("myBackgroundBitmap");
Bitmap myBackground = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
setBackgroundImage(myBackground);
}
}
#SuppressLint("NewApi")
private void setBackgroundImage(Bitmap bitmap) {
RelativeLayout yourBackgroundView = (RelativeLayout) findViewById(R.id.rl_drag_and_drop_app);
Drawable d = new BitmapDrawable(getResources(), bitmap);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
yourBackgroundView.setBackgroundDrawable(d);
} else {
yourBackgroundView.setBackground(d);
}
}
}
So where could I implement that coding and where could I also get rid of other unused bitmaps in memory? (recycle them?)