camera activity gives null pointer exception - android

in my camera intent:
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
this part gives me a null pointer exception.
can anyone explain why and what need to be changed??
button_1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("android.media.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, TAKE_PICTURE);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
}

Try the following,
public class Camera extends Activity
{
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
WebView webview;
String fileName = "capturedImage.jpg";
private static Uri mCapturedImageURI;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent cameraIntent = new Intent(ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
Random randomGenerator = new Random();randomGenerator.nextInt();
String newimagename=randomGenerator.toString()+".jpg";
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + newimagename);
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//write the bytes in file
try {
fo = new FileOutputStream(f.getAbsoluteFile());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
uri=f.getAbsolutePath();
//this is the url that where you are saved the image
}
}

Related

Cannot see entire string after converting bitmap to string. Black screen displayed

Converting bitmap to string and printing in toast message does not display string. I see the black screen
'MainActivity.java'
public void Upload(View v){
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(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
Log.i("HATA", "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.parse(mCurrentPhotoPath));
mImageView.setImageBitmap(mImageBitmap);
Toast.makeText(getApplicationContext(),imageToString(mImageBitmap),Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I tried all options, Any help is appreciated.

Video recording using Intent saves empty file

This is the code i used to record video from an android device in MP4 format. The file is being created but is of 0 bytes size.
Here is my code :-
Button buttonStart;
File newFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
newFile = File.createTempFile("vid", ".mp4", Environment.getExternalStorageDirectory());
} catch (IOException e) {
e.printStackTrace();
}
Uri outputFileUri = Uri.fromFile(newFile);
Intent record = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
record.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(record, 5);
}
});
}
protected void initUI(){
buttonStart = (Button) findViewById(R.id.buttonRecord);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 5){
if(resultCode == RESULT_OK){
try {
newFile = File.createTempFile("vid", ".mp4", Environment.getExternalStorageDirectory());
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this, "Video Captured Successfully...!!", Toast.LENGTH_LONG).show();
}
}
}
I don't understand what has gone wrong.
Can anybody help me ...
Thanks
String strVideoPath=null;//define global variable
to open an Intetn for video recording
void displayCamera() {
File imagesFolder = new File(Environment
.getExternalStorageDirectory(), getResources()
.getString(R.string.app_name) + "foldername");
try {
imagesFolder.mkdirs();
} catch (Exception e) {
}
File f_image = new File(imagesFolder, new Date().getTime() + ".mp4");
Uri uriSavedVideo = Uri.fromFile(f_image);
Intent intent = new Intent(
MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedVideo);
strVideoPath = f_image.getAbsolutePath();
try {
startActivityForResult(intent, 111);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
catch it on OnActivity Result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 111) {
if (resultCode == mActivity.RESULT_OK) {
//do stuff here on success
}else{
strVideoPath=null;
}
}
}
first u need to create a directory
File newFileLocation;
try {
newFileLocation = new File(Environment.getExternalStorageDirectory(), "videoyo");
imagesFolder.mkdirs();
newFile = new File(newFileLocation , "vid" + ".mp4");
} catch (Exception e) {
}

Upload image to server from gallary or camera android

i have a Activity for Upload image from gallary or camera to server.image upload from camera is fine but upload from gallary is not done.i have a error showing
BitmapFactory﹕ Unable to decode stream: FileNotFoundException
i want to do when i pick up the image from gallary it is shown in other Activity on image view.
i don't know how to get fileuri for gallary please help me.
my code:
loadimage = (ImageView) findViewById(R.id.profilpic);
loadimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
/* Intent i = new Intent(Tab1.this, ImageMain.class);
startActivity(i);*/
// selectImageFromGallery();
AlertDialog.Builder builder = new AlertDialog.Builder(Tab1.this);
builder.setMessage("Select Image From")
.setCancelable(true)
.setPositiveButton("camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
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_REQUEST);
}
})
.setNegativeButton("gallary", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
Hear is my onActiivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
launchUploadActivity(true);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
else if(requestCode==RESULT_LOAD_IMAGE){
if (resultCode==RESULT_OK){
launchUploadActivity(true);
}
}
}
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(Tab1.this,UploadAvtivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
Here is the Code piece for Taking a Picture through Default Camera (here I implemented Intent to to fetch the image). After that store it to SD card(here a new file will be created and the newly taken image will be stored ); and if you don't want to store then remove the saving part from code. After that you can use the file path for your upload purpose. You can then refer it and change to get the path as your wish.
In the class area put these lines
final int TAKE_PHOTO_REQ = 100;
String file_path = Environment.getExternalStorageDirectory()
+ "/recent.jpg";//Here recent.jpg is your image name which will going to take
After that invoke the camera by putting these line in calling method.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PHOTO_REQ);
then add this method in your Activity to get the picture and save it to sd card and you can invoke your upload method from here to upload the image by knowing its path.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PHOTO_REQ: {
if (resultCode == TakePicture.RESULT_OK && data != null) {
Bitmap srcBmp = (Bitmap) data.getExtras().get("data");
// ... (process image if necesary)
imageView.setImageBitmap(srcBmp);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
srcBmp.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
// you can create a new file name "test.jpg" in sdcard folder.
File f = new File(file_path);
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// write the bytes in file
FileOutputStream fo = null;
try {
fo = new FileOutputStream(f);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// remember close de FileOutput
try {
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("take-img", "Image Saved to sd card...");
// Toast.makeText(getApplicationContext(),
// "Image Saved to sd card...", Toast.LENGTH_SHORT).show();
break;
}
}
}
}
Hope this will be helpful for you and others too .. thanks

