My app quits as soon as picture is selected - java

I have created an app that basically takes a picture and saves it to the gallery. The only problem is that after the picture is taken it takes you to the screen where you can preview it with the two buttons that say okay and cancel. Once you click okay, the app quits. The image is still saved to the gallery but I want the app to stay open. I also want the app to display a bitmap of the image on an imageView that I have.
Here is my MainActivity.java
package com.example.app;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity { <- Line 22
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent(); <- Line 34
}
});
}
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.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
// I AM UNSURE WHAT CODE TO PUT HERE. DOES ANYONE KNOW WHAT I SHOULD BE PUTTING HERE?
}
// Continue only if the File was successfully created
if (photoFile != null) {
//This is where the error is occurring but I do not know why.
Line 56 -> Uri photoURI = FileProvider.getUriForFile(this, "com.example.app", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
ImageView imageView = findViewById(R.id.imageView);
imageView.setImageBitmap(imageBitmap);
}
}
String currentPhotoPath;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
}
Here is my error message
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.app, PID: 22357
java.lang.IllegalArgumentException: Couldn't find meta-data for provider with authority com.example.app
at androidx.core.content.FileProvider.parsePathStrategy(FileProvider.java:606)
at androidx.core.content.FileProvider.getPathStrategy(FileProvider.java:579)
at androidx.core.content.FileProvider.getUriForFile(FileProvider.java:417)
--> at com.example.app.MainActivity.dispatchTakePictureIntent(MainActivity.java:56)
--> at com.example.app.MainActivity.access$000(MainActivity.java:22)
--> at com.example.app.MainActivity$1.onClick(MainActivity.java:34)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14966)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29315)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7777)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1047)
I/Process: Sending signal. PID: 22357 SIG: 9

Related

On clicking predict button, the app crashes

Recently I have been working on android studio, I built a python image classification model and want to integrate it with an app. But when I click on predict button, the app crashes. Would be helpful if I can get the idea as to where things are going wrong.
Attached is the code and the error it throws -
Activitymain.java :-
package com.example.uni;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.uni.ml.ConvertedModel;
import org.tensorflow.lite.DataType;
import org.tensorflow.lite.support.image.TensorImage;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;
import java.io.IOException;
import java.nio.ByteBuffer;
public class MainActivity extends AppCompatActivity {
private ImageView imgView;
private Button predict;
private Button select;
private TextView tv;
private Bitmap img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView = (ImageView) findViewById(R.id.imageView);
tv = (TextView) findViewById(R.id.textView);
select = (Button) findViewById(R.id.button);
predict = (Button) findViewById(R.id.button2);
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,12);
}
});
predict.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
img = Bitmap.createScaledBitmap(img,
500,
500,
true);
try {
ConvertedModel model = ConvertedModel.newInstance(getApplicationContext());
// Creates inputs for reference.
TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 500, 500, 3}, DataType.FLOAT32);
TensorImage tensorImage = new TensorImage(DataType.FLOAT32);
tensorImage.load(img);
ByteBuffer byteBuffer = tensorImage.getBuffer();
inputFeature0.loadBuffer(byteBuffer);
// Runs model inference and gets result.
ConvertedModel.Outputs outputs = model.process(inputFeature0);
TensorBuffer outputFeature0 = outputs.getOutputFeature0AsTensorBuffer();
// Releases model resources if no longer used.
model.close();
tv.setText((int) outputFeature0.getFloatArray()[0]);
} catch (IOException e) {
/* TODO Handle the exception */
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 100)
{
imgView.setImageURI(data.getData());
Uri uri = data.getData();
try {
img = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In logcat I see this -
2021-11-05 13:23:38.040 24027-24027/com.example.uni I/tflite: Initialized TensorFlow Lite runtime.
2021-11-05 13:23:38.090 24027-24027/com.example.uni E/libc: Access denied finding property "ro.hardware.chipname"
2021-11-05 13:23:38.081 24027-24027/com.example.uni W/com.example.uni: type=1400 audit(0.0:232245): avc: denied { read } for name="u:object_r:vendor_default_prop:s0" dev="tmpfs" ino=14249 scontext=u:r:untrusted_app:s0:c48,c257,c512,c768 tcontext=u:object_r:vendor_default_prop:s0 tclass=file permissive=0
2021-11-05 13:23:38.841 24027-24027/com.example.uni E/com.example.un: Invalid ID 0x00000000.
2021-11-05 13:23:38.842 24027-24027/com.example.uni D/AndroidRuntime: Shutting down VM
2021-11-05 13:23:38.843 24027-24027/com.example.uni E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.uni, PID: 24027
android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:381)
at android.content.res.MiuiResources.getText(MiuiResources.java:97)
at android.widget.TextView.setText(TextView.java:6397)
at com.example.uni.MainActivity$2.onClick(MainActivity.java:85)
at android.view.View.performClick(View.java:7189)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:7166)
at android.view.View.access$3500(View.java:819)
at android.view.View$PerformClick.run(View.java:27682)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7592)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
2021-11-05 13:23:38.887 24027-24027/com.example.uni I/Process: Sending signal. PID: 24027 SIG: 9
Need suggestions as to what's going on and how to resolve it. I'm using android studio arctic fox 2020.3.1 patch 3.
The logcat already told you that it crashed at the setText() call. You called
tv.setText((int) outputFeature0.getFloatArray()[0]);
The int in setText(int) refers to a Resource ID defined in the string.xml (R.string.xxx).
If you are not getting the string from res, you should use setText(CharSequence) instead.
You probably want
tv.setText(String.format("%f",outputFeature0.getFloatArray()[0]));
(change "%f" to any decimal points or format you want)

