setDataSource with Uri causes NullPointerException - java

Well, this is the onClick method of a button:
public void aggiungi (View v){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("audio/*");
startActivityForResult(Intent.createChooser(intent, "Select"), PICK_AUDIO_REQUEST_CODE);
}
And outside I've handled the output:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_AUDIO_REQUEST_CODE){
if (resultCode == RESULT_OK){
Uri uri_to_use = data.getData();
setAudioToButton(uri_to_use);
}
}
}
And here's the setAudioToButton method called
public void setAudioToButton(final Uri audio){
PercentRelativeLayout percentRelativeLayout = (PercentRelativeLayout)findViewById(R.id.main_layout);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(43, 12);
layoutParams.addRule(PercentRelativeLayout.ALIGN_PARENT_RIGHT);
layoutParams.addRule(PercentRelativeLayout.BELOW, R.id.quattro);
Button button = new Button(this);
button.setLayoutParams(layoutParams);
PercentRelativeLayout.LayoutParams layoutParams1 = (PercentRelativeLayout.LayoutParams)button.getLayoutParams();
PercentLayoutHelper.PercentLayoutInfo percentLayoutInfo = layoutParams1.getPercentLayoutInfo();
percentLayoutInfo.heightPercent = 0.12f;
percentLayoutInfo.widthPercent = 0.43f;
percentLayoutInfo.topMarginPercent = 0.063f;
percentLayoutInfo.leftMarginPercent = 0.007f;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mediaPlayer != null){mediaPlayer.stop();}
try {mediaPlayer.setDataSource(getBaseContext(), audio);} catch (IOException error){error.printStackTrace();}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
});
button.setText("start");
percentRelativeLayout.addView(button);
}
The problem is when I click on the new button to make it sound, I have a NullPointerException:
08-22 02:32:43.164 11880-11880/com.example.utente.usefulsounds E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.utente.usefulsounds, PID: 11880
Theme: themes:{}
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setDataSource(android.content.Context, android.net.Uri)' on a null object reference
at com.example.utente.usefulsounds.MainActivity$1.onClick(MainActivity.java:182)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21158)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I am wondering why this happens, I can't understand
**
EDIT:
**
I've put this in the onCreate method
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE_REQUEST_CODE);
}
But it didn't worked
Now I've tried in a different way: intead of passing an Uri to the MediaPlayer, I've passed a filedescriptor:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mediaPlayer != null){mediaPlayer.stop();}
File file = new File(audio.getPath());
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(file);
try {mediaPlayer.setDataSource(fileInputStream.getFD());} catch (IOException error){error.printStackTrace();}
}catch (IOException ioe){button.setText("FILE ERROR");}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
});
The button appears with the text "select", so there isn't any problem with the file (otherwise it should have been "file error"), but when I click on that I still have a crash caused by a NullPointerException with mediaPlayer. Why this? I can't understand

HERE'S THE ANSWER
Instead of doing a setDataSource() method you have to use simply a create() method :)
Eg.
MediaPlayer.create(getApplicationContext(), yourAudioUri).start();
Happy coding and have fun :)

Related

Media Player is a null object, when made from an activity which was launched from a BroadCastReceiver

