Android getting URI from Camera - java

I am having an issue when taking a photo with the camera on my Nexus 5. I can take photos from the gallery no problem and save them to the back end. However when I try to take a picture using the camera, after I take the picture and select the tick, then the app crashes...
I can see that the intent passed to the onActivityResult() is empty but I don't know how to fix this. Can anyone help? thanks.
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.khackett.runmate.R;
import com.khackett.runmate.utils.FileHelper;
import com.khackett.runmate.utils.ParseConstants;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MyProfileFragment extends Fragment implements View.OnClickListener {
public static final String TAG = MyProfileFragment.class.getSimpleName();
protected Button mTakePicture;
protected Button mChoosePicture;
/**
* Default constructor
*/
public MyProfileFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_my_profile, container, false);
mTakePicture = (Button) rootView.findViewById(R.id.takePictureButton);
mChoosePicture = (Button) rootView.findViewById(R.id.choosePictureButton);
mTakePicture.setOnClickListener(this);
mChoosePicture.setOnClickListener(this);
return rootView;
}
/**
* Called when a view has been clicked.
*
* #param v The view that was clicked.
*/
#Override
public void onClick(View v) {
// Switch statement to select which action to take depending on button/text pressed
switch (v.getId()) {
case R.id.takePictureButton:
takeCameraPicture();
break;
case R.id.choosePictureButton:
chooseGalleryPicture();
break;
default:
System.out.println("Problem with input");
}
}
public static final int TAKE_PHOTO_REQUEST = 1888;
public static final int PICK_PHOTO_REQUEST = 1888;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1888;
// member variable to store the media type as a URI, that can be stored in multiple places
// Uri = uniform resource identifier
protected Uri mMediaUri;
public void takeCameraPicture() {
// Take picture
// use an existing camera app on the phone by starting an intent
// declare intent to capture a photo using whatever camera app is available
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// after invoking the camera,
mMediaUri = getOutputMediaFileUri();
// check that a null value is not returned
if (mMediaUri == null) {
// display an error
Toast.makeText(getActivity(), R.string.error_external_storage, Toast.LENGTH_LONG).show();
} else {
// to add extra data to an intent, use the putExtra() method
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mMediaUri);
// start an activity for a result so that the activity exits and returns a result back for us
// ie, the main activity will wait for the result
startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
}
}
public void chooseGalleryPicture() {
// Choose picture
Intent choosePhotoIntent = new Intent(Intent.ACTION_GET_CONTENT);
// need to specify which type of action we want to get - an image in this case
choosePhotoIntent.setType("image/*");
startActivityForResult(choosePhotoIntent, PICK_PHOTO_REQUEST);
}
private Uri getOutputMediaFileUri() {
// To be safe, you should check that the SD card / external storage is mounted
// using Environment.getExternalStorageState() before doing this.
// see method below...
if (isExternalStorageAvailable()) {
String appName = MyProfileFragment.this.getString(R.string.app_name);
// get the Uri
// Get the external storage directory - we want to return a file object
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), appName);
// Create our subdirectory
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdir()) {
Log.e(TAG, "Failed to create directory");
return null;
}
}
// Create a file to hold the image
File mediaFile;
// get the current date and time
Date now = new Date();
// convert the date and time into a String datetimestamp
// see http://developer.android.com/guide/topics/media/camera.html#saving-media for the methods used
// need to append a timestamp to make it unique - otherwise it will overwrite the previous photo
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(now);
String path = mediaStorageDir.getPath() + File.separator;
// create a new file using the constructor that takes a name
mediaFile = new File(path + "IMG_" + timestamp + ".jpg");
Log.d(TAG, "File: " + Uri.fromFile(mediaFile));
// Return the files URI
Log.d(TAG, "Returning the files URI");
return Uri.fromFile(mediaFile);
} else {
return null;
}
}
/**
* check if external storage is available on the users device
*
* #return
*/
private boolean isExternalStorageAvailable() {
// find out what state external storage is in
String state = Environment.getExternalStorageState();
// if external storage is available, return true,
if (state.equals(Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (data == null) {
Log.d(TAG, "Data is null");
Toast.makeText(getActivity(), getString(R.string.general_error), Toast.LENGTH_LONG).show();
} else {
Log.d(TAG, "Data: " + data);
// the intent has data, so set the media uri
Log.d(TAG, "adding the data using the getData() method");
mMediaUri = data.getData();
Log.d(TAG, "Media Uri: " + mMediaUri);
}
// ParseUser.getCurrentUser().put("profilePic", mMediaUri);
saveImageToParse();
}
} else if (resultCode != Activity.RESULT_CANCELED) {
Log.d(TAG, "Problem getting the picture from gallery");
// Toast.makeText(getActivity(), R.string.general_error, Toast.LENGTH_LONG).show();
}
}
public void saveImageToParse() {
Log.d(TAG, "entering saveImageToParse() method");
byte[] fileBytes = FileHelper.getByteArrayFromFile(getActivity(), mMediaUri);
fileBytes = FileHelper.reduceImageForUpload(fileBytes);
String fileName = FileHelper.getFileName(getActivity(), mMediaUri, "file");
ParseFile file = new ParseFile(fileName, fileBytes);
ParseUser.getCurrentUser().put("profilePic", file);
ParseUser.getCurrentUser().saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Log.d(TAG, "Image saved successfully");
// myObjectSavedSuccessfully();
} else {
Log.d(TAG, "Image not saved");
// myObjectSaveDidNotSucceed();
}
}
});
}
.
package com.khackett.runmate.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;
import org.apache.commons.io.IOUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
// https://github.com/treehouse/treehouse_android_utilities
public class FileHelper {
public static final String TAG = FileHelper.class.getSimpleName();
public static final int SHORT_SIDE_TARGET = 1280;
public static byte[] getByteArrayFromFile(Context context, Uri uri) {
byte[] fileBytes = null;
InputStream inStream = null;
ByteArrayOutputStream outStream = null;
Log.d(TAG, "in the getByteArrayFromFile() method");
if (uri.getScheme() != null && uri.getScheme().equals("content")) {
try {
Log.d(TAG, "entering try to set inputstream");
inStream = context.getContentResolver().openInputStream(uri);
outStream = new ByteArrayOutputStream();
byte[] bytesFromFile = new byte[1024 * 1024]; // buffer size (1 MB)
int bytesRead = inStream.read(bytesFromFile);
while (bytesRead != -1) {
outStream.write(bytesFromFile, 0, bytesRead);
bytesRead = inStream.read(bytesFromFile);
}
fileBytes = outStream.toByteArray();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} finally {
try {
inStream.close();
outStream.close();
} catch (IOException e) { /*( Intentionally blank */ }
}
} else {
try {
File file = new File(uri.getPath());
FileInputStream fileInput = new FileInputStream(file);
fileBytes = IOUtils.toByteArray(fileInput);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
}
return fileBytes;
}
public static byte[] reduceImageForUpload(byte[] imageData) {
Bitmap bitmap = ImageResizer.resizeImageMaintainAspectRatio(imageData, SHORT_SIDE_TARGET);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
byte[] reducedData = outputStream.toByteArray();
try {
outputStream.close();
} catch (IOException e) {
// Intentionally blank
}
return reducedData;
}
public static String getFileName(Context context, Uri uri, String fileType) {
String fileName = "uploaded_file.";
if (fileType.equals(ParseConstants.TYPE_IMAGE)) {
fileName += "png";
} else {
// For video, we want to get the actual file extension
if (uri.getScheme().equals("content")) {
// do it using the mime type
String mimeType = context.getContentResolver().getType(uri);
int slashIndex = mimeType.indexOf("/");
String fileExtension = mimeType.substring(slashIndex + 1);
fileName += fileExtension;
} else {
fileName = uri.getLastPathSegment();
}
}
return fileName;
}
}
.
09-01 20:15:49.322 23271-23271/com.khackett.runmate E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.khackett.runmate, PID: 23271
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=67424, result=-1, data=Intent { }} to activity {com.khackett.runmate/com.khackett.runmate.ui.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3574)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
at android.app.ActivityThread.access$1300(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference
at com.khackett.runmate.utils.FileHelper.getByteArrayFromFile(FileHelper.java:29)
at com.khackett.runmate.ui.MyProfileFragment.saveImageToParse(MyProfileFragment.java:233)
at com.khackett.runmate.ui.MyProfileFragment.onActivityResult(MyProfileFragment.java:210)
at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:165)
at android.app.Activity.dispatchActivityResult(Activity.java:6192)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3570)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
            at android.app.ActivityThread.access$1300(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

From the log, and your code, you can track that it is mMediaUri being null.
This should be caused by activity recreate because of screen rotation, for example, if your app usually run in Portrait, while the camera force to Landscape or you rotated when you use camera.
Anyway to solve this, you have to save the mMediaUrl and restore it in onCreate, modify your Fragment like this:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current state
savedInstanceState.putString("media_url", mMediaUrl.toString());
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mMediaUrl = Uri.parse(savedInstanceState.getString("media_url"));
}
}
Edit:
noticed another problem, change the followings:
public static final int TAKE_PHOTO_REQUEST = 1889;
public static final int PICK_PHOTO_REQUEST = 1888;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_PHOTO_REQUEST) {
if (data == null) {
Log.d(TAG, "Data is null");
Toast.makeText(getActivity(), getString(R.string.general_error), Toast.LENGTH_LONG).show();
} else {
Log.d(TAG, "Data: " + data);
// the intent has data, so set the media uri
Log.d(TAG, "adding the data using the getData() method");
mMediaUri = data.getData();
Log.d(TAG, "Media Uri: " + mMediaUri);
}
// ParseUser.getCurrentUser().put("profilePic", mMediaUri);
saveImageToParse();
} else if(requestCode == TAKE_PHOTO_REQUEST) {
saveImageToParse();
}
} else if (resultCode != Activity.RESULT_CANCELED) {
Log.d(TAG, "Problem getting the picture from gallery");
// Toast.makeText(getActivity(), R.string.general_error, Toast.LENGTH_LONG).show();
}
}