Cannot instance a View Model because the table is empty

I'm creating a view model in my activity in order to add an object to the database via method. But the view model is representing an empty table, and it's causing this stack trace and complete crash of the application:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gmproxy.pastilarma, PID: 9827
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gmproxy.pastilarma/com.gmproxy.pastilarma.UserAddScreen}: java.lang.RuntimeException: Cannot create an instance of class com.gmproxy.Util.PathologyUserViewModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.gmproxy.Util.PathologyUserViewModel
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:275)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:112)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at com.gmproxy.pastilarma.UserAddScreen.onCreate(UserAddScreen.java:84)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:112) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150) 
at com.gmproxy.pastilarma.UserAddScreen.onCreate(UserAddScreen.java:84) 
at android.app.Activity.performCreate(Activity.java:8000) 
at android.app.Activity.performCreate(Activity.java:7984) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
at androidx.room.RoomDatabase.assertNotMainThread(RoomDatabase.java:385)
at androidx.room.RoomDatabase.query(RoomDatabase.java:441)
at androidx.room.util.DBUtil.query(DBUtil.java:83)
at com.gmproxy.DAO.PathologyUserDAO_Impl.getAllObjects(PathologyUserDAO_Impl.java:154)
at com.gmproxy.DAO.PathologyUserRepository.getAllObjects(PathologyUserRepository.java:19)
at com.gmproxy.Util.PathologyUserViewModel.<init>(PathologyUserViewModel.java:19)
at java.lang.reflect.Constructor.newInstance0(Native Method) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:343) 
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267) 
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:112) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150) 
at com.gmproxy.pastilarma.UserAddScreen.onCreate(UserAddScreen.java:84) 
at android.app.Activity.performCreate(Activity.java:8000) 
at android.app.Activity.performCreate(Activity.java:7984) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
This is happening as soon as I enter said activity. The other view models that have records in the database are created with no problem, but the other ones that lack any object in the database fail to create too. Do I purposedly need to add a record in order to create those?
This is the activity and view model code respectively:
Activity:
package com.gmproxy.pastilarma;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
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.lifecycle.ViewModelProvider;
import com.gmproxy.DAO.PathologyUserDAO;
import com.gmproxy.DAO.UserDAO;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Entities.User;
import com.gmproxy.Util.AlarmUserViewModel;
import com.gmproxy.Util.ImageConverter;
import com.gmproxy.Util.PathologyUserViewModel;
import com.gmproxy.Util.UserViewModel;
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;
PathologyUserViewModel pathologyUserViewModel;
int pathAct = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
context = this.getApplicationContext();
Bundle bundle = new Bundle();
pathAct = getIntent().getIntExtra("path-record",0);
if (pathAct == 1){
onRestoreInstanceState(bundle);
}
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);
userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
pathologyUserViewModel = new ViewModelProvider(this).get(PathologyUserViewModel.class);
List<String> genderList = new ArrayList<>();
genderList.add("M");
genderList.add("F");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,genderList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
addGender.setAdapter(adapter);
obs = intent.getStringExtra("observation");
paths = (Pathology) intent.getSerializableExtra("paths");
}
public void gotoBack(View view) {
Intent mainAct = new Intent(UserAddScreen.this, UserListScreen.class);
startActivity(mainAct);
}
public void addObservation(View view) {
Intent mainAct = new Intent(UserAddScreen.this, UserObservationScreen.class);
startActivity(mainAct);
}
public void addPathology(View view) {
Intent mainAct = new Intent(UserAddScreen.this, PathologiesSearchScreen.class);
startActivity(mainAct);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("Nombre_usuario",addUsername.getText().toString());
savedInstanceState.putString("Apellido_usuario",addSurname.getText().toString());
savedInstanceState.putString("Edad_usuario",addAge.getText().toString());
savedInstanceState.putString("Habitacion_usuario",addRoomNumber.getText().toString());
savedInstanceState.putInt("Sexo_usuario",addGender.getSelectedItemPosition());
savedInstanceState.putString("Observacion-usuario", obs);
savedInstanceState.putSerializable("Patologia-usuario", paths);
super.onSaveInstanceState(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");
}
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);
} 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);
} 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, String.valueOf(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);
}
}
}
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);
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);
pathologyUserViewModel.insert(userViewModel.getIdByNameAndSurname(addUsername.getText().toString(),addSurname.getText().toString()), 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();
}
}
View Model:
package com.gmproxy.Util;
import android.app.Application;
import androidx.lifecycle.AndroidViewModel;
import com.gmproxy.DAO.PathologyUserRepository;
import com.gmproxy.Entities.PathologyUser;
import java.util.List;
public class PathologyUserViewModel extends AndroidViewModel {
private PathologyUserRepository repository;
public List<PathologyUser> pathologyUsers;
public PathologyUserViewModel(Application application) {
super(application);
repository = new PathologyUserRepository(application);
pathologyUsers = repository.getAllObjects();
}
List<PathologyUser> getAll() { return pathologyUsers; }
public List<PathologyUser> getAllFromUser(int i) { return repository.getAllFromUser(i); }
public void insert(int i, int j) { repository.insertObject(i,j); }
public void delete(PathologyUser obj) { repository.deleteObject(obj); }
}
I don't quite remember anything about not being able to create view models with empty tables in the documentation, maybe I'm missing something?
Instead of the line:
pathologyUserViewModel = new ViewModelProvider(this).get(PathologyUserViewModel.class);
You can use:
pathologyUserViewModel = new ViewModelProvider
.AndroidViewModelFactory(this.getApplication())
.create(PathologyUserViewModel.class);
Or,
pathologyUserViewModel = ViewModelProvider(
this,
ViewModelProvider.AndroidViewModelFactory(application)
).get(PathologyUserViewModel::class.java)
If you look through the log, you are trying to access the database on the main thread :-
Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time
at the line :-
pathologyUsers = repository.getAllObjects();
You either need to run this on another thread OR alternately (and not recommended) allow it to run on the main thread which can be done by using:-
.allowMainThreadQueries()
when building the room database. e.g. :-
Room.databaseBuilder(context, TheDatabase::class.java, "thedatabasefile.db")
.allowMainThreadQueries() //<<<<<<<<<< allow main thread run
.build()
Do I purposedly need to add a record in order to create those?
As long as you are handling the returned Lists correctly and not assuming they are not empty, there should be no problem.

