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;
}
Related
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.
The complete code of my Fragment:
public class ProfileEditPictureFragment extends BaseFragment implements OnClickListener {
private ImageView imageView = null;
private Button buttonPick = null;
private Button buttonSave = null;
private Button buttonCancel = null;
private File tempFile = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
this.sessionProfilePreferences = new SessionProfilePreferences(this.getActivity());
this.sessionLoginPreferences = new SessionLoginPreferences(this.getActivity());
this.sessionLoginSingleton = SessionLoginSingleton.getInstance(this.getActivity());
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
this.tempFile = new File(Environment.getExternalStorageDirectory(), "temp_photo.jpg");
}
else {
this.tempFile = new File(this.getActivity().getFilesDir(), "temp_photo.jpg");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile_picture_edit, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.imageView = (ImageView) view.findViewById(R.id.profile_picture_edit_imageview_photo);
this.buttonPick = (Button) view.findViewById(R.id.profile_picture_edit_button_pick);
this.buttonPick.setOnClickListener(this);
this.buttonSave = (Button) view.findViewById(R.id.profile_picture_edit_button_save);
this.buttonSave.setOnClickListener(this);
this.buttonCancel = (Button) view.findViewById(R.id.profile_picture_edit_button_cancel);
this.buttonCancel.setOnClickListener(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("ProfileEditPicture", "requestCode: " + requestCode);
Log.v("ProfileEditPicture", "resultCode: " + resultCode);
Log.v("ProfileEditPicture", "data: " + data);
Bitmap bitmap = null;
if(resultCode == Activity.RESULT_OK) {
if (requestCode == Globals.REQUEST_PICK_PHOTO) {
try {
InputStream inputStream = this.getActivity().getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(this.tempFile);
Helper.copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
this.startCropImage();
} catch (Exception e) {}
} else if (requestCode == Globals.REQUEST_CROP_PHOTO) {
String path = data.getStringExtra(CropActivity.IMAGE_PATH);
if (path == null) {
return;
}
bitmap = BitmapFactory.decodeFile(this.tempFile.getPath());
this.imageView.setImageBitmap(bitmap);
}
}
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.profile_picture_edit_button_pick : {
this.pickPicture();
} break;
case R.id.profile_picture_edit_button_save : {
} break;
case R.id.profile_picture_edit_button_cancel : {
this.getActivity().finish();
}
}
}
private void pickPicture() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
this.startActivityForResult(Intent.createChooser(intent, "Select Picture"), Globals.REQUEST_PICK_PHOTO);
}
private void startCropImage() {
Intent intent = new Intent(this.getActivity(), CropActivity.class);
intent.putExtra(CropActivity.IMAGE_PATH, this.tempFile.getPath());
intent.putExtra(CropActivity.SCALE, true);
intent.putExtra(CropActivity.ASPECT_X, 3);
intent.putExtra(CropActivity.ASPECT_Y, 2);
this.startActivityForResult(intent, Globals.REQUEST_CROP_PHOTO);
}
}
But the resultCode is always 0 and the data is always null. Permissions are set ofcourse.
So how can i pick images from the gallery?
I test it on Nexus 4 with Android 5.0.1
Try ACTION_PICK like this
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
And on Activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
I was having same problem in one of my activities when I set launchMode="singleInstance" in manifest for that activity. It works fine when I remove that attribute. Although I don't know reason for this behaviour.
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)
Here, I have to select an image from gallery or camera. When user selects image from gallery, that selected image should be displayed to next activity. But here these both activities are under the same tab, say tab A. Means in tab A there are two activities. In first activity, user has two options to select image either from gallery or from camera. And in second activity under same tab A, user gets that selected image. But here I'm not getting the expected output. Below is my code...
MainActivity.java
public class MainActivity extends TabActivity {
TabHost tabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources ressources = getResources();
tabHost = getTabHost();
Intent intentProfile = new Intent().setClass(this, Tab1.class);
TabSpec tabProfile = tabHost
.newTabSpec("Profile")
.setIndicator("Profile", ressources.getDrawable(R.drawable.ic_launcher))
.setContent(intentProfile);
Intent intentFriends = new Intent().setClass(this, Tab2.class);
TabSpec tabFriends = tabHost
.newTabSpec("Friends")
.setIndicator("Friends", ressources.getDrawable(R.drawable.ic_launcher))
.setContent(intentFriends);
tabHost.addTab(tabProfile);
tabHost.addTab(tabFriends);
tabHost.setCurrentTab(0);
}
public void switchTabBar(int tab) {
tabHost.setCurrentTab(tab);
}
#Override
public void onBackPressed() {
// Called by children
MainActivity.this.finish();
}
}
ABCGroup.java
public class ABCGroup extends ActivityGroup{
public static ABCGroup group;
private ArrayList<View> history;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.history = new ArrayList<View>();
group = this;
View view = getLocalActivityManager().startActivity
("ParentActivity",
new Intent(ABCGroup.this, Tab1.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
replaceView(view);
}
public void replaceView(View v) {
// Adds the old one to history
history.add(v);
// Changes this Groups View to the new View.
setContentView(v);
}
public void back() {
if(history.size() > 0) {
history.remove(history.size()-1);
if(history.size()<=0){
finish();
}else{
setContentView(history.get(history.size()-1));
}
}else {
finish();
}
}
#Override
public void onBackPressed() {
ABCGroup.group.back();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK){
ABCGroup.group.back();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Tab1.java
public class Tab1 extends ActivityGroup {
Button gallery, camera;
private ArrayList<View> myActivityHistory;
private static final int REQUEST_ID = 1;
private static final int HALF = 2;
private static final int TAKE_PICTURE = 3;
private Uri mUri;
private Bitmap mPhoto;
int i = 0;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab1);
myActivityHistory = new ArrayList<View>();
gallery = (Button)findViewById(R.id.gallery);
camera = (Button)findViewById(R.id.camera);
gallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_ID);
}
});
camera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
File f = new File(Environment.getExternalStorageDirectory(), "photo.jpg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
mUri = Uri.fromFile(f);
startActivityForResult(i, TAKE_PICTURE);
}
});
}
public void replaceContentView(String id, Intent newIntent, int flag)
{
View mview = getLocalActivityManager().startActivity(id,newIntent.addFlags(flag)).getDecorView();
ABCGroup.group.replaceView(mview);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK)
{
getContentResolver().notifyChange(mUri, null);
ContentResolver cr = getContentResolver();
try
{
mPhoto = null;
mPhoto = android.provider.MediaStore.Images.Media.getBitmap(cr, mUri);
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
break;
case REQUEST_ID :
InputStream stream = null;
if (resultCode == Activity.RESULT_OK) {
try
{
stream = getContentResolver().openInputStream(data.getData());
Bitmap original;
original = null;
original= BitmapFactory.decodeStream(stream);
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
Intent in = new Intent(Tab1.this, Second.class);
replaceContentView("activity3", in, Intent.FLAG_ACTIVITY_CLEAR_TASK);
}
catch (Exception e)
{
e.printStackTrace();
}
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
Toast.makeText(getBaseContext(), "" + cursor.getString(column_index) , 5000).show();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("data", cursor.getString(column_index) );
editor.commit();
return cursor.getString(column_index);
}
}
Second.java
public class Second extends ActivityGroup {
public static Bitmap bmp;
String path;
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Button btn = (Button)findViewById(R.id.button1);
iv = (ImageView)findViewById(R.id.imageView1);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
path = preferences.getString("data", "");
File imgFile = new File(path);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
iv.setImageBitmap(myBitmap);
}
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ABCGroup.group.back();
}
});
}
#Override
public void onBackPressed() {
// this.getParent().onBackPressed();
Intent intent = new Intent(Second.this, Tab1.class);
Tab1 parentActivity = (Tab1)getParent();
parentActivity.replaceContentView("Profile", new Intent(Second.this, Tab1.class), Intent.FLAG_ACTIVITY_CLEAR_TASK);
}
}
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();
}
}