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.
Related
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)
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
I'm new at coding and I am making simple flashlight android program in Android Studio. But I am getting this problem (shown in LogCat) and don't know how to resolve it.
I tried searching of this error in forums, tried debugging, but it didn't help. Any ideas?
The whole script
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class FlashActivity extends AppCompatActivity {
private Button buttonEnable;
private ImageView imageFlashlight;
private static final int CAMERA_REQUEST = 50;
private boolean flashLightStatus = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageFlashlight = (ImageView) findViewById(R.id.imageFlashlight);
buttonEnable = (Button) findViewById(R.id.buttonEnable);
final boolean hasCameraFlash = getPackageManager().
hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
boolean isEnabled = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED;
buttonEnable.setEnabled(!isEnabled);
imageFlashlight.setEnabled(isEnabled);
buttonEnable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(FlashActivity.this, new String[] {Manifest.permission.CAMERA}, CAMERA_REQUEST);
}
});
imageFlashlight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (hasCameraFlash) {
if (flashLightStatus)
flashLightOff();
else
flashLightOn();
} else {
Toast.makeText(FlashActivity.this, "No flash available on your device",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void flashLightOn() {
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
String cameraId = cameraManager.getCameraIdList()[0];
cameraManager.setTorchMode(cameraId, true);
flashLightStatus = true;
imageFlashlight.setImageResource(R.drawable.on);
} catch (CameraAccessException e) {
}
}
private void flashLightOff() {
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
String cameraId = cameraManager.getCameraIdList()[0];
cameraManager.setTorchMode(cameraId, false);
flashLightStatus = false;
imageFlashlight.setImageResource(R.drawable.off);
} catch (CameraAccessException e) {
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch(requestCode) {
case CAMERA_REQUEST :
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
buttonEnable.setEnabled(false);
buttonEnable.setText("Camera Enabled");
imageFlashlight.setEnabled(true);
} else {
Toast.makeText(FlashActivity.this, "Permission Denied for the Camera", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
The error of Log Cat
E/AndroidRuntime: FATAL EXCEPTION: main
Process: l.www.survivalbook, PID: 8117
java.lang.RuntimeException: Unable to start activity ComponentInfo{l.www.survivalbook/l.www.survivalbook.FlashActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference
at l.www.survivalbook.FlashActivity.onCreate(FlashActivity.java:39)
at android.app.Activity.performCreate(Activity.java:7183)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
the line, where error is shown (39 code line)
buttonEnable.setEnabled(!isEnabled);
imageFlashlight.setEnabled(isEnabled);
Here is xml script
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_compass"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textAlignment="center"
android:textSize="40sp"
android:textColor="#000"
android:textStyle="bold"
android:text="0°"
android:id="#+id/txt_azimuth"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/kompasas"
android:layout_below="#+id/txt_azimuth"
android:id="#+id/img_compass"/>
</RelativeLayout>
A null object Reference always points out that there is some object in your code that has no value.
Button myButton = null;
myButton.setVisibility(GONE);
The code above will always lead to the error that appears in your code. Your buttonEnable has no value. Try buttonEnable = new Button() or use findViewById if you declared the button within your layout XML.
enter image description here
I put a listener on each button that takes me to different activities.
The login button works perfectly, but the register button stops the app when I click on it.
I've tried to put a Toast message in the _btnreg listener, and it worked...
I got this error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.virtualshelter, PID: 24128
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.virtualshelter/com.example.android.virtualshelter.register}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2787)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6247)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.android.virtualshelter.register.onCreate(register.java:35)
at android.app.Activity.performCreate(Activity.java:6754)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2787)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6247)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
package com.example.android.virtualshelter;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity
{
Button _btnreg, _btnlogin;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_btnlogin = findViewById(R.id.btnlogin);
_btnreg = findViewById(R.id.btnreg);
_btnreg.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,register.class);
startActivity(intent);
}
});
_btnlogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,login.class);
startActivity(intent);
}
});
}
}
My register.java code
package com.example.android.virtualshelter;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class register extends AppCompatActivity
{
SQLiteOpenHelper openHelper;
SQLiteDatabase db;
Button _btnReg;
EditText _txtfname, _txtlname, _txtpass, _txtemail, _txtphone;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
openHelper = new DatabaseHelper(register.this);
_txtfname = findViewById(R.id.txtfname);
_txtlname = findViewById(R.id.txtlname);
_txtpass = findViewById(R.id.txtpass);
_txtemail = findViewById(R.id.txtemail);
_txtphone = findViewById(R.id.txtphone);
_btnReg = findViewById(R.id.btnreg);
_btnReg.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
db = openHelper.getWritableDatabase();
String fname = _txtfname.getText().toString();
String lname = _txtlname.getText().toString();
String pass = _txtpass.getText().toString();
String email = _txtemail.getText().toString();
String phone = _txtphone.getText().toString();
insertdata(fname, lname, pass, email, phone);
Toast.makeText(getApplicationContext(), "register successfully", Toast.LENGTH_LONG).show();
}
});
}
public void insertdata(String fname, String lname, String pass, String email, String phone)
{
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.COL_2, fname);
contentValues.put(DatabaseHelper.COL_3, lname);
contentValues.put(DatabaseHelper.COL_4, pass);
contentValues.put(DatabaseHelper.COL_5, email);
contentValues.put(DatabaseHelper.COL_6, phone);
long id = db.insert(DatabaseHelper.TABLE_NAME, null, contentValues);
}
}
I expect to go to activity register.java, but the app is crashing
My hunch is, you are not able find the button, causing a NPE when setting the listner. Could be that you don't have the button defined in R.layout.activity_main, but in a different layout.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Hello im new in stackover flow i want to try these website and ask for someones help in my android when i change the intent there's an error in my android monitor in android studio here is it.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kim.checkerv3, PID: 2970
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kim.checkerv3/com.example.kim.checkerv3.BudgetOutput}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.BaseBundle.getString(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.BaseBundle.getString(java.lang.String)' on a null object reference
at com.example.kim.checkerv3.BudgetOutput.onCreate(BudgetOutput.java:22)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
i didn't understand this i'd tried researching for solution and im still stuck on it.
Here the intent will be pass to other java class.
package com.example.kim.checkerv3;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import static android.content.Context.MODE_PRIVATE;
/**
* Created by KIM-PC on 12/5/2016.
*/
public class BudgetFragment extends android.support.v4.app.Fragment {
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_budget, container, false);
final EditText etCash = (EditText) v.findViewById(R.id.etCash);
final Button bBudget = (Button) v.findViewById(R.id.bBudget);
bBudget.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
SharedPreferences sharedpref = getContext().getSharedPreferences("user_id", MODE_PRIVATE);
String id = sharedpref.getString("user_id","");
final int budgeted = Integer.parseInt(etCash.getText().toString());
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray arr = jsonResponse.getJSONArray("message");
boolean success = jsonResponse.getBoolean("success");
System.out.println(budgeted/arr.length());
int total = budgeted/arr.length();
if (success) {
Intent intent = new Intent(getContext(), BudgetOutput.class);
Bundle b = new Bundle();
b.putString("total", String.valueOf(total));
getContext().startActivity(intent);
if (arr != null) {
int sum = 0;
for(int i = 0;i<arr.length();i++){
//listdata.add(arr.get(i).toString());
String money = arr.getJSONObject(i).getString("amount");
sum += Integer.parseInt(money);
}
SharedPreferences sharedPref1 = getActivity().getSharedPreferences("mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref1.edit();
editor.putInt("TotalSum", sum);
editor.commit();
System.out.println(sum);
//arrayAdapter.notifyDataSetChanged();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("Failed to fetch. Try again.")
.setNegativeButton("OK", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RecordRequest recordRequest = new RecordRequest(id, responseListener);
RequestQueue queue = Volley.newRequestQueue(getContext());
queue.add(recordRequest);
}
});
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
SharedPreferences sharedpref1 = getContext().getSharedPreferences("mypref", MODE_PRIVATE);
int budgeted = sharedpref1.getInt("TotalSum", 0);
System.out.println(budgeted/2);
}
}
and the class where the intent will be get.
package com.example.kim.checkerv3;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.TextView;
/**
* Created by KIM-PC on 12/6/2016.
*/
public class BudgetOutput extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_output);
final TextView tvOutput = (TextView) findViewById(R.id.tvoutput);
Bundle b = getIntent().getExtras();
String output=b.getString("total");
if(b !=null)
output = b.getString("total");
tvOutput.setText(output+" Per cheque record.");
}
}
if there is someone who could solve i appreciate and give my thanks to you.
Well, you forgot to add your Bundle to the Intent
Intent intent = new Intent(getContext(), BudgetOutput.class);
Bundle b = new Bundle();
b.putString("total", String.valueOf(total));
intent.putExtras(b);
getContext().startActivity(intent);