I am trying to play a MediaPlayer from a activity, which was OPENED BY A BROADCAST RECEIVER. This works fine, if I play an internal file from the R.raw folder. But if I try to access a Mp3 file via a URI, it doesn't work anymore.
public class AlarmScreen extends AppCompatActivity {
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_screen);
mediaPlayer = new MediaPlayer();
startMusic();
}
private void startMusic() {
String stringUri = element.getUri();
if (!(stringUri.equals(""))){
Uri uri = Uri.parse(stringUri);
mediaPlayer = MediaPlayer.create(this, uri);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mediaPlayer.start();
}
}, 1000);
}
}
The Error I get looks like this:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
I also tried to make the Media Player the following way, but it led to the same result:
Uri uri = Uri.parse(stringUri);
try {
mediaPlayer.setDataSource(this, uri);
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.prepareAsync();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mediaPlayer.start();
}
}, 300);
I guess that the problem lies somewhere within the permissions, because as far as I know the BroadCastReceivers don't have the same permissions as the normal apps.
If you need more code, please let me know.
EDIT:
I have narrowed down the problem by making the following test-project:
Here 2 Uris are created. For Uri1, I use the data from the chooser. For Uri2 I use the Uri-String from a previous round. Then these Uris are played in the start(). If I play Uri1, it works always. But if I play Uri2, it only works if Uri1 is equal to Uri2. This is only the case if the same music-file is chosen in the chooser again, as in the round where I originally copied Uri2.
I really don't understand what I'm doing wrong. Is there another way, to access music-files from your device?
private void play(){
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(this, uri2);
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.prepareAsync();
mediaPlayer.start();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uri2 = Uri.parse("content://com.android.providers.media.documents/document/audio%3A17207");
uri1 = data.getData();
String str = uri.toString();
}
private void start(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("audio/*");
startActivityForResult(Intent.createChooser(intent, "choose:"), 1);
}
I think your problem is because of permissions.
Try to add the READ_EXTERNAL_STORAGE to your manifest.
Something like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.snazzyapp">
...
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
...
<application ...>
...
</application>
</manifest>

data null onActivityResult

Activity results is NullPointerException, What I have done wrong or missed?
Photo gallery application(Eventually), followed the instructions on the android developer site about taking photos with inbuilt camera. onActivityResult giving null pointer. I am new to android so can't figure it out.
Because of this it crashes, i expect it to show a bitmap in the activity.
public class aCamera extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_TAKE_PHOTO = 1;
ImageView imageView;
String currentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a_camera);
dispatchTakePictureIntent();
}
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) {
File photoFile = null;
try {
photoFile = createImageFile();
Log.i("DTPI-1", "dispatchTakePictureIntent: The IF AND TRY");
} catch (IOException ex) {
Log.i("DTPI-3" , "dispatchTakePictureIntent: catch");
}
// Continue only if the File was successfully created
if (photoFile != null) {
Log.i("photoURI", "dispatchTakePictureIntent: PHOTO FILE NOT EMPTY");
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
//setResult(RESULT_OK, takePictureIntent);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
Log.i("CIF -1", "createImageFile: Create FILE");
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;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("Result", "onActivityResult: WE GET HERE");
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView = findViewById(R.id.imageView);
imageView.setImageBitmap(imageBitmap);
}
}
Error logs.
2019-05-06 20:01:33.555 23363-23363/com.example.camera E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.camera, PID: 23363
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.camera/com.example.camera.aCamera}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4339)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4382)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1654)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:251)
at android.app.ActivityThread.main(ActivityThread.java:6572)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at com.example.camera.aCamera.onActivityResult(aCamera.java:81)
at android.app.Activity.dispatchActivityResult(Activity.java:7235)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4335)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4382) 
at android.app.ActivityThread.-wrap19(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1654) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:251) 
at android.app.ActivityThread.main(ActivityThread.java:6572) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
The camera saves the image to the photoUri that you supply in your Intent. In onActivityResult you have to get the Bitmap from that file.
The line putExtra is the issue. Delete that line and receive bitmap in
onActivityResult like mentioned below.
#Override
protected void onActivityResult(int requestCode, int resultcode, Intent intent) {
if (requestCode == REQUEST_TAKE_PHOTO && resultcode == RESULT_OK) {
Uri uri = intent.getData();
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
image.setImageBitmap(bitmap);
}
}
Hope this works. You will see the explaination here on a post with similar issue.
As mentioned by #aalap patel, the issue is not with onActivityResult, it is with one line in dispatchTakePictureIntent method.
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
adding to this is the code that he also mentions.

Android MediaPlayer unknown error

