null bitmap when capturing image and receiving results inside fragments Android - android

I'm trying to capture image from camera and put result in grid view. I use fragments as follow. I receive null pointer exception on OnActivityResult while trying to receive the intent extras :
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
try {
FileOutputStream outStream = new FileOutputStream(PATH_TO_SAVE+"img2.png");
//NULL pointer exception here
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
if (success) {
Log.i("SF", "Image saved with success");
} else {
Log.i("SF", "Image saved with F");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
// Starting activity here
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.submit_feed_scr2 , container, false);
Button b = (Button) view.findViewById(R.id.btnCapture);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new
File(PATH_TO_SAVE)));
startActivityForResult(intent, CAPTURE_ITEM);
}
});
//Adapter
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,
items);
GridView gridview = (GridView) view.findViewById(R.id.gridView1);
gridview.setAdapter(adapter);
//Providing Grid with Images
gridview = (GridView) view.findViewById(R.id.gridView1);
gridview.setAdapter(new ImageAdapter(view.getContext(),1));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Toast.makeText(this, "" + position, Toast.LENGTH_SHORT).show();
}
});
return view;
}

Your photo is saved in PATH_TO_SAVE location.
You should in onActivityResult do something like this:
File file = new File(PATH_TO_SAVE);
Bitmap bmp = BitmapFactory.decodeFile(file.getPath());

try this, it works for me:
if (resultCode == RESULT_OK) {
String realPath = Constants.TMP_CAMERA_PATH;
photoTaked = (Bitmap) data.getExtras().get("data");
photoTakedFile = new File(realPath);
photoTakedFile.deleteOnExit();
if (photoTakedFile.exists()) {
photoTakedFile.delete();
}
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photoTaked.compress(Bitmap.CompressFormat.PNG, 90, bytes);
photoTakedFile.createNewFile();
FileOutputStream fo = new FileOutputStream(photoTakedFile);
fo.write(bytes.toByteArray());
fo.close();
uploadImageView.setImageBitmap(photoTaked);
uploadImageView.setVisibility(View.VISIBLE);
calcRemainingChars();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

Androind ImageView in Fragment

I am trying to put an image on my fragment, but the image is not showing up. I am certain that it was working just yesterday but now it is not. Any help is appreciated.
This code is in my Fragment:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mUser = (User) getArguments().getSerializable(ARGS_USER);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_picture_picker, container, false);
mImageView = v.findViewById(R.id.imageView);
mSelectImageButton = v.findViewById(R.id.select_image);
mSelectImageButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, IMG_REQUEST);
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == IMG_REQUEST && resultCode == Activity.RESULT_OK && data != null){
Uri path = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), path);
mImageView.setImageBitmap(bitmap);
mImageView.setVisibility(View.VISIBLE);
mUser.setProfilePicture(bitmap);
}catch(IOException e){
e.printStackTrace();
}
}
}
Actually you are not using the Volley. Please change the heading of your question. You are accessing the Gallery and showing the image inside the imageView. Use the below code for accessing the image from camera as well as gallery.
if (action.equals("CAMERA")) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, ACTION_REQUEST_CAMERA);
} else {
openCamera();
}
} else if (action.equals("GALLERY")) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, ACTION_REQUEST_GALLERY);
} else {
openGallery();
}
}
private void openCamera(){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
getActivity().startActivityForResult(cameraIntent, ACTION_REQUEST_CAMERA);
}
private void openGallery(){
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
Intent chooser = Intent.createChooser(galleryIntent, "Choose a Picture");
getActivity().startActivityForResult(chooser, ACTION_REQUEST_GALLERY);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("OnActivityResult");
System.out.println("resultCode: "+resultCode+"\n"+"requestCode: "+requestCode);
ImageOperations operations = new ImageOperations();
if (resultCode == RESULT_OK) {
if (requestCode == ACTION_REQUEST_GALLERY) {
System.out.println("select file from gallery ");
Uri selectedImageUri = data.getData();
renderProfileImage(selectedImageUri,operations);
} else if (requestCode == ACTION_REQUEST_CAMERA) {
System.out.println("select file from camera ");
Bitmap photo = (Bitmap) data.getExtras().get("data");
String name = "profile_pic.png";
operations.saveImageToInternalStorage(photo,getActivity(),name);
profile_image.setImageBitmap(photo);
}
}
}
private void renderProfileImage(Uri selectedImageUri,ImageOperations operations) {
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImageUri);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bytes);
String name = "profile_pic.png";
operations.saveImageToInternalStorage(bitmap,getActivity(),name);
profile_image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
private class ImageOperations {
public boolean saveImageToInternalStorage(Bitmap image, Context context, String name) {
try {
// Use the compress method on the Bitmap object to write image to
// the OutputStream
FileOutputStream fos = context.openFileOutput("profile_pic.png", Context.MODE_PRIVATE);
// Writing the bitmap to the output stream
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
return false;
}
}
public Bitmap getThumbnail(Context context,String filename) {
String fullPath = Environment.getDataDirectory().getAbsolutePath();
Bitmap thumbnail = null;
// Look for the file on the external storage
try {
if (isSdReadable() == true) {
thumbnail = BitmapFactory.decodeFile(fullPath + "/" + filename);
}
} catch (Exception e) {
Log.e("Image",e.getMessage());
}
// If no file on external storage, look in internal storage
if (thumbnail == null) {
try {
File filePath = context.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
thumbnail = BitmapFactory.decodeStream(fi);
} catch (Exception ex) {
Log.e("getThumbnail()", ex.getMessage());
}
}
return thumbnail;
}
public boolean isSdReadable() {
boolean mExternalStorageAvailable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = true;
Log.i("isSdReadable", "External storage card is readable.");
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
Log.i("isSdReadable", "External storage card is readable.");
mExternalStorageAvailable = true;
} else {
// Something else is wrong. It may be one of many other
// states, but all we need to know is we can neither read nor write
mExternalStorageAvailable = false;
}
return mExternalStorageAvailable;
}
}
action is like what you want to do. ACTION_REQUEST_GALLERY and ACTION_REQUEST_CAMERA use some integer constants like 100 and 101. profileImage is your ImageView.

