Estoy desarrollando una app con 2 opciones para subir imágenes al servidor web: "Tomar foto con cámara" ó "Elegir foto de galería" Mi problema es al tratar de subir la imagen seleccionándola desde la galería, No se que puedo estar haciendo mal..
Al momento de seleccionar la imagen de galería me muestra esto en el logcat:
05-23 10:36:16.211 24386-24386/mx.gob.lahuerta.oficiadepartes I/BitmapFactory: DecodeImagePath(decodeResourceStream3) : value is null. res : null
Este es el codigo de mi app:
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showOptions();
}
});
subir.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
serverUpdate();
}
});
Aqui muestro las opciones para capturar la imagen
private void showOptions(){
final CharSequence[] option = {"Tomar foto", "Elegir de galeria", "Cancelar"};
final AlertDialog.Builder builder = new AlertDialog.Builder(Modificar.this);
builder.setTitle("Elige una opción");
builder.setItems(option, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(option[which] == "Tomar foto"){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
//Verifica permisos para Android 6.0+
checkExternalStoragePermission();
}
File file = new File(Environment.getExternalStorageDirectory(), MEDIA_DIRECTORY);
boolean isDirectoryCreated = file.exists();
if(!isDirectoryCreated)
isDirectoryCreated = file.mkdirs();
if(isDirectoryCreated){
Long timestamp = System.currentTimeMillis() / 1000;
imageName = timestamp.toString() + ".jpg";
mPath = Environment.getExternalStorageDirectory() + File.separator + MEDIA_DIRECTORY
+ File.separator + imageName;
newFile = new File(mPath);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(newFile));
startActivityForResult(intent, PHOTO_CODE);
}
}else if(option[which] == "Elegir de galeria"){
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent.createChooser(intent, "Selecciona app de imagen"), SELECT_PICTURE);
}else {
dialog.dismiss();
}
}
});
builder.show();
}
Metodo para caputurar foto con la camara
private void getCamara(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
//Verifica permisos para Android 6.0+
checkExternalStoragePermission();
}
File file = new File(Environment.getExternalStorageDirectory(), MEDIA_DIRECTORY);
boolean isDirectoryCreated = file.exists();
if(!isDirectoryCreated)
isDirectoryCreated = file.mkdirs();
if(isDirectoryCreated){
Long timestamp = System.currentTimeMillis() / 1000;
imageName = timestamp.toString() + ".jpg";
mPath = Environment.getExternalStorageDirectory() + File.separator + MEDIA_DIRECTORY
+ File.separator + imageName;
newFile = new File(mPath);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(newFile));
startActivityForResult(intent, PHOTO_CODE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
switch (requestCode){
case PHOTO_CODE:
MediaScannerConnection.scanFile(this,
new String[]{mPath}, null,
new MediaScannerConnection.OnScanCompletedListener() {
@Override
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> Uri = " + uri);
}
});
Bitmap bitmap = BitmapFactory.decodeFile(mPath);
imagen.setImageBitmap(bitmap);
nombreImagen.setText(imageName);
subir.setEnabled(true);
break;
case SELECT_PICTURE:
Uri path = data.getData();
imagen.setImageURI(path);
imageName = path.getPath().substring(path.getPath().lastIndexOf("/")+1)+".jpg";
nombreImagen.setText(imageName);
subir.setEnabled(true);
break;
}
}
}
Metodo para subir la foto al servidor
private void uploadFoto(String imag){
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://xxx/WebService/upload.php");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody foto = new FileBody(newFile, "image/jpeg");
mpEntity.addPart("evidencia", foto);
httppost.setEntity(mpEntity);
try {
httpclient.execute(httppost);
httpclient.getConnectionManager().shutdown();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private boolean onInsert(){
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
HttpPost httppost;
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://xxx/WebService/upload.php"); // Url del Servidor
//Añadimos nuestros datos
nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("evidencia",imageName+".jpg"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
return true;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
private void serverUpdate(){
if (newFile.exists()){
new ServerUpdate().execute();
}
}
class ServerUpdate extends AsyncTask<String,String,String>{
ProgressDialog pDialog;
@Override
protected String doInBackground(String... arg0) {
uploadFoto(foto);
if(onInsert())
runOnUiThread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(Modificar.this, "Exito al subir la imagen",
Toast.LENGTH_LONG).show();
}
});
else
runOnUiThread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(Modificar.this, "Sin exito al subir la imagen",
Toast.LENGTH_LONG).show();
}
});
return null;
}
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Modificar.this);
pDialog.setMessage("Actualizando Servidor, espere..." );
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.show();
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
}
}
private void checkExternalStoragePermission() {
int permissionCheck = ContextCompat.checkSelfPermission(
this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
Log.i("Mensaje", "No se tiene permiso para leer.");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 225);
} else {
Log.i("Mensaje", "Se tiene permiso para leer!");
}
}
Anexo el error del logcat al presionar el boton "subir"
05-24 10:56:09.651 28020-28020/mx.gob.lahuerta.oficiadepartes E/AndroidRuntime: FATAL EXCEPTION: main
Process: mx.gob.lahuerta.oficiadepartes, PID: 28020
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.io.File.exists()' on a null object reference
at mx.gob.lahuerta.oficiadepartes.Modificar.serverUpdate(Modificar.java:502)
at mx.gob.lahuerta.oficiadepartes.Modificar.access$300(Modificar.java:83)
at mx.gob.lahuerta.oficiadepartes.Modificar$6.onClick(Modificar.java:323)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10826)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Espero su ayuda! :(
OutOfMemory
??