I am creating a MediaPlayer instance in MainActivity's onCreate() method like this
MediaPlayer mPlayer = MediaPlayer.create(this, Uri.fromFile(new File("/storage/emulated/0/soundrecorder/My recording #26.wav")));
It is created successfully but I get this error:
07-06 18:33:44.266 18366-18366/com.audiorecorder.wel.voicerecorder E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
07-06 18:33:44.267 18366-18366/com.audiorecorder.wel.voicerecorder E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
Also tried this but the same error on logcat:
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(this, Uri.fromFile(new File("/storage/emulated/0/soundrecorder/My recording #26.wav")));
} catch (IOException e) {
e.printStackTrace();
}
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
I have tried different audio files with different formats but result is the same error. I have also tried searching the answer on stackoverflow but could not resolve the issue. Can you help me on this?
It seems there is some issue with your file. Update that with this :
musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
And then follow these steps:
1. getLoaderManager().initLoader(0,null,this);
2. #Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
switch (id){
case 0 : return new CursorLoader(getApplicationContext(),musicUri,null,null,null,null);
return new Loader<>(this);
}
3. #Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case 0 :
if(data != null && data.moveToFirst()) {
songTitleColumnIndex = data.getColumnIndex(MediaStore.Audio.Media.TITLE);
do {
songTitle = data.getString(songTitleColumnIndex);
songsList.add(songTitle);
} while (data.moveToNext());
}
break;
So the SongTitles are being put in the SongList which is an ArraList of String Type.
Hope This Helps.
Try using a FileInputStream to start your MediaPlayer with a FileDescriptor instead:
String yourFilePath = "/wherever/your/file/is.wav";
MediaPlayer mPlayer = new MediaPlayer();
try{
FileInputStream inputStream = new FileInputStream(yourFilePath);
mPlayer.setDataSource(inputStream.getFD());
inputStream.close();
mPlayer.prepare();
mPlayer.start();
}catch (IOException e){
Log.e("IOException", e.getMessage());
}

Null object reference onReceive BroadcastReceiver

I'm using two activities, the main one, and the camera one. In the mainActivity i call startActivity(new Intent(this, CameraActivity));
Now, when camera activity starts, the onCreate() is:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_preview);
View myView= (View) findViewById(R.id.camera_previeww);
myView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
cameraID= Camera.CameraInfo.CAMERA_FACING_FRONT;
mCamera=openCamera(cameraID);
mCamera.startPreview();
IntentFilter filter = new IntentFilter();
filter.addAction(Tabbed.BROADCAST_ACTION_TABBED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(this);
bm.registerReceiver(mBroadcastReceiver, filter);
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) this.findViewById(R.id.camera_previeww);
preview.addView(mPreview);
}
The openCamera(int cameraID) method is:
public Camera openCamera(int cameraIDD){
Camera c=null;
try{
c=Camera.open(cameraIDD);
}catch (Exception e){
Log.d("Camera Activity", e.getMessage());
}
return c;
}
Also I'm using a BroadcastReceiver like:
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
byte [] data=new byte[3];
if (intent.getAction().equals(Tabbed.BROADCAST_ACTION_TABBED)) {
data = intent.getByteArrayExtra(Tabbed.EXTRA_PARAM_BYTE);
}
if (data[FINGER]==MIDDLE_FINGER && data[TYPE]==SINGLE_TAP){
//switchCamera();
//releaseCamera();
//mCamera=Camera.open();
}
else if (data[FINGER]==MIDDLE_FINGER && data[TYPE]==DOUBLE_TAP){
// HAVE TO GO BACK
kill_activity();
}
else if (data[FINGER]==INDEX_FINGER && data[TYPE]==SINGLE_TAP){
mCamera.takePicture(null, null, mPicture);
}
// kill activity
}
};
And some other methods:
#Override
protected void onPause() {
super.onPause();
//releaseCamera(); // release the camera immediately on pause event
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
void kill_activity()
{
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
releaseCamera();
finish();
}
Here is the crash:
FATAL EXCEPTION: main
Process: com.etu.goglove, PID: 6008
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.Camera.takePicture(android.hardware.Camera$ShutterCallback, android.hardware.Camera$PictureCallback, android.hardware.Camera$PictureCallback)' on a null object reference
at com.etu.goglove.CameraActivity$2.onReceive(CameraActivity.java:155)
at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:297)
at android.support.v4.content.LocalBroadcastManager.access$000(LocalBroadcastManager.java:46)
at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:116)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
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)
With all this, I'm trying to take a photo when I receive broadcast intents. So, after my activity has started, I open mCamera and when I receive an intent I make the photo or I get back. At the first time, i can take the photo and then I finish my activity. If i try to restart cameraActivity from the mainActivity, calling startActivity(intent),in the onCreate() camera is open and it is not null (checked with the debugger), but this time, when I get in the onReceive() method, mCamera is always null, so I get a null object reference on mCamera!(when I'm trying to do mCamera.takePicture()) don't know how ...
Thanks!
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
byte [] data=new byte[3];
if (intent!=null && intent.getAction().equals(Tabbed.BROADCAST_ACTION_TABBED)) {
data = intent.getByteArrayExtra(Tabbed.EXTRA_PARAM_BYTE);
if (data[FINGER]==MIDDLE_FINGER && data[TYPE]==SINGLE_TAP){
//switchCamera();
//releaseCamera();
//mCamera=Camera.open();
}
else if (data[FINGER]==MIDDLE_FINGER && data[TYPE]==DOUBLE_TAP){
// HAVE TO GO BACK
kill_activity();
}
else if (data[FINGER]==INDEX_FINGER && data[TYPE]==SINGLE_TAP){
mCamera.takePicture(null, null, mPicture);
}
}
// kill activity
}
};

