i have create an android application that will capture picture and save in sdcard folder,now i want to save the image with a custom name.
import java.io.ByteArrayOutputStream;
import android.view.Menu;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView) this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI.getPath());
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, "new-photo-name.jpg");
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
MediaStore.Images.Media.insertImage(getContentResolver(), photo,
null, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
}
}
here is the code which i have used for capturing the image and save them in the sd card folder,please help me to save the image with a specific name for eg:android.jpeg
File outFile = new File(Environment.getExternalStorageDirectory(), "myname.jpeg");
FileOutputStream fos = new FileOutputStream(outFile);
photo.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
you would also need to add Permission in Android Manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
the snippet will save the content of photo inside /sdcard with the name "myname.jpeg"
You need to put fileName as Intent Extras -
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, "android.jpg");
this article maybe useful, try it.
& this as well, the only different that he used the date as a default name.
change it.
It usually works :)
Related
I am trying to make a simple text editor for Android in Java. I run into a problem, when tring to open a file.
In this line of my code
File file = new File(getExternalFilesDir(filepath), filename);
I got a null pointer exception:
java.lang.NullPointerException: name == null
at java.io.File.<init>(File.java:150)
at java.io.File.<init>(File.java:124)
at my.app.texteditor.MainActivity$1.onClick(MainActivity.java:31)
and my app crashes, leaving the filepicker on my android device open.
For me (after some time of trying to debug my code) it seems that the
protected void onActivityResult(int requestCode, int resultCode, Intent data)
function is never called and thus the filepath and filename are never assigned, which generates the exception. Hovever I am not sure whether I detected the problem correctly and I dont know how to fix it.
Here is the (full) code of my main activity - the one where I am trying to open a file:
package my.app.texteditor;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
public class MainActivity extends AppCompatActivity {
String filepath, filename, folder;
private static final int PICKFILE_RESULT_CODE = 1;
private static int PICKER_RESULT = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button OpenButton = (Button) findViewById(R.id.OpenButton);
OpenButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent getContent = new Intent(Intent.ACTION_GET_CONTENT);
getContent.setType("text/*");
startActivityForResult(getContent, PICKFILE_RESULT_CODE);
File file = new File(getExternalFilesDir(filepath), filename);
Intent openIntent = new Intent(MainActivity.this, ShowFile.class);
openIntent.putExtra("my.app.file", file);
startActivity(openIntent);
}
});
Button NewButton = (Button) findViewById(R.id.NewButton);
NewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent newIntent = new Intent(MainActivity.this, ShowFile.class);
startActivity(newIntent);
}
});
if (!StorageHandler.isExternalStorageAvailable() || StorageHandler.isExternalStorageReadOnly()) {
OpenButton.setEnabled(false);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
PICKER_RESULT = resultCode;
if (requestCode == PICKFILE_RESULT_CODE) {
if (resultCode == RESULT_OK) {
filepath = data.getData().getPath();
filename = data.getData().getLastPathSegment();
int lastPos = filepath.length() - filename.length();
folder = filepath.substring(0, lastPos);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
When I put this part of my code:
File file = new File(getExternalFilesDir(filepath), filename);
Intent openIntent = new Intent(MainActivity.this, ShowFile.class);
openIntent.putExtra("my.app.file", file);
startActivity(openIntent);
in an if statement, so it will be executed only if the PICKER_RESULT variable is changed in onActivityResult function - like this:
if(PICKER_RESULT!=-1) {
File file = new File(getExternalFilesDir(filepath), filename);
Intent openIntent = new Intent(MainActivity.this, ShowFile.class);
openIntent.putExtra("my.app.file", file);
startActivity(openIntent);
}
then my android device opens the filepicker, app DOES NOT crash, but I am not able to open a file - the PICKER_RESULT is still set to -1.
So my quesion is, why is the onActivityResult function never called?
You're trying to use the result of the activity in the onClick event handler. This won't work because the activity is started asynchronously. The event handler will keep running until the end, and only then the activity starts.
All of the code that depends on the activity result should be in
onActivityResult (or a method that's called from it)
startActivityForResult(getContent, PICKFILE_RESULT_CODE);
// MOVE THIS TO onActivityResult
File file = new File(getExternalFilesDir(filepath), filename);
Intent openIntent = new Intent(MainActivity.this, ShowFile.class);
openIntent.putExtra("my.app.file", file);
startActivity(openIntent);
Good afternoon, I have the following code in Android for take a photo and show in ImageView, the file photo is in the path when I check with filemanager, but dont show in ImageView and have the following message:
E/BitmapFactory: Unable to decode stream:
java.io.FileNotFoundException:
/storage/emulated/0/S3TAUDIT/photos/S3actual.png (No such file or
directory)
Please I need your help for finish my app. I use API 25 Android 7, permissions, options.inJustDecodeBounds. I have reviewed all posts with this error type and dont find solutions.
Thanks a lot.
package com.example.jorge.s3taudit;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import java.io.File;
public class PICSSECTOR extends AppCompatActivity {
private final String carpeta_raiz="S3TAUDIT/";
private final String ruta_imagen=carpeta_raiz+"photos";
String path;
ImageView pics1actual;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picssector);
public void pics1actual(View view) {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
File pics1actualpng= new File(Environment.getExternalStorageDirectory(),ruta_imagen);
boolean isCreada =pics1actualpng.exists();
String nombre_imagen ="";
if (isCreada == false){
isCreada = pics1actualpng.mkdirs();
nombre_imagen = "S3actual.png";
}
if (isCreada==true){
nombre_imagen = "S3actual.png";
}
path = Environment.getExternalStorageDirectory()+File.separator +ruta_imagen+File.separator+ nombre_imagen;
File pics1actual =new File(path);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(pics1actual));
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
MediaScannerConnection.scanFile(this, new String[]{path}, null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String s, Uri uri) {
Log.i("RUTA de almacenamiento", "Path: " + path);
}
});
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
ImageView pics1actual = (ImageView) findViewById(R.id.s1actual);
Bitmap bitmap = BitmapFactory.decodeFile(path,options);
pics1actual.setImageBitmap(bitmap);
}
}
}
The xml only for this action is:
<ImageView
android:id="#+id/s1actual"
android:layout_width="0dp"
android:layout_height="150dp"
android:layout_margin="4dp"
android:layout_weight="1"
android:background="#DDDDDD" />
<Button
android:id="#+id/ButtonPICS1actual"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawableStart="#drawable/ic_stat_name"
android:onClick="pics1actual"
android:text="PHOTO"
android:textSize="20dp" />
This image I have in Debugger
So I've managed to get a button to open a pdf file using an intent, however when i run the app and press the button it says "Cannot display PDF". Can anyone help me out as to where exactly the code goes wrong?
Here is the my activity:
package com.example.android.practiceapp;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import java.io.File;
public class promotions extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_promotions);
final Button button = (Button) findViewById(R.id.earlybird);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/pictures/Early_Bird_Bonus_Rules");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent1 = Intent.createChooser(intent, "Open With");
try {
startActivity(intent1);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
}
});
}
}
I am absolutely new to Android as well as Java (only some basic knowledge). I am trying to develop a simple app as per a youtube video. In this app, I have a button which is clickable and call the method launchCamera(). The image captured by the camera has to be displayed in the ImageView.
PROBLEM: I installed the .apk file in my mobile. When I click the "Take Photo" button, my camera starts. When I capture a image from my camera and save it, that image gets displayed in the ImageView only for a second (even less then a second). How can I keep that photo in the ImageView till the user does not press the "Take Photo" button again?
UPDATE: With the same code, I just noticed something strange. Mostly the image captured while holding the phone vertically rotates itself inside the ImageView and disappears. But sometimes it stays in the ImageView vertically and doesn't get disappeared till the "Take Photo" button is pressed again (Desired case).
My Code:
package com.siddexample.buttonimage;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.content.pm.PackageInfo;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class ButtonImageMainActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView siddImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button_image_main);
Button siddButton = (Button) findViewById(R.id.siddButton);
siddImageView = (ImageView) findViewById(R.id.siddImageView);
}//////-------------///////////////
public void launchCamera(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Take a picture by your intent
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
siddImageView.setImageBitmap(photo);
}
}
}
Try using this tutorial here , as follows:
Taking a picture:
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);
}
Receiving the picture:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} 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();
}
}
}
and displaying the picture:
/*
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// 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);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
As #stkent said, maybe the onActivityResult is called twice.
I noticed the default camera activity I call on a Droid X is different looking than the one on my Droid and Nexus One. After selecting "OK" on the Droid and Nexus One, the activity would finish - the Droid X has a "Done" button (which takes you back to the Camera, instead of finishing the activity), and the only way to get to the screen I want is to hit the "Back" button.
Here is the class that works on Android 2.2/2.3, but not for Droid X's:
package com.android.xxx;
import java.io.File;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Window;
public class CameraView extends MenusHolder {
protected String _path;
protected boolean _taken;
protected static final String PHOTO_TAKEN = "photo_taken";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.create_event_view);
/*
* save to sd
*/
File imageDirectory = new File(
Environment.getExternalStorageDirectory() + "/MyPath/");
imageDirectory.mkdirs();
/*
* temp image overwrites each time for space
*/
_path = Environment.getExternalStorageDirectory()
+ "/MyPath/temporary_image.jpg";
startCameraActivity();
}
protected void startCameraActivity() {
File file = new File(_path);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (resultCode) {
case 0:
setResult(5);
finish();
break;
case -1:
onPhotoTaken();
break;
}
}
protected void onPhotoTaken() {
_taken = true;
setResult(0);
finish();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(CameraView.PHOTO_TAKEN, _taken);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.getBoolean(CameraView.PHOTO_TAKEN)) {
onPhotoTaken();
}
}
}
I solved this with a really really ugly workaround. I coded two functions to read and write files from sdcard (taken from here: http://www.sgoliver.net/blog/?p=2035).
private boolean readFile() {
try
{
File sd_path = Environment.getExternalStorageDirectory();
File f = new File(sd_path.getAbsolutePath(), "lock_camera_oncreate");
BufferedReader fin =
new BufferedReader(
new InputStreamReader(
new FileInputStream(f)));
String text = fin.readLine();
fin.close();
Log.e("Files", "Reading file");
return true;
}
catch (Exception ex)
{
Log.e("Files", "Error reading file from SD Card");
return false;
}
}
private void createFile() {
try
{
File sd_path = Environment.getExternalStorageDirectory();
File f = new File(sd_path.getAbsolutePath(), "lock_camera_oncreate");
OutputStreamWriter fout =
new OutputStreamWriter(
new FileOutputStream(f));
fout.write("Semaphore test.");
fout.close();
Log.e("Files", "File writed");
}
catch (Exception ex)
{
Log.e("Files", "Error reading file from SD Card");
}
}
Then, in onCreate function, I make this:
public void onCreate(Bundle savedInstanceState) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
super.onCreate(savedInstanceState);
if(readFile() == true)
{
File sd_path = Environment.getExternalStorageDirectory();
File f = new File(sd_path.getAbsolutePath(), "lock_camera_oncreate");
f.delete();
Intent intent = this.getIntent();
this.setResult(RESULT_OK, intent);
return;
}
createFile();
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCurrentImagePath)));
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
The setRequestedOrientation call solves the issue when you are using your app in portrait mode, but when camera is launched, you put the mobile in landscape and then shoot the photo.
Then, the ugly readFile thing checks if a lock_camera_oncreate file exists and if it's true,
then an additional onCreate call happened, so delete file and RETURN from this activity.
If activity advances, means the file's not created and there is only one camera activity running.
Hope it helps, it's ugly but worked for me :D
Dude... it's just a bug. I had the same problem and there's no way to workaround that. It sometimes work, and sometimes it does not. I asked the Motorola's guy for help and they said that there's no support for those Android images.