Android: Resolution issue while saving image into gallery

I've managed to programmatically take a photo from the camera, then display it on an imageview, and then after pressing a button, saving it on the Gallery.
It works, but the problem is that the saved photo are low resolution.. WHY?!
I took the photo with this code:
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
Then I save the photo on a var using :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
thumbnail = (Bitmap) data.getExtras().get("data");
}
}
and then after displaying it on an imageview, I save it on the gallery with this function:
public void SavePicToGallery(Bitmap picToSave, File savePath){
String JPEG_FILE_PREFIX= "PIC";
String JPEG_FILE_SUFFIX= ".JPG";
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File filePath = null;
try {
filePath = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, savePath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream out = null;
try {
out = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
picToSave.compress(CompressFormat.JPEG, 100, out);
try {
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Add the pic to Android Gallery
String mCurrentPhotoPath = filePath.getAbsolutePath();
MediaScannerConnection.scanFile(this,
new String[] { mCurrentPhotoPath }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
}
I really can't figure out why it lose so much quality while saved..
Any help please ? Thanks..
The photo you are displaying in the ImageView is a thumbnail :
data.getExtras().get("data");
Are you calling the method :
public void SavePicToGallery(Bitmap picToSave, File savePath)
with the thumbnail ?
Here you have all the steps describe to do what you want :
http://developer.android.com/training/camera/photobasics.html
data.getExtras().get("data") only get thumbnail.
To do it properly, you have to declare global uri variable
Uri imageCapturedUri ;
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
imageCaptureUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageCaptureUri);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
// mImageCaptureUri is your Uri
}
}

why my file type is not supporting to send taken picture as MMS

I am implementing an MMS application for that i am using camera also.Main theme of main application was take picture using device camera ater that send that image as MMS to specified number.But while attahing the image i am getting error warning like
Unable to attach File not support
Please help to resolve my problem.
Thanks,
public class MMS extends Activity implements OnClickListener {
int TAKE_PHOTO_CODE = 0;
public static int count=0;
EditText preLoc,comeby;
Button ok,capture;
String photo;
String dir;
boolean GPS,flag;
String cityName=null;
String SubThorugh = null;
Intent i;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mms);
preLoc = (EditText)findViewById(R.id.etPreLoc1);
comeby = (EditText)findViewById(R.id.etComing1);
ok = (Button)findViewById(R.id.bOK1);
capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(this);
ok.setOnClickListener(this);
i = getIntent();
GPS = i.getBooleanExtra("GPSneed", false);
ok.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId())
{
case R.id.btnCapture:
capturePicture();
break;
case R.id.bOK1:
sendMMS();
preLoc.setText(cityName+SubThorugh);
break;
}
}
private void sendMMS() {
// TODO Auto-generated method stub
try {
Uri uri = Uri.parse(photo);
Intent i = new Intent(Intent.ACTION_SEND);
//i.putExtra("address",etnum.getText().toString());
//i.putExtra("sms_body",etmsg.getText().toString());
i.putExtra(Intent.EXTRA_STREAM,uri);
i.setType("image/*");
startActivity(i);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.d("CameraDemo", "Pic saved");
Toast.makeText(getApplicationContext(), "photo saved as: "+photo, Toast.LENGTH_LONG).show();
}
}
private void capturePicture() {
//here,we are making a folder named picFolder to store pics taken by the camera using this application
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
// here,counter will be incremented each time,and the picture taken by camera will be stored as 1.jpg,2.jpg and likewise.
count++;
String file = dir+count+".jpg";
photo = file;
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}

Categories

Resources