I know there are a few of these on SO already but none of them really were able to help my issue, but when I am running the code and start recording audio and then press my stop button it always fails because it is in the wrong state. I am not sure how I would go about fixing my states for this.
Here is my MainActivity.java code:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.IOException;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
public class MainActivity extends AppCompatActivity {
Button buttonStartRecording, buttonStopRecording, buttonPlayLastRecordAudio,
buttonStopPlayingRecording;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder;
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer;
AudioManager audioManager;
boolean isAudioPlayInSameDevice = true;
// AudioRouter audioRouter;
RadioGroup mRadioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStartRecording = (Button) findViewById(R.id.start_recording);
buttonStopRecording = (Button) findViewById(R.id.stop_rec);
buttonPlayLastRecordAudio = (Button) findViewById(R.id.play_last_rec);
buttonStopPlayingRecording = (Button) findViewById(R.id.stop_playing_btn);
// mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);
buttonStopRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);
buttonStartRecording.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View view) {
// Check audio permission
if (checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "AudioRecording.3gp";
// Start Media recorder
MediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buttonStartRecording.setEnabled(false);
buttonStopRecording.setEnabled(true);
Toast.makeText(MainActivity.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
buttonStopRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonStopRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
buttonStartRecording.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
// Stop Media recorder
mediaRecorder.stop();
Toast.makeText(MainActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();
}
});
buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) throws IllegalArgumentException,
SecurityException, IllegalStateException {
int selectedId = 1;
if (selectedId == 1) {
isAudioPlayInSameDevice = true;
} else {
isAudioPlayInSameDevice = false;
}
// if you want to play audio on your Mobile speaker then set isAudioPlayInSameDevice true
// and if you want to play audio to connected device then set isAudioPlayInSameDevice false.
if (isAudioPlayInSameDevice) {
audioManager.setMode(audioManager.STREAM_MUSIC);
audioManager.setSpeakerphoneOn(true);
} else {
audioManager.setSpeakerphoneOn(false);
audioManager.setMode(audioManager.MODE_NORMAL);
}
audioManager.setBluetoothScoOn(false);
audioManager.stopBluetoothSco();
buttonStopRecording.setEnabled(false);
buttonStartRecording.setEnabled(false);
buttonStopPlayingRecording.setEnabled(true);
mediaPlayer = new MediaPlayer();
try {
// Start media player
System.out.println("Recorded Audio Path-" + AudioSavePathInDevice);
mediaPlayer.setDataSource(AudioSavePathInDevice);
if (isAudioPlayInSameDevice) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "Recording Playing",
Toast.LENGTH_LONG).show();
}
});
buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonStopRecording.setEnabled(false);
buttonStartRecording.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
if (mediaPlayer != null) {
// Stop Media Player
mediaPlayer.stop();
mediaPlayer.release();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
MediaRecorderReady();
}
}
}
});
}
private BroadcastReceiver mBluetoothScoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
System.out.println("ANDROID Audio SCO state: " + state);
if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
/*
* Now the connection has been established to the bluetooth device.
* Record audio or whatever (on another thread).With AudioRecord you can record with an object created like this:
* new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
* AudioFormat.ENCODING_PCM_16BIT, audioBufferSize);
*
* After finishing, don't forget to unregister this receiver and
* to stop the bluetooth connection with am.stopBluetoothSco();
*/
}
}
};
#RequiresApi(api = Build.VERSION_CODES.O)
public void MediaRecorderReady() {
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_2_TS);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
registerReceiver(mBluetoothScoReceiver, intentFilter);
audioManager = (AudioManager) getApplicationContext().getSystemService(getApplicationContext().AUDIO_SERVICE);
// Start Bluetooth SCO.
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(true);
audioManager.startBluetoothSco();
// Stop Speaker.
audioManager.setSpeakerphoneOn(false);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mBluetoothScoReceiver);
// Stop Bluetooth SCO.
audioManager.stopBluetoothSco();
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(false);
// Start Speaker.
audioManager.setSpeakerphoneOn(true);
}
private void requestPermission() {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length > 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
// if (StoragePermission && RecordPermission) {
// Toast.makeText(BluetoothAudioRecorder.this, "Permission Granted",
// Toast.LENGTH_LONG).show();
// } else {
// Toast.makeText(BluetoothAudioRecorder.this,"Permission Denied",Toast.LENGTH_LONG).show();
// }
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
}
And then my logcat of when the error occurs:
2019-11-24 11:26:54.440 29627-29683/com.example.esense_application E/libc: Access denied finding property "vendor.gralloc.disable_ahardware_buffer"
2019-11-24 11:26:54.435 29627-29627/com.example.esense_application W/RenderThread: type=1400 audit(0.0:17779): avc: denied { read } for name="u:object_r:vendor_default_prop:s0" dev="tmpfs" ino=24699 scontext=u:r:untrusted_app:s0:c7,c257,c512,c768 tcontext=u:object_r:vendor_default_prop:s0 tclass=file permissive=0
2019-11-24 11:26:54.487 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 1
2019-11-24 11:26:54.487 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 2
2019-11-24 11:26:54.868 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 1
2019-11-24 11:26:57.769 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 1
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: java.io.FileNotFoundException: /storage/emulated/0/AudioRecording.3gp: open failed: EACCES (Permission denied)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at libcore.io.IoBridge.open(IoBridge.java:496)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at java.io.RandomAccessFile.<init>(RandomAccessFile.java:289)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at java.io.RandomAccessFile.<init>(RandomAccessFile.java:152)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.media.MediaRecorder.prepare(MediaRecorder.java:1046)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at com.example.esense_application.MainActivity$1.onClick(MainActivity.java:67)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View.performClick(View.java:7140)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View.performClickInternal(View.java:7117)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View.access$3500(View.java:801)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View$PerformClick.run(View.java:27351)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.os.Handler.handleCallback(Handler.java:883)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.os.Handler.dispatchMessage(Handler.java:100)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.os.Looper.loop(Looper.java:214)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7356)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at java.lang.reflect.Method.invoke(Native Method)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.Linux.open(Native Method)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:252)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7255)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.IoBridge.open(IoBridge.java:482)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: ... 15 more
2019-11-24 11:27:03.528 29627-29627/com.example.esense_application E/MediaRecorder: stop called in an invalid state: 4
2019-11-24 11:27:03.528 29627-29627/com.example.esense_application D/AndroidRuntime: Shutting down VM
2019-11-24 11:27:03.529 29627-29627/com.example.esense_application E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.esense_application, PID: 29627
java.lang.IllegalStateException
at android.media.MediaRecorder.stop(Native Method)
at com.example.esense_application.MainActivity$2.onClick(MainActivity.java:98)
at android.view.View.performClick(View.java:7140)
at android.view.View.performClickInternal(View.java:7117)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27351)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2019-11-24 11:27:03.540 29627-29627/com.example.esense_application I/Process: Sending signal. PID: 29627 SIG: 9
Your MediaRecorder is throwing when you try to stop() it because it has never entered the "recording" state. In fact, it never even entered the "prepared" state, because your call to prepare() did not complete successfully.
SOLUTION
Do not allow a call to start() until the prepare() call has returned (without throwing).
Do not allow a call to stop() until the start() call has returned (without throwing).
Make sure you have chosen a valid location for your output file. Try using getExternalFilesDir( null ) instead of Environment.getExternalStorageDirectory(). The bad file path is the reason your prepare() call is currently failing with an EACCESS.
As you can see, swallowing exceptions without addressing their root cause (i.e., just doing a e.printStackTrace() and carrying on), can rapidly lead to problems -- even in rough code used for learning/experimentation. If you are going to add an exception handler, it is better to provide real error handling -- and always make sure you understand why an exception is being thrown.
Related
I want to take an user Screenshot, I used this code. I was take 3 permission, READ_EXTERNAL_STORE,WRITE_EXTERNAL_STORE, and READ_EXTERNAL_STORAGE. Problem not fix. It show open failed: EPERM (Operation not permitted)
public void tackeAndSaveScreenShot(Activity mActivity) {
View MainView = mActivity.getWindow().getDecorView();
MainView.setDrawingCacheEnabled(true);
MainView.buildDrawingCache();
Bitmap MainBitmap = MainView.getDrawingCache();
Rect frame = new Rect();
mActivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
//to remove statusBar from the taken sc
int statusBarHeight = frame.top;
//using screen size to create bitmap
int width = mActivity.getWindowManager().getDefaultDisplay().getWidth();
int height = mActivity.getWindowManager().getDefaultDisplay().getHeight();
Bitmap OutBitmap = Bitmap.createBitmap(MainBitmap, 0, statusBarHeight, width, height - statusBarHeight);
MainView.destroyDrawingCache();
try {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
//you can also using current time to generate name
String name="YourName";
File file = new File(path, name + ".png");
fOut = new FileOutputStream(file);
OutBitmap.compress(Bitmap.CompressFormat.PNG, 1000, fOut);
fOut.flush();
fOut.close();
//this line will add the saved picture to gallery
MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
When I check on my Logcat. they show the problem is in
fOut = new FileOutputStream(file);
I get permission properly.
private void userPermission2(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.MANAGE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_CODE1);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE && grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
userPermission2();
}else {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
}
I tried many why but don'work. Every time is the same problem.
The log is.
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10351; state: ENABLED
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/YourName.png: open failed: EPERM (Operation not permitted)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:492)
W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:236)
W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
W/System.err: at com.example.myapplication.MainActivity.tackeAndSaveScreenShot(MainActivity.java:93)
W/System.err: at com.example.myapplication.MainActivity$1.onClick(MainActivity.java:64)
W/System.err: at android.view.View.performClick(View.java:7570)
W/System.err: at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1202)
W/System.err: at android.view.View.performClickInternal(View.java:7525)
W/System.err: at android.view.View.access$3900(View.java:836)
W/System.err: at android.view.View$PerformClick.run(View.java:28680)
W/System.err: at android.os.Handler.handleCallback(Handler.java:938)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err: at android.os.Looper.loop(Looper.java:254)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:8243)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:612)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1006)
W/System.err: Caused by: android.system.ErrnoException: open failed: EPERM (Operation not permitted)
W/System.err: at libcore.io.Linux.open(Native Method)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:8125)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:478)
W/System.err: ... 16 more
String path = Environment.getExternalStorageDirectory().toString();
Change to:
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
And for Android 10 devices add android:legacyExternalStorage="true" to application tag in manifest file.
For Android 13+ devices you do not need any permission.
I am trying to build a music recording app and the recording and stopping part is working, but it looks like the app cannot play the recorded file because it throws this error:
java.io.FileNotFoundException: /storage/emulated/0/CKENCAudioRecording.3gp: open failed: ENOENT (No such file or directory)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:492)
W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:160)
W/System.err: at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1259)
W/System.err: at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1230)
W/System.err: at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1195)
W/System.err: at com.example.karaokebuddies.record$3.onClick(record.java:99)
W/System.err: at android.view.View.performClick(View.java:8160)
W/System.err: at android.widget.TextView.performClick(TextView.java:16193)
W/System.err: at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
W/System.err: at android.view.View.performClickInternal(View.java:8137)
W/System.err: at android.view.View.access$3700(View.java:888)
W/System.err: at android.view.View$PerformClick.run(View.java:30236)
W/System.err: at android.os.Handler.handleCallback(Handler.java:938)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err: at android.os.Looper.loop(Looper.java:246)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:8462)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:596)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
W/System.err: at libcore.io.Linux.open(Native Method)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:8323)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:478)
The error is referring to this line inside the play.setOnClicklistener.
mediaPlayer.setDataSource(AudioSavePathInDevice);
//AudioSavePathInDevice = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + CreateRandomAudioFileName(5) + "AudioRecording.3gp";
I've searched through a lot of similar cases in stack overflow, but none really helped.
I included necessary permissions and set requestLegacyExternalStorage to true:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
android:requestLegacyExternalStorage="true"
Here's my record.java:
package com.example.karaokebuddies;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.IOException;
import java.util.Random;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
public class record extends AppCompatActivity {
private Button play, stop, record, stopPlaying;
private MediaRecorder myAudioRecorder;
private String outputFile;
private String AudioSavePathInDevice = null;
Random random;
String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
public static final int RequestPermissionCode = 1;
private MediaPlayer mediaPlayer;
boolean isRecording = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.record);
play = (Button) findViewById(R.id.play);
stop = (Button) findViewById(R.id.stop);
record = (Button) findViewById(R.id.record);
stopPlaying = (Button) findViewById(R.id.button_stopPlaying);
stop.setEnabled(false);
play.setEnabled(false);
stopPlaying.setEnabled(false);
random = new Random();
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkPermission()) {
AudioSavePathInDevice = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + CreateRandomAudioFileName(5) + "AudioRecording.3gp";
MediaRecorderReady();
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
isRecording = true;
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
record.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isRecording) {
myAudioRecorder.stop();
}
myAudioRecorder.release();
isRecording = false;
stop.setEnabled(false);
play.setEnabled(true);
record.setEnabled(true);
stopPlaying.setEnabled(false);
Toast.makeText(getApplicationContext(), "Audio Recorded successfully", Toast.LENGTH_LONG).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws IllegalArgumentException, SecurityException, IllegalStateException {
// MediaPlayer mediaPlayer = new MediaPlayer();
stop.setEnabled(false);
record.setEnabled(false);
stopPlaying.setEnabled(true);
mediaPlayer = new MediaPlayer();
try {
// mediaPlayer.setDataSource(outputFile);
mediaPlayer.setDataSource(AudioSavePathInDevice);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
Toast.makeText(getApplicationContext(), "Playing Audio", Toast.LENGTH_LONG).show();
}
});
stopPlaying.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stop.setEnabled(false);
record.setEnabled(true);
stopPlaying.setEnabled(false);
play.setEnabled(true);
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
MediaRecorderReady();
}
}
});
}
public void MediaRecorderReady() {
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(AudioSavePathInDevice);
}
public String CreateRandomAudioFileName(int string) {
StringBuilder stringBuilder = new StringBuilder(string);
int i = 0;
while (i < string) {
stringBuilder.append(RandomAudioFileName.charAt(random.nextInt(RandomAudioFileName.length())));
i ++;
}
return stringBuilder.toString();
}
private void requestPermission() {
ActivityCompat.requestPermissions(record.this, new String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length > 0) {
boolean StoragePermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (StoragePermission && RecordPermission) {
Toast.makeText(record.this, "Permission Granted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(record.this, "Permission Denied", Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
}
}
As I was searching for a solution, I was wondering if the cause of this error is because I own a Galaxy s21+, which does not have an external storage, and I'm trying to save the recorded file into external storage directory. If so, would there be a solution to my situation? (i.e. saving to an internal storage?). Or, is there something else that I'm doing wrong?
Thank you in advance for your support!
First of all, when Android references "External Storage", it doesn't refer to an SD card. From this link:
"Categories of storage locations
Android provides two types of physical storage locations: internal storage and external storage. On most devices, internal storage is smaller than external storage. However, internal storage is always available on all devices, making it a more reliable place to put data on which your app depends."
The File Not Found could be related to two issues:
You do not have the correct permissions
The folder or file doesn't exist
If you review the error in your Logcat, you can usually determine the specific details. Also, using a File app on your device, you should be able to see if file with that name actually does in that folder.
Double-check to ensure that the permissions have been granted/accepted.
What level SDK are you targeting? If you have targetSdkVersion 30 in your app's build.gradle file, you need to update your code to adhere to a recent policy change that Google made.
If you aren't sure if the directory exists, you can use code such as this to create it:
final File root = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)));
// Create the directory if it doesn't exist
if (!root.exists()) {
boolean wasSuccessful = root.mkdirs();
// Display Toast message if the directory creation wasn't successful
if (!wasSuccessful) {
mToast = Toast.makeText(this, R.string.photo_directory_not_created_error, Toast.LENGTH_SHORT);
mToast.show();
}
}
I am trying to build an application that uses a Google maps activity using Android Studio.
I am facing issue: every time I try to launch the activity the app crashes. When I am using an emulator with SDK 24, the activity launches, it requires my permission and then it gives me an authentication error, even though I placed the correct API key.
On an emulator with SDK 26 the activity doesn't even launch and it crashes instantly.
Can you please help with this?
MapsActivity
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.util.ArrayList;
#SuppressWarnings("unchecked")
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onMapReady: map is ready");
mMap = googleMap;
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
private static final String TAG = "MapsActivity";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 15f;
//vars
private Boolean mLocationPermissionsGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
getLocationPermission();
}
private void getDeviceLocation(){
Log.d(TAG, "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try{
if(mLocationPermissionsGranted){
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()){
Log.d(TAG, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM);
}else{
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(MapsActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException e){
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
}
}
private void moveCamera(LatLng latLng, float zoom){
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void initMap(){
Log.d(TAG, "initMap: initializing map");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
}
private void getLocationPermission(){
Log.d(TAG, "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = true;
initMap();
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: called.");
mLocationPermissionsGranted = false;
switch(requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if(grantResults.length > 0){
for(int i = 0; i < grantResults.length; i++){
if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = false;
Log.d(TAG, "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d(TAG, "onRequestPermissionsResult: permission granted");
mLocationPermissionsGranted = true;
//initialize our map
initMap();
}
}
}
}
}
Error from the logcat for an emulator with SDK 24:
06-21 16:52:53.625 13392-13392/com.example.raluca.geoloc.feature E/art: The String#value field is not present on Android versions >= 6.0
06-21 16:52:55.011 1314-1321/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
06-21 16:52:55.452 13392-13560/com.example.raluca.geoloc.feature E/Google Maps Android API: Authorization failure. Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map.
06-21 16:52:55.454 13392-13560/com.example.raluca.geoloc.feature E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
Ensure that the "Google Maps Android API v2" is enabled.
Ensure that the following Android Key exists:
API Key: XXX_Key
Android Application (<cert_fingerprint>;<package_name>): D3:DF:7B:C7:09:CA:00:9F:32:DD:93:98:D6:E2:09:A1:18:B1:F6:6B;com.example.raluca.geoloc.feature
06-21 16:53:01.866 13392-13392/com.example.raluca.geoloc.feature E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.raluca.geoloc.feature, PID: 13392
java.lang.RuntimeException: Failure delivering result ResultInfo{who=#android:requestPermissions:, request=1234, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.example.raluca.geoloc.feature/com.example.raluca.geoloc.feature.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4053)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
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:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at com.example.raluca.geoloc.feature.MapsActivity.initMap(MapsActivity.java:110)
at com.example.raluca.geoloc.feature.MapsActivity.onRequestPermissionsResult(MapsActivity.java:154)
at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:7067)
at android.app.Activity.dispatchActivityResult(Activity.java:6919)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4049)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
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:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
06-21 16:53:02.076 1314-1322/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
06-21 16:53:05.957 8187-8220/? E/InputDispatcher: channel '65bcf76 com.example.raluca.geoloc.feature/com.example.raluca.geoloc.feature.LoginActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
06-21 16:53:05.957 8187-8220/? E/InputDispatcher: channel '23dfb3a com.example.raluca.geoloc.feature/com.example.raluca.geoloc.feature.MapsActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
06-21 16:53:26.978 8543-12462/? E/NetworkScheduler: Unrecognised action provided: android.intent.action.PACKAGE_REMOVED
06-21 16:53:27.653 8543-11730/? E/NetworkScheduler: Unrecognised action provided: android.intent.action.PACKAGE_REPLACED
06-21 16:53:28.495 8906-13710/? E/FontsPackageChangeOp: Error adding manifest dependency for newly downloaded font {Press Start 2P, wdth 100.0, wght 400, ital 0.0, bestEffort false}
06-21 16:53:28.507 8906-13053/? E/FontDisk: Error inserting metadata for Press Start 2P
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/user/0/com.google.android.gms/databases/metadata.db
at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1442)
at vdo.run(Unknown Source)
at ovb.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431):27)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at pbc.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431))
at java.lang.Thread.run(Thread.java:761)
06-21 16:53:29.228 13637-13764/? E/art: The String#value field is not present on Android versions >= 6.0
06-21 16:53:29.611 13637-13764/? E/Finsky: [464] com.google.android.finsky.am.c.a(34): Unable to build selector: /storage/emulated/0/Download/marketenvs.csv (No such file or directory)
06-21 16:53:30.423 13637-13637/? E/Finsky: [1] com.google.android.finsky.wear.y.a(3): onConnectionFailed: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null}
06-21 16:53:35.484 13637-13828/? E/Finsky: [483] com.google.android.finsky.splitinstallservice.ad.a(3): Can't schedule deferred install. No modules found.
06-21 16:53:36.939 13637-13637/? E/Finsky: [1] com.google.android.finsky.wear.y.a(3): onConnectionFailed: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null}
06-21 16:53:37.759 13836-13836/? E/art: The String#value field is not present on Android versions >= 6.0
06-21 16:53:38.320 8906-8965/? E/AsyncOpDispatcher: Unable to get current module info in ModuleManager created with non-module Context
06-21 16:53:39.373 8543-13891/? E/BluetoothAdapter: Bluetooth binder is null
06-21 16:53:39.503 8543-13891/? E/GCoreUlr: java.lang.IllegalStateException: Missing location or location status: 3016643, -1, 3781840, 7160153
at awot.a(:com.google.android.gms#12685026#12.6.85 (040700-197041431):387)
at awos.a(:com.google.android.gms#12685026#12.6.85 (040700-197041431):12)
at awos.handleMessage(:com.google.android.gms#12685026#12.6.85 (040700-197041431):7)
at oup.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431):6)
at ovb.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431):27)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at pbc.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431))
at java.lang.Thread.run(Thread.java:761)
06-21 16:53:40.868 12038-13901/? E/art: The String#value field is not present on Android versions >= 6.0
06-21 16:58:10.742 8543-13895/? E/BluetoothAdapter: Bluetooth binder is null
06-21 16:58:10.743 8543-13895/? E/GCoreUlr: java.lang.IllegalStateException: Missing location or location status: 3016643, -1, 3781840, 7431479
at awot.a(:com.google.android.gms#12685026#12.6.85 (040700-197041431):387)
at awos.a(:com.google.android.gms#12685026#12.6.85 (040700-197041431):12)
at awos.handleMessage(:com.google.android.gms#12685026#12.6.85 (040700-197041431):7)
at oup.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431):6)
at ovb.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431):27)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at pbc.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431))
at java.lang.Thread.run(Thread.java:761)
06-21 17:07:17.957 8543-9125/? E/WakeLock: release without a matched acquire!
06-21 17:07:18.371 14053-14083/? E/SQLiteLog: (1) no such table: mmsconfig
06-21 17:07:18.376 14053-14083/? E/Babel_SMS: canonicalizeMccMnc: invalid mccmnc nullnull
Error from the logcat for an emulator with SDK 26:
06-21 17:13:05.646 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:14.440 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.440 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.441 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.441 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.443 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.899 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:15.787 5360-5360/com.example.raluca.geoloc.feature E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.raluca.geoloc.feature, PID: 5360
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.raluca.geoloc.feature/com.example.raluca.geoloc.feature.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
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 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at com.example.raluca.geoloc.feature.MapsActivity.initMap(MapsActivity.java:110)
at com.example.raluca.geoloc.feature.MapsActivity.getLocationPermission(MapsActivity.java:123)
at com.example.raluca.geoloc.feature.MapsActivity.onCreate(MapsActivity.java:67)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
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)
06-21 17:13:16.975 1510-1510/? E/AudioFlinger: not enough memory for AudioTrack size=131296
06-21 17:13:16.976 1510-1510/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
06-21 17:13:16.978 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -12
06-21 17:13:16.990 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
06-21 17:13:16.990 2349-5365/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
06-21 17:13:16.998 2349-5365/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
06-21 17:13:17.682 2308-2853/com.google.android.gms.persistent E/ctxmgr: [ProducerStatusImpl]updateStateForNewContextData: inactive, contextName=7
06-21 17:13:17.794 2308-2308/com.google.android.gms.persistent E/BeaconBle: Missing BluetoothAdapter
06-21 17:13:17.895 2308-2308/com.google.android.gms.persistent E/BeaconBle: Scan couldn't start for Places
06-21 17:13:22.074 1510-1650/? E/AudioFlinger: not enough memory for AudioTrack size=131296
06-21 17:13:22.074 1510-1650/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
06-21 17:13:22.074 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -12
06-21 17:13:22.084 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
06-21 17:13:22.084 2349-5365/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
06-21 17:13:22.086 2349-5365/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
06-21 17:13:27.115 1510-1648/? E/AudioFlinger: not enough memory for AudioTrack size=131296
06-21 17:13:27.116 1510-1648/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
06-21 17:13:27.116 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -12
06-21 17:13:27.123 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
06-21 17:13:27.124 2349-5365/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
06-21 17:13:27.714 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:27.737 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:31.070 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:31.084 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:32.154 1510-1650/? E/AudioFlinger: not enough memory for AudioTrack size=131296
06-21 17:13:32.155 1510-1650/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
06-21 17:13:32.155 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -12
06-21 17:13:32.157 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
06-21 17:13:32.157 2349-5365/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
Msps Activity Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity"
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
/>
</RelativeLayout>
Gradle
android {
compileSdkVersion 26
defaultConfig {
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
debuggable true
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation project(':base')
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.github.orhanobut:logger:1.12'
compile 'com.google.android.gms:play-services-maps:11.6.0'
implementation "com.google.android.gms:play-services-location:11.6.0"
}
You have to initialize your map in onCreate() as done here and this will do your job.
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback
{
private GoogleMap mMap;
#Override
public void onMapReady(GoogleMap googleMap)
{
Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d("Mapready", "onMapReady: map is ready");
mMap = googleMap;
if (mLocationPermissionsGranted)
{
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
private static final String TAG = "MapsActivity";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 15f;
//vars
private Boolean mLocationPermissionsGranted = false;
private FusedLocationProviderClient mFusedLocationProviderClient;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
initMap();
getLocationPermission();
}
private void getDeviceLocation(){
Log.d(TAG, "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try{
if(mLocationPermissionsGranted){
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()){
Log.d(TAG, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM);
}else{
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(MapsActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException e){
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
}
}
private void moveCamera(LatLng latLng, float zoom){
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void initMap(){
Log.d(TAG, "initMap: initializing map");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
}
private void getLocationPermission(){
Log.d(TAG, "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = true;
initMap();
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: called.");
mLocationPermissionsGranted = false;
switch(requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if(grantResults.length > 0){
for(int i = 0; i < grantResults.length; i++){
if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = false;
Log.d(TAG, "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d(TAG, "onRequestPermissionsResult: permission granted");
mLocationPermissionsGranted = true;
//initialize our map
initMap();
}
}
}
}
}
Also, do the following changes in the manifest file:-
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY"/>
Create a New Project and check on the "Use androidx.* artifacts" and it will work fine.
Should use API 23 or newer.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I tried to build an app that lets you send data over bluetooth to an
arduino. But I got stuck while creating the socket. The app keeps
crashing on startup, but I don't know why.
package de.lutherschule.bled.bluetoothled;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.icu.util.Output;
import android.support.annotation.WorkerThread;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
BluetoothAdapter bAdapter;
BluetoothDevice device;
Boolean found;
BluetoothSocket btSocket;
OutputStream outputStream;
InputStream inputStream;
public static final String DEVICE_ADRESS = "";
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final String TAG = "MainActvity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bAdapter = BluetoothAdapter.getDefaultAdapter();
found = false;
btSocket = null;
Log.v(TAG, "Funst");
if (bAdapter == null) {
Toast.makeText(getApplicationContext(),"Funst net",Toast.LENGTH_SHORT).show();
}
if(!bAdapter.isEnabled()) {
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
}
Set<BluetoothDevice> bondedDevices = bAdapter.getBondedDevices();
if(bondedDevices.isEmpty()) {
Toast.makeText(getApplicationContext(),"Muss gepaired werden",Toast.LENGTH_SHORT).show();
} else {
for (BluetoothDevice iter : bondedDevices) {
if(iter.getAddress().equals(DEVICE_ADRESS)) { // oder iter.getName() wenn Name bekannt muessen dann aendern
device=iter;
found=true;
break;
}
}
}
When I delete the section under this quote. The app starts just fine.
try{
btSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
}catch(IOException ioe){
Log.v(TAG, "socket nit erstellt");
}
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
device = bAdapter.getRemoteDevice(DEVICE_ADRESS);
try {
btSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket nit erstellt", Toast.LENGTH_LONG).show();
}
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
}
}
}
#Override
public void onPause() {
super.onPause();
try {
btSocket.close();
} catch (IOException e2) {
}
}
}
I'd appreciate any help. By the way sorry for my formatting... I'm a newbie in creating posts.
Android Monitor:
08-27 17:56:51.857 3071-3071/? E/libprocessgroup: failed to make and chown /acct/uid_10058: Read-only file system
08-27 17:56:51.857 3071-3071/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
08-27 17:56:51.857 3071-3071/? I/art: Not late-enabling -Xcheck:jni (already on)
08-27 17:56:52.086 3071-3071/de.lutherschule.bled.bluetoothled I/InstantRun: Starting Instant Run Server for de.lutherschule.bled.bluetoothled
08-27 17:56:52.288 3071-3071/de.lutherschule.bled.bluetoothled W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
[ 08-27 17:56:52.386 1162: 2146 D/ ]
HostConnection::get() New Host Connection established 0xb68aea60, tid 2146
08-27 17:56:52.429 3071-3079/de.lutherschule.bled.bluetoothled W/art: Suspending all threads took: 17.085ms
08-27 17:56:52.442 3071-3071/de.lutherschule.bled.bluetoothled E/BluetoothAdapter: Bluetooth binder is null
08-27 17:56:52.442 3071-3071/de.lutherschule.bled.bluetoothled V/MainActvity: Funst
08-27 17:56:52.452 3071-3071/de.lutherschule.bled.bluetoothled D/AndroidRuntime: Shutting down VM
--------- beginning of crash
08-27 17:56:52.453 3071-3071/de.lutherschule.bled.bluetoothled E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.lutherschule.bled.bluetoothled, PID: 3071
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.lutherschule.bled.bluetoothled/de.lutherschule.bled.bluetoothled.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
at de.lutherschule.bled.bluetoothled.MainActivity.onCreate(MainActivity.java:59)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Try to use
BluetoothDevice device = mAdapter.getRemoteDevice(address);
btsocket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
Here is my code.
try {
socket = connect_device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
h.sendEmptyMessage(0);
} catch (IOException e) {
// TODO Auto-generated catch block
h.sendEmptyMessage(1);
e.printStackTrace();
try {
socket.close();
} catch (IOException e2) {
}
}
I have a problem, that I can't fix. I have spent almost all day today trying to get this to work, but I can't and I am out of any ideas, so decided to ask for your help.
Also, I have looked around google and stackoverflow for answers, none of which helped me.
The problem regards photo capturing with android. I have an activity, where I can "create" a new item that is later on stored in a database. I can pass it a name and location, as well as take a photo that binds to it. When I press "add" it is saved to the database. Everything works, except the Camera intent. I want to be able to take a photo in that activity, that binds to the "object" I'm creating, so later on I can view that photo when I click on a particular "object" on a list. I do have permissions (write and read) in my AndroidManifest, but still they dont help.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="18"
/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18"
/>
<uses-feature android:name="android.hardware.camera"
android:required="false"
/>
My android version is 6.0.
This code is the most recent compilation of solutions that I have gathered to try to make it work. I would very much appreciate your help with my issue.
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class CreateItemFragment extends Fragment {
private static final int REQUEST_PHOTO = 2;
private static final String TAG = "button clicked";
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private TextView mNameText;
private TextView mLocationText;
private Button mAddButton;
private ImageButton mPhotoButton;
private ImageView mPhotoView;
private String mCurrentPhotoPath;
private File mPhotoFile;
private Item mItem;
private List<Item> mItems;
private static ItemStash sItemStash;
public static CreateItemFragment newInstance(){
return new CreateItemFragment();
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_create_item, container, false);
mNameText = (TextView)view.findViewById(R.id.item_name);
mLocationText = (TextView)view.findViewById(R.id.item_location);
sItemStash = sItemStash.get(getContext());
mAddButton = (Button)view.findViewById(R.id.add_button);
mAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mNameText.getText().length() > 0 && mLocationText.getText().length() > 0){
sItemStash.addItem(
new Item(mNameText.getText().toString(),
mLocationText.getText().toString()));
Toast.makeText(getActivity(), mNameText.getText().toString() + " added to the list!", Toast.LENGTH_SHORT).show();
}
mNameText.setText("");
mLocationText.setText("");
}
});
mPhotoButton = (ImageButton)view.findViewById(R.id.photo_button);
//final Intent captureImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
/*
PackageManager packageManager = getActivity().getPackageManager();
boolean canTakePhoto = mPhotoFile != null && captureImage.resolveActivity(packageManager) != null;
mPhotoButton.setEnabled(canTakePhoto);
if(canTakePhoto) {
Uri uri = Uri.fromFile(mPhotoFile);
captureImage.putExtra(MediaStore.EXTRA_OUTPUT, uri);
}
*/
mPhotoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
verifyStoragePermissions(getActivity());
capturePhotoIntent();
//startActivityForResult(captureImage, REQUEST_PHOTO);
//mPhotoFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString());
//mPhotoFile = new File(mItem.setPhotoFilename(mNameText.getText().toString()));
}
});
mPhotoView = (ImageView)view.findViewById(R.id.item_photo);
//updatePhotoView();
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_PHOTO && resultCode == Activity.RESULT_OK){
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap)extras.get("data");
//mPhotoFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString());
mPhotoView.setImageBitmap(imageBitmap);
}
}
/*
private void updatePhotoView(){
if(mPhotoFile == null || !mPhotoFile.exists()){
Log.d(TAG, "is clicked");
mPhotoView.setImageDrawable(null);
}else{
Bitmap bitmap = PhotoUtils.getScaledBitmap(mPhotoFile.getPath(), getActivity());
mPhotoView.setImageBitmap(bitmap);
}
}
*/
private void capturePhotoIntent(){
Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
PackageManager packageManager = getActivity().getPackageManager();
if(photoIntent.resolveActivity(packageManager) != null){
File photoFile = null;
try{
photoFile = createImageFile();
}catch (IOException ioe){
ioe.printStackTrace();
}
if(photoFile != null) {
photoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(photoIntent, REQUEST_PHOTO);
}
}
}
public File createImageFile() throws IOException {
verifyStoragePermissions(getActivity());
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,
".jpg",
storageDir
);
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
public static void verifyStoragePermissions(Activity activity) {
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
}
*EDIT
Forgot to paste in my stack trace. I do get this:
04-21 22:34:56.688 3574-3604/com.bignerdranch.android.tingleapp
W/OpenGLRenderer: Fail to change FontRenderer cache size, it already initialized
04-21 22:34:56.704 3574-3574/com.bignerdranch.android.tingleapp D/android.widget.GridLayout: horizontal constraints: x1-x0>=163, x2-x1>=1080, x2-x0<=1080 are inconsistent; permanently removing: x2-x0<=1080.
04-21 22:34:56.708 3574-3574/com.bignerdranch.android.tingleapp D/android.widget.GridLayout: vertical constraints: y2-y0>=745, y2-y1<=136, y1-y0<=136 are inconsistent; permanently removing: y2-y1<=136.
04-21 22:34:56.819 3574-3604/com.bignerdranch.android.tingleapp E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb8767340
04-21 22:34:57.533 3574-3574/com.bignerdranch.android.tingleapp W/System.err: java.io.IOException: open failed: EACCES (Permission denied)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at java.io.File.createNewFile(File.java:939)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at java.io.File.createTempFile(File.java:1004)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.bignerdranch.android.tingleapp.CreateItemFragment.createImageFile(CreateItemFragment.java:173)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.bignerdranch.android.tingleapp.CreateItemFragment.capturePhotoIntent(CreateItemFragment.java:154)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.bignerdranch.android.tingleapp.CreateItemFragment.access$300(CreateItemFragment.java:30)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.bignerdranch.android.tingleapp.CreateItemFragment$2.onClick(CreateItemFragment.java:108)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.view.View.performClick(View.java:5226)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.view.View$PerformClick.run(View.java:21266)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.os.Looper.loop(Looper.java:168)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5845)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at java.lang.reflect.Method.invoke(Native Method)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at libcore.io.Posix.open(Native Method)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at java.io.File.createNewFile(File.java:932)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: ... 14 more
the method verisfyStoragePermission() was supposed to fix that error as I found in other topics, but I still get this error