How to create a GIF from multiple image bitmaps in android

The main theme of my app is, user has to select images from his device gallery, and those selected images are turned into a GIF. I'm converting those selected images into bitmap and I am using this GIFEncoder.java file to converted selected images into a GIF, and I have achieved it. when I check it in my folder, GIF was created but when I open the GIF is was not animating just a black screen was appeared.
Here is my MainActivity looks like:
public class MainActivity extends AppCompatActivity {
private static final int SELECT_PHOTO = 102;
private FileOutputStream outStream;
ArrayList<Bitmap> bitmaps = new ArrayList<>();
private Button generateImageGIF, selectImages;
String BASE_PATH = Environment.getExternalStorageDirectory().toString() + File.separator + "ImagesToGif";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File mydir = new File(BASE_PATH);
if (!mydir.exists()) {
mydir.mkdirs();
}
generateImageGIF = (Button) findViewById(R.id.generate_image_gif);
selectImages = (Button) findViewById(R.id.select_images);
selectImages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
});
generateImageGIF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Toast.makeText(getApplicationContext(), "gif creation started", Toast.LENGTH_LONG).show();
outStream = new FileOutputStream(BASE_PATH + File.separator + getString(R.string.app_name) + ".gif");
outStream.write(generateGIF());
outStream.close();
Toast.makeText(getApplicationContext(), "gif creation ended", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK && data != null) {
Bitmap bitmap1 = BitmapFactory.decodeFile(String.valueOf(data.getData()));
bitmaps.add(bitmap1);
}
}
public byte[] generateGIF() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(bos);
for (Bitmap bitmap : bitmaps) {
encoder.addFrame(bitmap);
}
encoder.finish();
return bos.toByteArray();
}
}

capture and save continious image in Android