Related

Bundle is always null no matter what I do

Everytime I try to go between activities, I save the editText texts because user experience and all that, but for some reason, while intents get through no problem, the savedinstanceState just won't ever be not null. I've added the onSave and onRestore methods, overrided them, did what had to be done inside, yet it is always null. What am I missing here?
package com.gmproxy.pastilarma;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import com.gmproxy.DAO.PathologyUserRepository;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Entities.User;
import com.gmproxy.Util.ImageConverter;
import com.gmproxy.ViewModels.UserViewModel;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class UserAddScreen extends AppCompatActivity {
Button gotoBack, addObservation, saveUser, addPathologies;
EditText addUsername, addSurname, addAge, addRoomNumber;
Spinner addGender;
ImageView selectImage;
String obs;
Pathology paths;
Context context;
UserViewModel userViewModel;
int pathAct = 0;
int obsAct = 0;
PathologyUserRepository paUsRe;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
context = this.getApplicationContext();
pathAct = getIntent().getIntExtra("path-record", 0);
obsAct = getIntent().getIntExtra("obs-record", 0);
paUsRe = new PathologyUserRepository(this.getApplication());
setContentView(R.layout.activity_user_add_screen);
gotoBack = findViewById(R.id.GotoBack);
addObservation = findViewById(R.id.AddObservation);
saveUser = findViewById(R.id.SaveUser);
addPathologies = findViewById(R.id.AddPathologies);
addUsername = findViewById(R.id.AddUsername);
addSurname = findViewById(R.id.AddSurname);
addAge = findViewById(R.id.AddAge);
addRoomNumber = findViewById(R.id.AddRoomNumber);
addGender = findViewById(R.id.AddGender);
selectImage = findViewById(R.id.SelectImage);
if (pathAct == 1 || obsAct == 1 && savedInstanceState!=null) {
onRestoreInstanceState(savedInstanceState);
}
if (savedInstanceState == null){
Log.println(Log.INFO,"Test","El bundle está vacio");
}
userViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(UserViewModel.class);
/*
From this line to 94, we create the spinner, since there's only two options there really is no need of poblating the list from the database.
*/
List<String> genderList = new ArrayList<>();
genderList.add("M");
genderList.add("F");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner, genderList);
adapter.setDropDownViewResource(R.layout.spinner);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
addGender.setAdapter(adapter);
addGender.setSelection(0);
if (savedInstanceState == null){
obs = intent.getStringExtra("observation");
} else {
obs = savedInstanceState.getString("Observacion-usuario");
}
if (obs != null){
Log.println(Log.INFO,"test obs", obs);
}
paths = (Pathology) intent.getSerializableExtra("paths");
}
public void gotoBack(View view) {
Intent mainAct = new Intent(UserAddScreen.this, UserListScreen.class);
startActivity(mainAct);
finish();
}
public void addObservation(View view) {
Intent mainAct = new Intent(UserAddScreen.this, UserObservationScreen.class);
startActivity(mainAct);
finish();
}
public void addPathology(View view) {
Intent mainAct = new Intent(UserAddScreen.this, PathologiesSearchScreen.class);
startActivity(mainAct);
finish();
}
/**
* This saves all recorded data for when we come back to the activity
* #param savedInstanceState
*/
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
if (!addUsername.getText().toString().equals("")) {
savedInstanceState.putString("Nombre_usuario", addUsername.getText().toString());
}
if (!addSurname.getText().toString().equals("")) {
savedInstanceState.putString("Apellido_usuario", addSurname.getText().toString());
}
if (!addAge.getText().toString().equals("")) {
savedInstanceState.putString("Edad_usuario", addAge.getText().toString());
}
if (!addRoomNumber.getText().toString().equals("")) {
savedInstanceState.putString("Habitacion_usuario", addRoomNumber.getText().toString());
}
savedInstanceState.putInt("Sexo_usuario", addGender.getSelectedItemPosition());
if (obs != null){
savedInstanceState.putString("Observacion-usuario", obs);
}
if (paths != null){
savedInstanceState.putSerializable("Patologia-usuario", paths);
}
super.onSaveInstanceState(savedInstanceState);
Log.println(Log.INFO,"Guardado","guardado");
}
/**
* This loads up all recorded things in the view
* #param savedInstanceState
*/
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
addUsername.setText(savedInstanceState.getString("Nombre_usuario"));
addSurname.setText(savedInstanceState.getString("Apellido_usuario"));
addAge.setText(savedInstanceState.getString("Edad_usuario"));
addRoomNumber.setText(savedInstanceState.getString("Habitacion_usuario"));
addGender.setSelection(savedInstanceState.getInt("Sexo_usuario"));
obs = savedInstanceState.getString("Observacion-usuario");
paths = (Pathology) savedInstanceState.getSerializable("Patologia-usuario");
}
/*
The next two methods are for
A: Opening either the camera, gallery, or getting a picture from assets
B: Actually selecting the image and making it show in the imageButton
*/
public void selectImageAction(View view) {
final CharSequence[] options = {"Hacer una foto", "Elegir de la galería", "Usar una genérica", "Cancelar"};
AlertDialog.Builder builder = new AlertDialog.Builder(UserAddScreen.this);
builder.setTitle("¡Añade una foto!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Hacer una foto")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivity(intent);
finish();
} else if (options[item].equals("Elegir de la galería")) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivity(intent);
finish();
} else if (options[item].equals("Cancelar")) {
dialog.dismiss();
} else if (options[item].equals("Usar una genérica")) {
selectImage.setImageResource(R.drawable.ic_user_generic_foreground);
selectImage.setBackgroundResource(R.drawable.ic_user_generic_foreground);
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
selectImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, System.currentTimeMillis() + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("..******************...", picturePath + "");
ImageView viewImage;
selectImage.setImageBitmap(thumbnail);
}
}
}
/**
* Actually creates the user in the database
* #param view
*/
public void saveUser(View view) {
//Just this to turn the image into a blob
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.id.SelectImage);
ImageConverter imgCon = new ImageConverter();
byte[] bytearray = imgCon.bitmapToBiteArray(bitmap);
if (addUsername.getText().toString() != null || addSurname.getText().toString() != null
|| addAge.getText().toString() != null || addRoomNumber.getText().toString() != null){
Toast.makeText(this, "Usuario creado.", Toast.LENGTH_SHORT).show();
User user = new User(addUsername.getText().toString(), addSurname.getText().toString(), addAge.getText().toString(),
Integer.parseInt(addRoomNumber.getText().toString()), addGender.getSelectedItem().toString(), obs, bytearray);
userViewModel.insert(user);
paUsRe.insertObject(userViewModel.getIdByNameAndSurname(user.getUser_name(), user.getUser_surname()), paths.getId_pathology());
Toast.makeText(this, "Patología " + paths.getPathologyName() + " añadida", Toast.LENGTH_SHORT).show();
Intent mainAct = new Intent(UserAddScreen.this, UserListScreen.class);
startActivity(mainAct);
finish();
} else {
Toast.makeText(this, "Por favor, introduce todos los parámetros necesarios.", Toast.LENGTH_SHORT).show();
}
}
}
onSaveInstanceState() is called right before your activity is about to be killed or restarted because of memory pressure or screen orientation change. Since you are just switching between activities, onSaveInstance() is not called thus the null instance. Wound suggest SharedPreference instead