Capture Image, Upload To Firebase And Retrieve Java Android Studio

I am very sorry if this may be a question with a simple solution.
What Am I Trying To Do?
Capture an image from a Button
Upload that image to Firebase storage
Retrieve that image in an ImageView
What Is My Trouble So Far?
Takes picture, but crashes when I click the tick.
Hence nothing is being uploaded or being achieved.
My Code
P.N I have looked at lots of other forums and video tutorials but nothing seems to be working. Hopefully someone can help.
public class LeaderboardActivity extends AppCompatActivity {
private static final int CAMERA_REQUEST_CODE = 1;
private static final int REQUEST_TAKE_PHOTO = 1;
private StorageReference mStorage;
private ProgressDialog mProgress;
String mCurrentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leaderboard);
mStorage = FirebaseStorage.getInstance().getReference();
final Button bImage = (Button) findViewById(R.id.bCamera);
final ImageView ivPic = (ImageView) findViewById(R.id.ivPic);
mProgress = new ProgressDialog(this);
bImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
mProgress.setMessage("Uploading Image");
mProgress.show();
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photo").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener < UploadTask.TaskSnapshot > () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Toast.makeText(LeaderboardActivity.this, "Uploading Complete...", Toast.LENGTH_LONG);
}
});
}
}
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
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
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
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
}
Error In Android Monitor
Not sure if this will help
02-13 02:30:32.693 2133-2133/com.example.rikhi.chores E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rikhi.chores, PID: 2133
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.rikhi.chores/com.example.rikhi.chores.LoginRegister.InsideMainActivity.LeaderboardActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4089)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at com.example.rikhi.chores.LoginRegister.InsideMainActivity.LeaderboardActivity.onActivityResult(LeaderboardActivity.java:74)
at android.app.Activity.dispatchActivityResult(Activity.java:6932)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132) 
at android.app.ActivityThread.-wrap20(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
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) 
I have looked at other people who had the same problem, followed what they said nothing happend, followed the Google Android instructions for this and again same problem.
On button, click remove that intent and just call your
dispatchTakePictureIntetnt() method on Onclick button Listener
Also, check go to your emulator settings, and check your camera
permission is on for your this app and also go to firebase console
and check the rules if, rules are not equal to null made them equal
to null then run your app because !=null rules only work when there
is an authentication method in your app

Categories

Resources