Convert from bitmap rgb_565 to Mat

I am using Android Intent to take a photo.
startActivityForResult(intent, 0);
This opens the native camera and i can take a picture.
In the Activity where the picture is returned to , in the onActivityResult method , I can get a hold of the returned Bitmap like so.
if (requestCode == 0 && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
I then wish to convert this to a Mat to do some openCV image processing.
I am attempting to convert like this.
Mat src = new Mat(imageBitmap.getHeight(), imageBitmap.getWidth(), CvType.CV_8UC4);
Utils.bitmapToMat(imageBitmap, src);
The line above causes a crash with the following stack trace .
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.i330155.testing123, PID: 16349
java.lang.UnsatisfiedLinkError: No implementation found for long org.opencv.core.Mat.n_Mat(int, int, int) (tried Java_org_opencv_core_Mat_n_1Mat and Java_org_opencv_core_Mat_n_1Mat__III)
at org.opencv.core.Mat.n_Mat(Native Method)
at org.opencv.core.Mat.<init>(Mat.java:37)
at com.example.testing123.MainActivity.onActivityResult(MainActivity.java:48)
at android.app.Activity.dispatchActivityResult(Activity.java:7022)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4248)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4295)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1583)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6290)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
After searching i found the following post.
http://answers.opencv.org/question/52722/what-is-the-correct-way-to-convert-a-mat-to-a-bitmap/
Which says that.
mat is a valid input Mat object of the types 'CV_8UC1', 'CV_8UC3' or 'CV_8UC4'.
bmp is a valid Bitmap object of the same size as the Mat and of type 'ARGB_8888' or 'RGB_565'.
As you can see in the constructor for the Mat I supply these args.
I have checked the config of the imageBitmap , which confirms that it is indeed
a 'RGB_565'.
What am i missing here? I dont understand why this does not work.
Thanks in advance.
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
public class MainActivity extends AppCompatActivity {
Button button ;
ImageView mImageView ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.capture) ;
mImageView = (ImageView)findViewById(R.id.imageView) ;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
Bitmap.Config config = imageBitmap.getConfig();
//this is throwing error
Mat src = new Mat(imageBitmap.getHeight(), imageBitmap.getWidth(), CvType.CV_8UC3);
Utils.bitmapToMat(imageBitmap, src);
Imgproc.Canny(src, src, 10, 100);
Bitmap edgeBitmap = Bitmap.createBitmap(imageBitmap.getWidth(), imageBitmap.getHeight(), Bitmap.Config.ARGB_8888);
// Utils.matToBitmap(dest, edgeBitmap);
mImageView.setImageBitmap(imageBitmap);
}
}
}
When debugging this method call :
Mat src = new Mat(imageBitmap.getHeight(), imageBitmap.getWidth(),
CvType.CV_8UC3);
calls another method
nativeObj = n_Mat(rows, cols, type);
this n_Mat is declared like so.
// C++: Mat::Mat(int rows, int cols, int type)
private static native long n_Mat(int rows, int cols, int type);
and is highlighted in red.
The application no longer crashes and functions as expected.
This post covers it quite well.
No implementation found for long org.opencv.core.Mat.n_Mat() error Using OpenCV
org-opencv-core-mat-n-mat-error-using-opencv