External storage: can't query a file that I have read access to

I am using a "ACTION_OPEN_DOCUMENT" intent to choose a file and open it.
This works just fine when I go to read the file.
However, when the file resides on EXTERNAL storage, and I run a query to obtain the file name, my program crashes. If the file resides on INTERNAL storage, I have no issues.
I DO have (and check for) external storage access permissions.
I have the query enclosed in a try{}, but the exception is not caught. I am developing on a Chrome book, so I am unable to run the debugger on it. But I have isolated the issue to the result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); statement.
I know that access to files on external storage has been limited, but I would think that if I can read a file that I should also be able to query it as well.
Here is my code:
package com.muddco.demo3;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
Activity mAct;
TextView rvalue, fnamevalue;
Button btn1, btn2;
Uri fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
rvalue = findViewById(R.id.readResult);
fnamevalue = findViewById(R.id.textView2);
mAct = this;
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
* Launch a file picker
*/
Intent intent = new Intent();
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Select a GPX file"), 1);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
* Get and display file name
*/
String fname = getFileName(fileUri);
fnamevalue.setText(fname);
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted and now can proceed
Toast.makeText(MainActivity.this, "Permission granted", Toast.LENGTH_SHORT).show();
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
}
return;
}
// add other cases for more permissions
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
InputStream inputStream = null;
Uri uri = null;
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
// Process GPX file
uri = data.getData();
try {
inputStream = getBaseContext().getContentResolver().openInputStream(uri);
rvalue.setText(readFile(inputStream));
} catch (FileNotFoundException e) {
Toast.makeText(this, "File not found: " + uri.toString(), Toast.LENGTH_SHORT).show();
}
//String fName = getFileName(uri);
//Toast.makeText(mAct, "Filename: "+fName, Toast.LENGTH_LONG).show();
fileUri = uri;
btn2.setVisibility(View.VISIBLE);
}
}
}
/*
* Read a FileStream
*
*/
String readFile(InputStream is) {
String ret = "";
String line = null;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
ret += line + "\n";
}
br.close();
} catch (Exception e) {
// if any I/O error occurs
e.printStackTrace();
ret = "Exception!";
}
return ret;
}
/*
* Obtain the filename from a URI
*/
public String getFileName(Uri uri) {
String result = "<empty>";
Cursor cursor;
if (uri.getScheme().equals("content")) {
ContentResolver cr = getContentResolver();
try {
cursor = cr.query(uri, null, null, null, null);
} catch (Exception e) {
Toast.makeText(this, "Cursor exception: " + e.toString(), Toast.LENGTH_LONG).show();
return null;
}
try {
if (cursor != null && cursor.moveToFirst()) {
//
// THE NEXT STATEMENT CRASHES WHEN FILE RESIDES ON EXTERNAL STORAGE
//
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
else {
Toast.makeText(mAct, "Bad cursor", Toast.LENGTH_SHORT).show();
return "Bad Cursor";
}
} catch (Exception e) {
Toast.makeText(this, "Cursor exception: " + e.toString(), Toast.LENGTH_LONG).show();
return "Cursoe Exception";
} finally {
cursor.close();
}
}
else
result="Non content URI";
return result;
}
}
When I press the first button, the file requestor pops up and I select my test text file. The contents of the file are listed in a textbox, then a second button is made visible. When that second button is pressed, I query the file and place the filename in a second textbox.
The entire project, along with the test.txt file I am using to test, can be found here