this is my code it store captured picture form camera and save it on the SDcard but Now i want to enhance this code to taking pictures every 5 seconds If any body having an idea how to do this ,please share
public class MainActivity extends ActionBarActivity {
private final int requestCode = 20;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int pictureCounter = 10;
imageHolder = (ImageView)findViewById(R.id.captured_photo);
Button capturedImageButton = (Button)findViewById(R.id.photo_button);
capturedImageButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, requestCode);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(this.requestCode == requestCode && resultCode == RESULT_OK){
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
String partFilename = currentDateFormat();
storeCameraPhotoInSDCard(bitmap, partFilename);
}
}
private String currentDateFormat(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
return currentTimeStamp;
}
private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You should implement a runnable interface that uses threads. This way you could call the function on the OnClick method, then call Thread.sleep(timeinmilliseconds), then call the function inside the onClick method again, as many times as needed.
Here is an example of how to use threads:
http://www.wideskills.com/java-tutorial/java-threads-tutorial

Can't save and retrieve image in android studio

I am working in fragments in android studio and In it I was trying to pick an image from gallery by clicking a button then save it and then again retrieve it when I again launch the app.Here is my code of picking image from gallery after clicking the button and saving and retrieving it.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_homepage, container, false);
iv = (ImageView) view.findViewById(R.id.profileImageView);
location=(TextView)view.findViewById(R.id.textView9);
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openGallery();
}
});
retrieveImage();
return view;
}
private void openGallery() {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try
{
if (requestCode==RESULT_OK){
String path=getPathFromCameraData(data,getActivity());
Bitmap bmp=BitmapFactory.decodeFile(path);
iv.setImageBitmap(bmp);
storeImage(bmp);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private String getPathFromCameraData(Intent data, Context context) {
Uri selectImage=data.getData();
String[] filepathColumn={MediaStore.Images.Media.DATA};
Cursor cursor=context.getContentResolver().query(selectImage, filepathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndx=cursor.getColumnIndex(filepathColumn[0]);
String piturepath=cursor.getString(columnIndx);
cursor.close();
return piturepath;
}
private boolean storeImage(Bitmap bitmap) throws IOException {
OutputStream outputStream=null ;
String directory=Environment.getExternalStorageDirectory().toString();
File file=new File(directory,"/friend");
if (file.exists())file.delete();
try{
outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
MediaStore.Images.Media.insertImage(getActivity().getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
}
catch (Exception e){
e.printStackTrace();
}
return true;
}
public boolean retrieveImage(){
File f = new File(android.os.Environment.getDataDirectory() + "profile.jpg");
Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
iv.setImageBitmap(bmp);
return true;
}

Picture not displaying after using camera to take photo

I am trying to click a photo in a fragment and display it inside my app. After I click the photo, the imageView is not set and I don't see the photo getting displayed. Does anyone know why?
Also do you think there is a better way of writing the code for taking a picture inside the fragment?
public class ImageFragment extends Fragment{
private Uri imageUri;
private String mPath;
private ImageView image;
Bitmap bitmap = null;
private File tempPhoto;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_image, container, false);
ImageButton snap=((ImageButton)v.findViewById(R.id.snap));
image = ((ImageView) v.findViewById(R.id.image));
snap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagePath;
try
{
tempPhoto = createTemporaryFile("picture", ".png");
tempPhoto.delete();
}
catch(Exception e)
{
return ;
}
imageUri = Uri.fromFile(tempPhoto);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(cameraIntent, 1);
}
});
return v;
}
private File createTemporaryFile(String part, String ext) throws Exception
{
File tempDir= Environment.getExternalStorageDirectory();
tempDir=new File(tempDir.getAbsolutePath()+"/.temp/");
if(!tempDir.exists())
{
tempDir.mkdir();
}
return File.createTempFile(part, ext, tempDir);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
ContentResolver cr = getActivity().getContentResolver();
try {
cr.notifyChange(imageUri, null);
File imageFile = new File(tempPhoto.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
Bitmap photo=null;
if (resultCode == 1) {
try {
photo = android.provider.MediaStore.Images.Media.getBitmap(cr, Uri.fromFile(tempPhoto));
image.setImageBitmap(photo);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onLowMemory() {
// TODO Auto-generated method stub
super.onLowMemory();
}
}
You compare 'resultCode' with Activity.RESULT_OK(=-1) in onActivityResult function.
Replace:
if (resultCode == 1)
by:
if (resultCode == Activity.RESULT_OK)

Categories

Resources