Ucrop activity skips with camera image :Android

I used Ucrop to crop an image from camera, but the activity skips. Here is my MainActivity.java file. I think i'm missing something. My code is little bit longer, please take a look. Thanks in advance.
package com.example.sathwik.uploadtrail1;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.yalantis.ucrop.UCrop;
public class MainActivity extends AppCompatActivity {
// LogCat tag
private static final String TAG = MainActivity.class.getSimpleName();
// Camera activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri; // file url to store image/video
private Button btnCapturePicture, btnRecordVideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Changing action bar background color
//getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
/**
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
/**
Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
// 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;
}
}
/**
     * Launching camera app to capture image
     */
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);
}
/**
     * Launching camera app to record video
     */
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);// set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/** Perform UCrop */
public void performUcrop(){
UCrop.of(fileUri, fileUri).start(this);
}
/**
     * Here we store the file url as it will be null after returning from camera
     * app
     */
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState (Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
     * 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_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
performUcrop();
// successfully captured the image
// launching upload activity
launchUploadActivity(true);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
//launching upload activity
launchUploadActivity(false);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(), "Sorry! Failed to record video", Toast.LENGTH_SHORT).show();
}
}
}
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(MainActivity.this, UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
/**
     * Creating file uri to store image/video
     */
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
     * returning image / video
     */
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Config.IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "+ Config.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
//Logout function
private void logout(){
//Creating an alert dialog to confirm logout
android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want to logout?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
//Getting out sharedpreferences
SharedPreferences preferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Getting editor
SharedPreferences.Editor editor = preferences.edit();
//Puting the value false for loggedin
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, false);
//Putting blank value to email
editor.putString(Config.EMAIL_SHARED_PREF, "");
//Saving the sharedpreferences
editor.commit();
//Starting login activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
//Showing the alert dialog
android.support.v7.app.AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menuLogout) {
logout();
}
return super.onOptionsItemSelected(item);
}
}
I added Ucrop libraries in my gradle file. My gradle app module has this
compile 'com.github.yalantis:ucrop:2.2.1-native'
Android monitor shows this log
07-02 00:42:22.953 1534-2050/system_process I/ActivityManager: START u0 {cmp=com.example.sathwik.uploadtrail1/com.yalantis.ucrop.UCropActivity (has extras)} from uid 10058 on display 0
07-02 00:42:22.954 1534-2050/system_process V/WindowManager: addAppToken: AppWindowToken{2e96b812 token=Token{39e8cb9d ActivityRecord{22ae1a74 u0 com.example.sathwik.uploadtrail1/com.yalantis.ucrop.UCropActivity t29}}} to stack=1 task=29 at 2
07-02 00:42:22.959 1534-1955/system_process I/ActivityManager: START u0 {cmp=com.example.sathwik.uploadtrail1/.UploadActivity (has extras)} from uid 10058 on display 0
07-02 00:42:22.962 1534-1955/system_process V/WindowManager: addAppToken: AppWindowToken{278b8499 token=Token{39cc69e0 ActivityRecord{322e0be3 u0 com.example.sathwik.uploadtrail1/.UploadActivity t29}}} to stack=1 task=29 at 3
07-02 00:42:23.578 14053-14053/com.example.sathwik.uploadtrail1 I/Choreographer: Skipped 36 frames! The application may be doing too much work on its main thread.
07-02 00:42:23.945 1534-1836/system_process V/WindowManager: Adding window Window{14ab833f u0 com.example.sathwik.uploadtrail1/com.example.sathwik.uploadtrail1.UploadActivity} at 6 of 11 (after Window{14c5edfe u0 com.android.camera/com.android.camera.Camera})
07-02 00:42:24.332 1534-1563/system_process I/ActivityManager: Displayed com.example.sathwik.uploadtrail1/.UploadActivity: +1s293ms
07-02 00:42:24.333 1534-1558/system_process I/ActivityManager: Killing 2721:com.google.android.gms.unstable/u0a7 (adj 15): empty for 3423s
07-02 00:42:24.333 1534-1558/system_process W/libprocessgroup: failed to open /acct/uid_10007/pid_2721/cgroup.procs: No such file or directory
07-02 00:42:25.366 2376-14273/com.google.android.gms W/PlatformStatsUtil: Could not retrieve Usage & Diagnostics setting. Giving up.
07-02 00:42:25.374 1534-1836/system_process I/ActivityManager: Killing 9541:com.android.calendar/u0a18 (adj 15): empty for 2545s
07-02 00:42:25.374 1534-1836/system_process W/libprocessgroup: failed to open /acct/uid_10018/pid_9541/cgroup.procs: No such file or directory
UCrop is working fine, but you are starting it the wrong way, if you specify the same argument for source and destination, the onActivityResult will be called immediately. and obviously with no result, fix:
1. specify different source and destination
UCrop.of(fileUri, dstUri).start(this);
2. add the code to handle the response from uCrop. in my tutorial
https://youtu.be/glwM0cAUV4A, the code in onActivityResult is not perfect but it works.