How to overwrite a photo's uri with a cropped uri?

I keep getting this error within the startOCR function :
java.lang.String android.net.Uri.getPath()' on a null object reference
I am trying to take a picture and then crop it before sending it to the perform OCR function. Can anyone help me out?
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.googlecode.tesseract.android.TessBaseAPI;
public class Main3Activity extends AppCompatActivity {
//Log variable.
private static final String TAG = Main3Activity.class.getSimpleName();
//Request code is 1
static final int PHOTO_REQUEST_CODE = 1;
//Constructing an instance to the Tesseract API
private TessBaseAPI tessBaseApi;
//Getting a reference to the TextView in the XML layout
TextView textView;
//Creating a Uri variable that will be holding the point of content to the image.
Uri outputFileUri;
final int PIC_CROP = 2;
private static final String lang = "eng";
String result = "empty";
private static final String DATA_PATH = Environment.getExternalStorageDirectory().toString() + "/TesseractSample/";
private static final String TESSDATA = "tessdata";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
textView = (TextView) findViewById(R.id.OcrResultTextView);
//Getting reference to the button and setting the onClickListener for the button.
Button captureImg = (Button) findViewById(R.id.CaptureImageButton);
if (captureImg != null) {
captureImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startCameraActivity();
}
});
}
}//end of onCreate
/*************************************************************************************************************************
Method that will start the camera of the phone.
************************************************************************************************************************/
private void startCameraActivity() {
try {
//String variable that will hold the directory of the folder which is to be created within the internal
//storage of the phone.
String IMGS_PATH = Environment.getExternalStorageDirectory().toString() + "/TesseractSample/imgs";
prepareDirectory(IMGS_PATH);
String img_path = IMGS_PATH + "/ocr.jpg";
//Uri variable (Uniform Resource Identifier) will contain the reference the uri created from a file.
outputFileUri = Uri.fromFile(new File(img_path));
//Creating an intent of type action_image_capture which is the standard action that
//can be sent to have the camera application capture an image and return it.
final Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Inserting into the intent extra_output because this is used to indicate a content
//resolver Uri to be used to store the requested image, can also be used for videos.
//Also passing in the output Uri which will hold the path to the output image.
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
//Ensuring that there is a camera activity to handle the intent and if there is,
//passing in the takePictureIntent and along with the photo request code.
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, PHOTO_REQUEST_CODE);
//At this current point the camera has been initated.
Log.e(TAG,"Started the camera.");
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
/*********************************************************************************************************************
This method will get called after the image is either finished taken or the user decided to cancel the camera.
********************************************************************************************************************/
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
Log.e(TAG, "Photo has been taken.");
//Method of cropping has to go here
//CropFunction();
//Creating photo
if (requestCode == PHOTO_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Log.e(TAG,"Taken to the confirmation.");
prepareTesseract();
//Put the crop here.
Log.e(TAG, "Starting crop function");
CropFunction();
//if(requestCode == PIC_CROP){
// Log.e(TAG, "Inside if statement for PIC_CROP");
//Getting the returned data and entering it into the Bundle.
//Bundle extras = data.getExtras();
//Get the cropped bitmap
// Bitmap thePic = extras.getParcelable("data");
Log.e(TAG, "Calling the startOCR function");
startOCR(outputFileUri);
// }
// startOCR(outputFileUri);
} else {
Toast.makeText(this, "ERROR: Image was not obtained.", Toast.LENGTH_SHORT).show();
}
}
/***************************************************************************************************
Method to create the directory within the internal storage of the phone.
Method will first check if the directory has not been created before, if it has not
it will create the directory and the Log will display the message it has been created.
If the internal photo directory has already been created this method will just be passed.
*************************************************************************************************/
private void prepareDirectory(String path) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.e(TAG, "ERROR: Creation of directory " + path + " failed, check does Android Manifest have permission to write to external storage.");
}
} else {
Log.i(TAG, "Created directory " + path);
}
}
/************************************************************************
Method responsible for preparing Tesseract operations.
***********************************************************************/
private void prepareTesseract() {
try {
prepareDirectory(DATA_PATH + TESSDATA);
} catch (Exception e) {
e.printStackTrace();
}
copyTessDataFiles(TESSDATA);
}
/*************************************************************************************************
****************************************************************************************************/
private void copyTessDataFiles(String path) {
try {
String fileList[] = getAssets().list(path);
for (String fileName : fileList) {
//Opening the file within the assets folder
// In the situation that the fole is no there it will copy it to the sd card
String pathToDataFile = DATA_PATH + path + "/" + fileName;
if (!(new File(pathToDataFile)).exists()) {
InputStream in = getAssets().open(path + "/" + fileName);
OutputStream out = new FileOutputStream(pathToDataFile);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.d(TAG, "Copied " + fileName + "to tessdata");
}
}
} catch (IOException e) {
Log.e(TAG, "Unable to copy files to tessdata " + e.toString());
}
}
/************************************************************************************************
This function performs the OCR technology within the image provided.
Function that beings the Optical Character Recognition of the image.
Function expects to recieve the Uri of a captured image.
*************************************************************************************************/
private void startOCR(Uri imgUri) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
// 1 - means max size. 4 - means maxsize/4 size. Don't use value <4, because you need more memory in the heap to store your data.
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(imgUri.getPath(), options);
//The result variable will hold whatever is returned from "extractText" function.
result = extractText(bitmap);
//Setting the string result to the content of the TextView.
textView.setText(result);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
private String extractText(Bitmap bitmap) {
try {
tessBaseApi = new TessBaseAPI();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
if (tessBaseApi == null) {
Log.e(TAG, "TessBaseAPI is null. TessFactory not returning tess object.");
}
}
tessBaseApi.init(DATA_PATH, lang);
Log.d(TAG, "Training file loaded");
tessBaseApi.setImage(bitmap);
String extractedText = "empty result";
try {
extractedText = tessBaseApi.getUTF8Text();
} catch (Exception e) {
Log.e(TAG, "Error in recognizing text.");
}
tessBaseApi.end();
return extractedText;
}
private void CropFunction(){
try{
Log.e(TAG, "Inside the crop function.");
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
//cropIntent.putExtra("crop", "true");
//cropIntent.putExtra("return-data", true);
//startActivityForResult(cropIntent,1);
//Inserting the imageType and the Uri into the intent.
cropIntent.setDataAndType(outputFileUri, "image/*");
//Passing in the crop properties to the intent.
cropIntent.putExtra("crop", "true");
//Indicating and passing in the aspect of the desired crop.
cropIntent.putExtra("aspectX", 0);
cropIntent.putExtra("aspectY", 0);
//Indicating and passing in the output for X and Y.
cropIntent.putExtra("outputX", 200);
cropIntent.putExtra("outputY", 150);
//retrieve data on return
//changed from true which gives me a bitmap to false which gives me the exact image.
cropIntent.putExtra("return-data", false);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
Log.e(TAG,"At the end of the crop function.");
startActivityForResult(cropIntent, PIC_CROP);
}catch(ActivityNotFoundException e){
String errorMessage = "Sorry, your device does not support the crop feature";
Toast toaster = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toaster.show();
}
}
}// End of class

