Good Day
I'm trying to capture an image with camera when I press the Button,then save it in Sqllite and then display it in gridview..
but after I capture the image it doesn't appear in the grid view :/ no error appear in logcat except nothing displayed in gridview
can anyone help?
here is my code
public class CameraFragment extends Fragment {
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final String IMAGE_DIRECTORY_NAME = "Myfiles";// directory name to store captured images
private static String mCurrentPhotoPath; // file path to the last image captured
View view;
private Uri fileUri;// file url to store image
private GridView myGridView;
private ImageListAdapter adapter;
private List<Images> myLists;// image list
Images images;
DatabaseAdapter DBadapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
// Inflate the layout for this fragment
view = inflater
.inflate(R.layout.fragment_camera, container, false);
} catch (InflateException e) {
/* map is already there, just return view as it is */
e.printStackTrace();
}
if (view != null)
init();
return view;
}
// initialize all the variables
private void init() {
DatabaseAdapter DBadapter =new DatabaseAdapter(getActivity());
DBadapter.open();
myLists = new ArrayList<Images>();
myLists=DBadapter.getImagesList();
adapter = new ImageListAdapter(getActivity(), R.layout.img_list_view, myLists);
// imageView = (ImageView) view.findViewById(R.id.imageListView);
Button myButton = (Button) view.findViewById(R.id.camerabutton);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);// create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE); // start the image capture Intent
}
});
myGridView = (GridView) view.findViewById(R.id.gridView);
myGridView.setAdapter(adapter);
/**
* Create a file Uri for saving an image or video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image /
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
//return null;
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//file path of captured image
String filePath = cursor.getString(columnIndex);
//file path of captured image
File f = new File(filePath);
String filename = f.getName();
cursor.close();
DBadapter.insertImage(images); //insaert image to database
myLists=DBadapter.getImagesList();
adapter = new ImageListAdapter(getActivity(), R.layout.img_list_view, myLists);
myGridView.setAdapter(adapter);
myGridView.invalidateViews();
break;
}
case 2:
if (resultCode == getActivity().RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getActivity(), "User cancelled image capture", Toast.LENGTH_SHORT)
.show();
}
else {
// failed to capture image
Toast.makeText(getActivity(), "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
} break;
}}
}
here is xml :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.labon.invoicemanger.CameraFragment">
<!-- TODO: Update blank fragment layout --> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Invoice"
android:layout_gravity="center"
android:layout_margin="20dp"
android:id="#+id/textView16"
android:textColor="#color/colorPrimary"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<GridView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/gridView"
android:layout_above="#+id/camerabutton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:numColumns="auto_fit"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add New Invoice"
android:textSize="18dp"
android:textStyle="bold"
android:textColor="#android:color/white"
android:id="#+id/camerabutton"
android:drawableRight="#drawable/screenshot"
android:background="#color/colorAccent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<!--android:drawableRight="#drawable/screen_shot"--> </RelativeLayout> </FrameLayout>
I think you should refresh your grid view when you save images in sqlite.
see the following link, it might help you:
click here!
you should use invalidateViews() method.
Related
I am creating an app which captures image from camera and saves image in a file. In onActivityResult() method i am getting null object reference error.
My Fragment class is here:
public class HomeFragment extends Fragment {
private static final int REQUEST_IMAGE_CAPTURE = 1;
private static final String JPEG_FILE_PREFIX = "IBR_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
File photoFile = null;
ImageButton camera_button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
camera_button = (ImageButton) rootView.findViewById(R.id.camera);
camera_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.i("File error", "File");
}
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri fileUri = Uri.fromFile(photoFile);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
fileUri);
Toast.makeText(getActivity(), photoFile.toString(), Toast.LENGTH_SHORT).show();
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
});
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
camera_button.setImageBitmap(imageBitmap);
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, storageDir);
return imageF;
}
}
Actually i am getting error in this line Bundle extras = data.getExtras();
Any suggestion how can i solve this problem?
If you specify MediaStore.EXTRA_OUTPUT then no thumb pick is returned in intent extra - in activityOnResult - you have to read manually filepath you have provided as MediaStore.EXTRA_OUTPUT.
You can read in docs for ACTION_IMAGE_CAPTURE:
The caller may pass an extra EXTRA_OUTPUT to control where this image will be written. *If the EXTRA_OUTPUT is not present, then a small sized image is returned as a Bitmap object in the extra field.
My Target:
Get one photo from camera or gallery, then set it to imageViewA
Add a draggable mask imageViewB on top of imageViewA
Users drag the mask imageViewB to anywhere in imageViewA
Users then click the save button
A combined bitmap of imageViewA and imageViewB should be created
My Problem:
Everything works fine, except that the imageViewB in the combined bitmap is not positioned appropriately (see the attached picture)
Code (MainActivity.java):
public class MainActivity extends ActionBarActivity {
Bitmap bmMask = null;
Bitmap bmOriginal = null;
Bitmap bmCombined = null;
ImageView normalImgView;
ImageView maskImgView;
ImageView combinedImgView;
static final int REQUEST_TAKE_PHOTO = 55;
static final int REQUEST_LOAD_IMAGE = 60;
String currentImagePath;
static final String TAG = "mover";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
combinedImgView = (ImageView) findViewById(R.id.combinedImgView);
normalImgView = (ImageView) findViewById(R.id.normalImgView);
maskImgView = (ImageView) findViewById(R.id.maskImgView);
bmMask = ((BitmapDrawable) maskImgView.getDrawable()).getBitmap();
Button addBtn = (Button) findViewById(R.id.addBtn);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bmCombined = ProcessingBitmap();
if(bmCombined!=null){
combinedImgView.setImageBitmap(bmCombined);
}
else {
Log.d(MainActivity.TAG, "combined bm is null");
}
}
});
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(MainActivity.TAG, "clicked");
getImageFromCameraIntent();
}
});
MultiTouchListener mTouchListener = new MultiTouchListener();
mTouchListener.isRotateEnabled = false;
// mTouchListener.isTranslateEnabled = false;
mTouchListener.isScaleEnabled = false;
maskImgView.setOnTouchListener(mTouchListener);
}
// take image from camera
private void getImageFromGalleryIntent() {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, REQUEST_LOAD_IMAGE);
}
// take image from camera
private void getImageFromCameraIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(this.getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
// create a image file for storing full size image taken from camera
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentImagePath = image.getAbsolutePath();
Log.d(MainActivity.TAG, "photo path: " + currentImagePath);
return image;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
// photo returned from camera
// update UI
updatePhotoView(currentImagePath);
} else if (requestCode == REQUEST_LOAD_IMAGE && resultCode == Activity.RESULT_OK) {
// photo returned from gallery
// update UI
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = this.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
updatePhotoView(picturePath);
} else {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
}
}
// scale down the image, then display it to image view
private void updatePhotoView(String photoPath) {
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(photoPath, bmOptions);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, bmOptions);
bmOriginal = bitmap;
normalImgView.setImageBitmap(bmOriginal);
}
private Bitmap ProcessingBitmap(){
Bitmap newBitmap = null;
int w;
w = bmOriginal.getWidth();
int h;
h = bmOriginal.getHeight();
Bitmap.Config config = bmOriginal.getConfig();
if(config == null){
config = Bitmap.Config.ARGB_8888;
}
newBitmap = Bitmap.createBitmap(w, h, config);
Canvas newCanvas = new Canvas(newBitmap);
newCanvas.drawBitmap(bmOriginal, 0, 0, null);
Paint paint = new Paint();
float left = maskImgView.getLeft();
float top = maskImgView.getTop();
Log.d(MainActivity.TAG, "left is " + left);
Log.d(MainActivity.TAG, "top is " + top);
newCanvas.drawBitmap(bmMask, left, top, paint);
return newBitmap;
}
}
Code (xml)
<RelativeLayout
android:id="#+id/imgSection"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5"
android:background="#android:color/background_dark">
<TextView
android:id="#+id/before_combie_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="before combine image"
android:textColor="#android:color/white"/>
<ImageView
android:id="#+id/normalImgView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/maskImgView"
android:layout_centerInParent="true"
android:src="#drawable/daffodils"
android:layout_width="100dp"
android:layout_height="60dp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5"
android:background="#android:color/holo_blue_dark">
<TextView
android:id="#+id/after_combie_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="after combine image"
android:textColor="#android:color/white"/>
<ImageView
android:id="#+id/combinedImgView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:text="Take Photo"
android:layout_gravity="center_horizontal"/>
<Button
android:id="#+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Combined Photo"
android:layout_gravity="center_horizontal"/>
My Thought:
I guess the positioning issue occurs in the few lines of code listed below. I just have no idea how to get it right, yet.
float left = maskImgView.getLeft();
float top = maskImgView.getTop();
newCanvas.drawBitmap(bmMask, left, top, paint);
Any help is appreciated!
In this case both of image view in same layout for ex.
<RelativeLayout
android:id="#+id/imgSection"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5"
android:background="#android:color/background_dark">
<TextView
android:id="#+id/before_combie_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="before combine image"
android:textColor="#android:color/white"/>
<ImageView
android:id="#+id/normalImgView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/maskImgView"
android:layout_centerInParent="true"
android:src="#drawable/daffodils"
android:layout_width="100dp"
android:layout_height="60dp" />
------->
RelativeLayout imgSection;
....
....
//On the save button click
imgSection.buildDrawingCache();
imgSection.getDrawingCache();//it will return combine image bitmap
I hope this will help.....
I seem to be having trouble creating a Bitmap from fileUri.
I would like to be able to set this Bitmap to an Imageview for previewing the image, and later adding elements to the image.
Any ideas why the image does not get set properly?
public class FeedActivity extends Fragment implements OnClickListener {
ImageView m_ImageView;
ImageButton btnCamera, btnGallery;
private final String TAG_CAMERA_FRAGMENT = "camera_fragment";
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private Uri fileUri;
public static final int MEDIA_TYPE_IMAGE = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_feed, container, false);
m_ImageView = (ImageView) view
.findViewById(R.id.imageViewFeed);
btnCamera = (ImageButton) view.findViewById(R.id.btn_Camera);
btnCamera.setOnClickListener(this);
btnGallery = (ImageButton) view.findViewById(R.id.btn_Gallery);
btnGallery.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_Camera:
Log.e("CAMERA", "CAMERA BUTTON PRESSED");
takePicture();
break;
case R.id.btn_Gallery:
Log.e("Gallery", "GALLERY BUTTON PRESSED");
break;
}
}
public void takePicture() {
// create Intent to take a picture and return control to the calling
// application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == getActivity().RESULT_OK) {
Log.e("ONACTIVITYRESULT",
"-----------------RESULT_OK----------------");
Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath());
m_ImageView.setImageBitmap(bitmap);
// Bundle bundle = new Bundle();
// bundle.putParcelable("URI", fileUri);
//
// Fragment fragment = new PictureEditActivity();
// fragment.setArguments(bundle);
//
// getFragmentManager()
// .beginTransaction()
// .replace(R.id.contentFragment, fragment,
// TAG_CAMERA_FRAGMENT).commit();
if (fileUri != null) {
Log.e("CAMERA", "Image saved to:\n" + fileUri);
Log.e("CAMERA", "Image path:\n" + fileUri.getPath());
}
} else if (resultCode == getActivity().RESULT_CANCELED) {
Log.e("ONACTIVITYRESULT",
"-----------------RESULT_CANCELLED----------------");
} else {
}
}
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"Pixagram");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("Pixagram", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
}
It appears as if I have found a solution.
http://www.androidhive.info/2013/09/android-working-with-camera-api/
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
m_ImageView.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
I am having a NullPointerException in my android code on this section
String title = titleEt.getText().toString();
String description = descriptionEt.getText().toString();
Log.i("title",title);
Log.i("description",description);
audioRecordPasser.onAudioRecordPass(title, "hiphop", description, fileUri.getPath());
getDialog().dismiss();
The exception is on the line
audioRecordPasser.onAudioRecordPass(title, "hiphop", description, fileUri.getPath());
audioRecordPasser is an interface.
The complete code implementation is
public class UploadFragment extends DialogFragment implements AdapterView.OnItemSelectedListener, View.OnClickListener {
Spinner genres;
ImageView photo;
TextView submit;
String fileName = "";
EditText titleEt, descriptionEt;
private static final String KEY = "choice";
public Uri fileUri; // file url to store image/video
OnAudioRecordPass audioRecordPasser;
public UploadFragment(){
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.fragment_upload, null);
builder.setView(v);
submit = (TextView) v.findViewById(R.id.upload_textView_submit);
genres = (Spinner) v.findViewById(R.id.upload_spinner_genre);
photo = (ImageView) v.findViewById(R.id.upload_imageView_photo);
titleEt = (EditText) v.findViewById(R.id.upload_edittext_title);
descriptionEt = (EditText) v.findViewById(R.id.upload_editText_description);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),
R.layout.ngoma_spinner, getResources().getStringArray(R.array.genres));
dataAdapter
.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
genres.setAdapter(dataAdapter);
genres.setOnItemSelectedListener(this);
submit.setOnClickListener(this);
photo.setOnClickListener(this);
return builder.create();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
private static final int INT_CODE = 1;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.upload_textView_submit:
Log.i("URI", fileUri.getPath());
// audioRecordPasser.onAudioRecordPass(titleEt.getText().toString(),"hiphop",descriptionEt.getText().toString(),fileUri.getPath());
if (validateInput()==false){
Toast.makeText(getActivity(),"Fields cannot be blank.",Toast.LENGTH_SHORT).show();
}
else {
String title = titleEt.getText().toString();
String description = descriptionEt.getText().toString();
Log.i("title",title);
Log.i("description",description);
audioRecordPasser.onAudioRecordPass(title, "hiphop", description, fileUri.getPath());
getDialog().dismiss();
}
break;
case R.id.upload_imageView_photo:
UploadPhotoDialog uploadDialog = new UploadPhotoDialog();
uploadDialog.setTargetFragment(this, INT_CODE);
uploadDialog.show(getActivity().getSupportFragmentManager(), "uploadPhoto");
break;
}
}
/**
* **************************************************************************************************
*/
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static int RESULT_LOAD_IMAGE = 1;
/**
* Select image from gallery
*/
private void selectFromGallery() {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
/**
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "ngoma";
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
/*
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}*/
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// get the file url
//fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Receiving activity result method will be called after closing the camera
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == Activity.RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getActivity().getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getActivity().getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
fileUri = selectedImage;
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
// String picturePath contains the path of selected Image
previewFromGallery(picturePath);
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
Log.i("previewCapturedImage", fileUri.getPath());
photo.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void previewFromGallery(String picturePath) {
photo.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
fileUri = Uri.fromFile(getOutputMediaFile(type));
Log.i("getOutputMediaFileUri", fileUri.getPath());
return fileUri;
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Error creating "
+ IMAGE_DIRECTORY_NAME + " directory.");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
public void choiceSelector(String data) {
if (data.equalsIgnoreCase("camera")) {
captureImage();
} else if (data.equalsIgnoreCase("gallery")) {
selectFromGallery();
}
}
public interface OnAudioRecordPass {
public void onAudioRecordPass(String title, String genre, String description, String photouri);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
audioRecordPasser = (OnAudioRecordPass) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnAudioRecordPass");
}
}
private boolean validateInput() {
if (titleEt.getText().toString().equalsIgnoreCase("") || descriptionEt.getText().toString().equalsIgnoreCase("")) {
return false;
} else {
return true;
}
}
}
Everything runs fine.In my logcat, I can see the values of title and desription and fileUri.getPath() variables.What could be the issue?
The logcat content
10-31 15:42:44.032 4101-4101/ngoma.android.shimba.com.ngoma E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.shimba.android.ngoma.activities.MainActivity.onAudioRecordPass(MainActivity.java:516)
at com.shimba.android.ngoma.fragments.UploadFragment.onClick(UploadFragment.java:101)
at android.view.View.performClick(View.java:3511)
at android.view.View$PerformClick.run(View.java:14105)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4440)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
at dalvik.system.NativeStart.main(Native Method)
The problem is with the parameter fileUri.getPath()
May be this is not properly initialized and as a result its value is null
Check the value of fileUri variable value before passing it to the function.
This will solve your problem
Tried many methods, but did not reach a positive outcome.
In TableLayout has ImageView:
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/photo_layout_background"
android:stretchColumns="*" >
<TableRow
android:background="#color/photo_layoutrow_background"
android:layout_weight="1"
android:layout_marginBottom="4dp"
android:gravity="center" >
<ImageView
android:id="#+id/photo1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginRight="4dp"
android:src="#drawable/icon_photo"
android:background="#color/photo_background"
android:clickable="true"
android:onClick="addPhoto_Click"/>
When you click on ImageView offer standard procedure for obtaining pictures and the file is saved on the SD card:
public void addPhoto_Click(View v){
select_add_photo_id = v.getId();
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, generateFilePhotoUri());
startActivityForResult(takePictureIntent, CAMERA_RESULT);
}
#SuppressLint("SimpleDateFormat")
private Uri generateFilePhotoUri() {
File file = null;
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
file = new File(MEDIA_PATH + String.valueOf(id) + File.separator + timeStamp + ".jpg");
select_add_photo_file = file.getAbsolutePath();
return Uri.fromFile(file);
}
The photo is saved normally stored in variables select_add_photo_id id ImageView on which tapped the select_add_photo_file variable holds the full path to the file photo.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_RESULT) {
if (resultCode == RESULT_OK){
ImageView imgView = (ImageView) findViewById(select_add_photo_id);
imgView.setImageDrawable(Drawable.createFromPath(select_add_photo_file));
}
}
}
But when the file is only get ImageView ImageView with background and increased size. Photography is not loaded. There are no errors.
As still set photos?
after take a phone, in onActivityResult, data.getData may be null, in this case, try data.getExtras()
Bitmap photo = null;
Uri photoUri = data.getData();
String filePath = "";
if (photoUri != null) {
//mFilePath = getRealPathFromURI(photoUri);
filePath = getRealPathFromURI(photoUri);
photo = BitmapFactory.decodeFile(photoUri.getPath());
}
if (photo == null) {
Bundle extra = data.getExtras();
if (extra != null) {
photo = (Bitmap)extra.get("data");
...