Android Java: Modification of instance variable inside button click handler

There is a strange behaviour of assigning/modifying instance variable of the class inside Button OnClick() handlers.
As shown below, the instance variable "CurrentFile" is modified inside imgBtn.setOnClickListener() handlers. But when this variable is accessed in onActivityResult() method, this variable contains the value "null".
According to my understanding, the activity "GetPicActivity" will not be destroyed till the Camera activity returns. So, the instance variable "CurrentFile" should not be null.
Please help, if I am missing some basics.
import java.io.File;
import java.io.IOException;
import com.favoritepics.R;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class GetPicActivity extends Activity {
protected static final int ID_REQ_IMAGE_CAPTURE = 1;
protected static final int ID_REQ_PICK_PHOTO = 0;
protected File currentFile = null; /// Goal is "to modify this variable inside Button onClick handlers"
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.DKGRAY));
setContentView(R.layout.activity_get_pic);
// set handler image gallery
ImageButton imgBtn = (ImageButton) findViewById(R.id.imgGallery);
imgBtn.setOnClickListener(new ImageButton.OnClickListener() {
#Override
public void onClick(View v) {
// create intent to take picture on camera
Intent pickPhoto = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, ID_REQ_PICK_PHOTO);
}
});
// set handler for camera image
imgBtn = (ImageButton) findViewById(R.id.imgCamera);
imgBtn.setOnClickListener(new ImageButton.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File tempDir = Environment.getExternalStorageDirectory();
File tempFile = null;
try {
currentFile = File
.createTempFile("_jpeg_", ".jpg", tempDir);
} catch (IOException exception) {
Toast.makeText(
GetPicActivity.this,
"Problem occured during creation of temp file! "
+ exception.getMessage(),
Toast.LENGTH_SHORT).show();
}
if (currentFile != null) {
takePicture.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(currentFile));
startActivityForResult(takePicture, ID_REQ_IMAGE_CAPTURE);
}
}
});
// set handler for cancel button
Button btnCancel = (Button) findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case ID_REQ_IMAGE_CAPTURE:
if (resultCode == RESULT_OK) {
Intent newIntent = new Intent();
newIntent.putExtra("TYPE", requestCode);
newIntent.putExtra("PATH", currentFile.getAbsolutePath());
setResult(RESULT_OK, newIntent);
finish();
}
break;
default:
break;
}
}
}
click here to see Logcat messages
Steps what I intend to do:
1, Create a temporary file in External storage for the destination of Camera picture
2, Start Camera to take a picture by passing the URI of temporary file
3, OnActivityResult() from camera, return the (temporary) File path to previous activity for further process
But here what I see is,
As soon as the Camera is started & picture is taken, the GetPicActivity is created again. Because of this, the instance variable "CurrentFile" will be null & in OnActivityResult() , I could not get the File path of temporary file.
Why is the GetPicActivity destroyed after starting Camera?
When the camera is started, the Camera appears in the screen orientation "Landscape".
Even the orientation of already existing activity stack is changed to "Landscape" itseems.
So, When the result of Camera is returned to GetPicActivity method OnActivityResult(), the GetPicActivity is created again. But now, the instance variable "CurrentFile" is null. This, gives a NullPointerException.

Categories

Resources