How to Get Image URI from Image selected From gallery. Android 5.0.2?

I aam new to android. Kindly provide me some help. I need the Image URI, before this i tried data.getData(); and pass it to getContentResolver().query() but data.getData(); always returned null
Error is at thes lines:
Uri SelectedImageURI = getImageUri(getApplicationContext(), SelectedImage);
return Uri.parse(path);
My android version is 5.0.2
05-10 01:55:10.712 24424-24424/com.donateblood.blooddonation E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.donateblood.blooddonation, PID: 24424
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=com.htc.HTCAlbum.action.ITEM_PICKER_FROM_COLLECTIONS (has extras) }} to activity {com.donateblood.blooddonation/com.donateblood.blooddonation.UploadImage}: java.lang.NullPointerException: uriString
at android.app.ActivityThread.deliverResults(ActivityThread.java:3881)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3931)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1408)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.<init>(Uri.java:473)
at android.net.Uri$StringUri.<init>(Uri.java:463)
at android.net.Uri.parse(Uri.java:435)
at com.donateblood.blooddonation.UploadImage.getImageUri(UploadImage.java:156)
at com.donateblood.blooddonation.UploadImage.onActivityResult(UploadImage.java:102)
at android.app.Activity.dispatchActivityResult(Activity.java:6160)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3877)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3931)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1408)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
package com.donateblood.blooddonation;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Rect;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.mongodb.DB;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by YouCaf Iqbal on 4/26/2016.
*/
public class UploadImage extends AppCompatActivity {
public static final int RESULT_LOAD = 1;
#InjectView(R.id.imageView) ImageView ImageUpload;
#InjectView(R.id.upload) Button Btn_Upload;
#InjectView(R.id.proceed) Button Btn_Proceed;
public String bloodgroup,name,password,number,email,picturePath,encodedPhotoString;
Database dbobj = new Database();
GPSTracker gps; private DB db;
public double latitude=0;
public double longitude=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uploadimage);
ButterKnife.inject(this);
getCurrentLatLong();
Btn_Upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
Intent upload = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//Adding Croping
upload.putExtra("crop","true");
upload.putExtra("aspectX",1);
upload.putExtra("aspectY",1);
upload.putExtra("outputX",300);
upload.putExtra("outputY",300);
upload.putExtra("return-data",true);
startActivityForResult(upload,RESULT_LOAD);
} catch (ActivityNotFoundException E) {
String errorMessage = "Your device doesn't support the crop action!";
Toast toast = Toast.makeText(UploadImage.this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
});
Btn_Proceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Prcoess();
}
});
}
// When image is selected from Gallery
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==RESULT_LOAD && resultCode==RESULT_OK && data!=null){
Bundle extras = data.getExtras();
//Uri SelectedImageURI = (Uri)extras.get(Intent.EXTRA_STREAM);
Bitmap SelectedImage = extras.getParcelable("data");
//Make Image rounded
//Bitmap RoundedImage = getRoundedShape(SelectedImage);
// Uri SelectedImageURI = data.getData();
Uri SelectedImageURI = getImageUri(getApplicationContext(), SelectedImage);
picturePath = getRealPathFromURI(SelectedImageURI);
ImageUpload.setImageBitmap(SelectedImage);
// retrieve image path
String[] projection = {MediaStore.Images.Media.DATA};
try {
// Cursor cursor = getContentResolver().query(SelectedImageURI, projection, null, null, null);
//cursor.moveToFirst();
// int columnIndex = cursor.getColumnIndex(projection[0]);
// picturePath = cursor.getString(columnIndex);
// cursor.close();
////////////////////////////////////////////////////
String fileNameSegments[] = picturePath.split("/");
String fileName = fileNameSegments[fileNameSegments.length - 1];
try {
File f = new File(picturePath);
Bitmap myImg = decodeFile(f,720);
//myImg = getResizedBitmap(myImg,100); // Compress it
// Bitmap myImg = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
// myImg = getResizedBitmap(myImg, 720);
myImg.compress(Bitmap.CompressFormat.JPEG, 50, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedPhotoString = Base64.encodeToString(byte_arr, 0);
// ImageUpload.setImageBitmap(myImg);
}catch (Exception e){
Toast.makeText(UploadImage.this,"Unable to Set Image Try Again",Toast.LENGTH_SHORT).show();
}
//Log.d("Picture Path", picturePath);
// Toast.makeText(getBaseContext(), ""+picturePath+"", Toast.LENGTH_LONG).show();
}
catch(Exception e) {
// Log.e("Path Error", e.toString());
Toast.makeText(getBaseContext(), "Error finding path", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
//
}
}
public void Prcoess(){
dbAsync signupThread = new dbAsync();
signupThread.execute();
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
public class dbAsync extends AsyncTask<Void,Void,Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UploadImage.this);
pDialog.setMessage("Creating Account...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
GetUserDetails();
dbobj.insertUser(name,email,password,number,bloodgroup,latitude,longitude,encodedPhotoString);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
Toast.makeText(getBaseContext(), "Created Successfully", Toast.LENGTH_LONG).show();
// Toast.makeText(getBaseContext(), ""+encodedPhotoString+"", Toast.LENGTH_LONG).show();
onSignupSuccess();
}
}
public void onSignupSuccess() {
// btn_signup.setEnabled(true);
//setResult(RESULT_OK, null);
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
public void GetUserDetails(){
//mySpinner=(Spinner) findViewById(R.id.spinner);
bloodgroup = SignupActivity.bloodgroup.toString();
name = SignupActivity.name.toString();
email = SignupActivity.email.toString();
password = SignupActivity.password.toString();
number = SignupActivity.number.toString();
}
public void getCurrentLatLong(){
gps = new GPSTracker(UploadImage.this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
}
}
public Bitmap decodeFile(File f,int IMAGE_MAX_SIZE){
Bitmap b = null;
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BitmapFactory.decodeStream(fis, null, o);
try {
fis.close();
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int) Math.pow(2, (int) Math.ceil(Math.log(IMAGE_MAX_SIZE /
(double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
}catch (IOException e) {
e.printStackTrace();
}
return b;
}
}
ACTION_PICK returns its result in the Uri in the Intent delivered to onActivityResult(). You call getData() to get this Uri. That's it. Hence, pretty much everything in your if(requestCode==RESULT_LOAD && resultCode==RESULT_OK && data!=null) block is not only wrong, but it is useless.
Beyond that, get rid of all the undocumented extras that you are placing on that ACTION_PICK Intent. Use an image cropping library.

How to delete captured video from sdcard in android

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_VIDEO = 1;
public static TextView output;
private VideoView videoPreview;
String[] fileList;
public static MainActivity ActivityContext =null;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
private Uri fileUri; // file url to store image/video
private static File mediaStorageDir;
private ImageButton deletbtn, previewbtn, btnRecordVideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRecordVideo = (ImageButton) findViewById(R.id.btnRecordVideo);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
previewbtn = (ImageButton) findViewById(R.id.previewbtn);
deletbtn = (ImageButton) findViewById(R.id.deletbtn);
/*
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
previewbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
previewVideo();
}
});
deletbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
deleteVideo();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/*
* Recording video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// Toast.makeText(getApplicationContext(), fileUri.toString(), Toast.LENGTH_LONG).show();
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 180);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
//previewVideo();
Toast.makeText(getApplicationContext(),
"Video recorded", Toast.LENGTH_SHORT)
.show();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
/*
* Previewing recorded video
*/
private void previewVideo() {
try {
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
// start playing
videoPreview.start();
} catch (Exception e) {
e.printStackTrace();
}
}
/** 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){
// Check that the SDCard is mounted
mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES),"MyCameraVideo");
// Create the storage directory(MyCameraVideo) if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
output.setText("Failed to create directory MyCameraVideo.");
Toast.makeText(ActivityContext, "Failed to create directory MyCameraVideo.",
Toast.LENGTH_LONG).show();
Log.d("MyCameraVideo", "Failed to create directory MyCameraVideo.");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
private void deleteVideo( ) {
enter code here
File videoFiles = new File(Environment.getExternalStorageDirectory()+"/MyCameraVideo");
if(videoFiles.isDirectory())
{
fileList=videoFiles.list();
Log.d("hello",FileList );
}
for(int i=0;i<fileList.length;i++)
{
Log.e("Video:"+i+" File name",fileList[i]);
}
}
}
I am getting this issue.
please suggest me how to do this.
8868-8868/com.example.video.videoapp W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41016ae0)
01-22 15:19:33.519 8868-8868/com.example.video.videoapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.video.videoapp.MainActivity.deleteVideo(MainActivity.java:238)
at com.example.video.videoapp.MainActivity.access$200(MainActivity.java:23)
at com.example.video.videoapp.MainActivity$3.onClick(MainActivity.java:76)
at android.view.View.performClick(View.java:4278)
at android.view.View$PerformClick.run(View.java:17429)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5099)
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:803)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:570)
at dalvik.system.NativeStart.main(Native Method)
01-22 15:19:38.454 8868-8868/com.example.video.videoapp I/Process﹕ Sending signal. PID: 8868 SIG: 9
File videofiles=new File(Environment.getExternalStorageDirectory()+"/MyCameraVideo.mp4");
videofiles.delete();
Using file class you can do it
File file = new File(path_to_the_file);
boolean deleted = file.delete();
where path_to_the_fileis the path of the file you want to delete - for example:
/sdcard/YourDirectoryname/filename.extention
In your code you don't delete the file. You are just taking the files inside your MyCameraVideo folder. Use the below code to delete the files.
private void deleteVideo( ) {
File videoFiles = new File(Environment.getExternalStorageDirectory()+"/MyCameraVideo/");
if(videoFiles.isDirectory())
{
fileList=videoFiles.list();
Log.d("hello",fileList.toString());
}
for(int i=0;i<fileList.length;i++)
{
Log.e("Video:"+i+" File name",fileList[i]);
String path=Environment.getExternalStorageDirectory()+"/MyCameraVideo/"+fileList[i];
File file = new File(path);
file.delete();
}
}
Don't Forget to add these permissions in your Manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
When Control is in onActivityResult, you can get the File path and with that you can delete the file if exist.
Review the code, hope it will help you.
Intent to Video Camera
intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,
MediaRecorder.OutputFormat.MPEG_4);
long maxVideoSize = 15*1024*1024; // 15 MB
intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, maxVideoSize);
startActivityForResult(intent, REQUEST_VIDEO_CAMERA);
Code in onActivityResult:
if (requestCode == REQUEST_VIDEO_CAMERA) {
if (resultCode == RESULT_OK) {
Log.d("In video from camera", "In video from camera");
Uri videoUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(videoUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
String mMediaFilePath = filePath; //File path of Video Recorded.
cursor.close();
//Delete File from Location.
File videoFile = new File(mMediaFilePath);
if(videoFile.exists())
{
videoFile.delete();
}
}
}

Categories