This question already has answers here:
Exception 'open failed: EACCES (Permission denied)' on Android
(34 answers)
Closed 6 years ago.
Currently I have this code where I copy paste from here into my source code. But due to some reason unknown to me, the OutputStreamWriter keep giving IOException. And I'm clueless on what cause this and how to fix it. Please help. Below is my code.
public void generateNoteOnSD(){// create a File object for the parent directory
try {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File myFile = new File(path, "mytextfile.txt");
FileOutputStream fOut = new FileOutputStream(myFile,true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("the text I want added to the file");
Log.d("Save File Test : ","Success");
myOutWriter.close();
fOut.close();
}
catch (IOException e) {
//do something if an IOException occurs.
Log.d("Save File Test : ","Failed");
}
}
I have already included
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in the manifest, and also running the code in AsyncTask - onPostExecute and on AVD with Lollipop version.
My stacktrace:
08-28 11:22:52.788 30478-30478/com.example.azrie.dummyvoice E/YOUR_APP_LOG_TAG: I got an error
java.io.FileNotFoundException: /storage/emulated/0/Download/mytextfile.txt: open failed: EACCES (Permission denied)
at libcore.io.IoBridge.open(IoBridge.java:452)
at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
at com.example.azrie.dummyvoice.ReadHTML.generateNoteOnSD(ReadHTML.java:126)
at com.example.azrie.dummyvoice.ReadHTML.onPostExecute(ReadHTML.java:78)
at com.example.azrie.dummyvoice.ReadHTML.onPostExecute(ReadHTML.java:37)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
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)
Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
at libcore.io.Posix.open(Native Method)
at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
at libcore.io.IoBridge.open(IoBridge.java:438)
at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
at com.example.azrie.dummyvoice.ReadHTML.generateNoteOnSD(ReadHTML.java:126)
at com.example.azrie.dummyvoice.ReadHTML.onPostExecute(ReadHTML.java:78)
at com.example.azrie.dummyvoice.ReadHTML.onPostExecute(ReadHTML.java:37)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
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)
private static final String FILE_NAME="score.txt";
BufferedOutputStream o;
try {
o = new BufferedOutputStream(new FileOutputStream(new File(getFilesDir(),FILE_NAME)));
String s = //here write what you want to write to the file . its got to be string to work
o.write(s.getBytes());
o.close();
}catch (FileNotFoundException e ){
}catch (IOException e){
}
for me its work for every time and its not opening new file every time.
if you want to see it in action serch FightWithMath in the play store. you will need to fully restart the app after first login and its writing in the main screen and while the game running every time you win
Related
Caused by:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.io.File.isDirectory()' on a null object reference
LocalOfficeManager officeManager = LocalOfficeManager.install();
try {
// Start an office process and connect to the started instance (on port 2002).
officeManager.start();
File inputFile = new File("storage/emulated/0/COVID-19/111.pdf");
wordtext = String.valueOf(JodConverter.convert(inputFile));
} catch (OfficeException e) {
e.printStackTrace();
} finally {
// Stop the office process
OfficeUtils.stopQuietly(officeManager);
}
E/AndroidRuntime: FATAL EXCEPTION: main Process: handbook_multi_maker.TJ, PID: 17976 java.lang.RuntimeException: Unable to start activity ComponentInfo{handbook_multi_maker.TJ/TJ.SecondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.io.File.isDirectory()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3107) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3250) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1947) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7032) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.io.File.isDirectory()' on a null object reference at org.jodconverter.local.office.LocalOfficeUtils.validateOfficeHome(LocalOfficeUtils.java:339) at org.jodconverter.local.office.LocalOfficeManager$Builder.build(LocalOfficeManager.java:169) at org.jodconverter.local.office.LocalOfficeManager.install(LocalOfficeManager.java:78) at TJ.SecondActivity.initWebView(SecondActivity.java:132) at TJ.SecondActivity.onCreate(SecondActivity.java:104) at android.app.Activity.performCreate(Activity.java:7327) at android.app.Activity.performCreate(Activity.java:7318) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3087) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3250) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1947) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7032) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
You got this error because the default behavior of JODConverter is to auto-detect the office (LibreOffice or Apache OpenOffice) installation you will be working with. In your particular case, the office home directory was not found (thus null).
So, if your office installation is within a custom directory, you can use the officeHome property.
Here's your updated code:
OfficeManager officeManager =
LocalOfficeManager.builder()
.officeHome("Path to your office home")
.install()
.build();
try {
// Start an office process and connect to the started instance (on port 2002).
officeManager.start();
File inputFile = new File("storage/emulated/0/COVID-19/111.pdf");
wordtext = String.valueOf(JodConverter.convert(inputFile));
} catch (OfficeException e) {
e.printStackTrace();
} finally {
// Stop the office process
OfficeUtils.stopQuietly(officeManager);
}
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 3 years ago.
I have to send some parameters from my Android application to a Php script, for a database insert.
I tried this script on Eclipse and it works fine.
But when I try to run it on Android it crashes.
public static void Insert(){
try {
// open a connection to the site
URL url = new URL("http://192.168.1.105/JavaInsert.php");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
// send your parameters to your site
ps.print("&email=random#gmail.com");
//ps.print("&Company=Company");
//ps.print("&Shares=Shares");
//ps.print("&Date=Date");
con.getInputStream();
ps.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
System.out.print("Db error 1");
} catch (IOException e2) {
e2.printStackTrace();
System.out.print("Db error 1");
}
}
There are these errors in the LogCat section
07-28 14:28:07.259 20554-20554/com.example.ivan.rocketsocialstudioapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ivan.rocketsocialstudioapp, PID: 20554
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)
at android.view.View.performClick(View.java:6663)
at android.view.View.performClickInternal(View.java:6635)
at android.view.View.access$3100(View.java:794)
at android.view.View$PerformClick.run(View.java:26199)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7593)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
at android.view.View.performClick(View.java:6663)
at android.view.View.performClickInternal(View.java:6635)
at android.view.View.access$3100(View.java:794)
at android.view.View$PerformClick.run(View.java:26199)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7593)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1523)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:231)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:213)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
at java.net.Socket.connect(Socket.java:621)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:145)
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:141)
at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
at com.example.ivan.rocketsocialstudioapp.MainActivity.Insert(MainActivity.java:72)
at com.example.ivan.rocketsocialstudioapp.MainActivity.send(MainActivity.java:45)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
at android.view.View.performClick(View.java:6663)
at android.view.View.performClickInternal(View.java:6635)
at android.view.View.access$3100(View.java:794)
at android.view.View$PerformClick.run(View.java:26199)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7593)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
07-28 14:28:07.284 20554-20554/com.example.ivan.rocketsocialstudioapp I/Process: Sending signal. PID: 20554 SIG: 9
The Php script works with Eclipse.
I've also already added the android Network and Internet Permissions
its because you cant run network operation on main thread it will cause the NetworkOnMainThreadException which you have
try networking libraries or do the operation on a AsyncTask
You need to create a Runnable Thread or AsyncTask to run network operations.
Check out my example below
private void login() {
JSONObject request = new JSONObject();
try {
//Populate the request parameters
request.put(KEY_USERNAME, username);
request.put(KEY_PASSWORD, password);
//Log.v("test", request.toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsArrayRequest = new JsonObjectRequest
(Request.Method.POST, login_url, request, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
try {
//Check if user got logged in successfully
if (response.getInt(KEY_STATUS) == 0) {
session.loginUser(username, response.getString(KEY_FULL_NAME));
loadDashboard();
} else {
Toast.makeText(getApplicationContext(),
response.getString(KEY_MESSAGE), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
//Display error message whenever an error occurs
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
I am trying to connect to a MS SQL Server in Android and I am having the following error on the Logcat:
Process: za.co.plus94.rate, PID: 22863
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/ietf/jgss/GSSManager;
at net.sourceforge.jtds.jdbc.TdsCore.createGssToken(TdsCore.java:4400)
at net.sourceforge.jtds.jdbc.TdsCore.sendMSLoginPkt(TdsCore.java:1971)
at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:617)
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:371)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(DriverManager.java:179)
at java.sql.DriverManager.getConnection(DriverManager.java:144)
at za.co.plus94.rate.Helpers.ConnectionClass.connClass(ConnectionClass.java:28)
at za.co.plus94.rate.RateKeywordActivity$SendSuggestion.doInBackground(RateKeywordActivity.java:108)
at za.co.plus94.rate.RateKeywordActivity$SendSuggestion.doInBackground(RateKeywordActivity.java:95)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ClassNotFoundException: Didn't find class "org.ietf.jgss.GSSManager" on path: DexPathList[[zip file "/data/app/za.co.plus94.rate-2/base.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_dependencies_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_0_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_1_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_2_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_3_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_4_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_5_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_6_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_7_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_8_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/za.co.plus94.rate-2/lib/arm64, /vendor/lib64, /system/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at net.sourceforge.jtds.jdbc.TdsCore.createGssToken(TdsCore.java:4400)
at net.sourceforge.jtds.jdbc.TdsCore.sendMSLoginPkt(TdsCore.java:1971)
at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:617)
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:371)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(DriverManager.java:179)
at java.sql.DriverManager.getConnection(DriverManager.java:144)
at za.co.plus94.rate.Helpers.ConnectionClass.connClass(ConnectionClass.java:28)
at za.co.plus94.rate.RateKeywordActivity$SendSuggestion.doInBackground(RateKeywordActivity.java:108)
at za.co.plus94.rate.RateKeywordActivity$SendSuggestion.doInBackground(RateKeywordActivity.java:95)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Suppressed: java.lang.ClassNotFoundException: org.ietf.jgss.GSSManager
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 17 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
I think the issue is coming from: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/ietf/jgss/GSSManager; and I don't know how to resolve it.
Here is my DB Connection method class:
public Connection connClass(String username, String password, String database, String server){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://" + server + ";databaseName=" + database + ";user" + username + ";password" + password + ";";
connection = DriverManager.getConnection(ConnectionURL);
}catch (SQLException ex){
Log.e("CONNECTION", ex.getMessage());
}catch(ClassNotFoundException ex){
Log.e("CONNECTION", ex.getMessage());
}catch (Exception ex){
Log.e("CONNECTION", ex.getMessage());
}
return connection;
}
}
I have enabled MultiDex as well.
Try using a previous version of jtds, ver. 1.2.7 to be exact. Try using that one it worked for me when i tried it
Make this change
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://" + server + "/" + database;
connection = DriverManager.getConnection(ConnectionURL, username, password);
I have checked and tried all the other threads for multiple hours today and none of the solutions work.
I have tried filtering through all avaible audio options. I have given the proper permissions to the app.
Goal: I am trying to get this audio stream so I can get the frequency of the audio.
My stuff
public int audioSource = MediaRecorder.AudioSource.MIC;
public int channelConfig = AudioFormat.CHANNEL_IN_MONO;
public int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
public AudioRecord audioRecord = null;
private Thread recordingThread = null;
public int blockSize = 256; // deal with this many samples at a time
public int sampleRate = 8000; // Sample rate in Hz
later on...
int bufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioEncoding);
AudioRecord audioeeeeRecord = new AudioRecord(audioSource, sampleRate, channelConfig, audioEncoding, bufferSize); // The RAW PCM sample recording
audioRecord = audioeeeeRecord;
if (audioRecord != null && audioRecord.getState() != AudioRecord.STATE_INITIALIZED)
try {
throw new Exception("AudioRecord init failed"); //audioRecord = findAudioRecord();
} catch (Exception e) {
e.printStackTrace();
}
final short[] buffer = new short[blockSize];
try {
audioRecord.startRecording();
} catch (Exception e) {
e.printStackTrace();
}
This throws the following error (http://pastebin.com/raw/3wmA4cku):
AudioRecord: AudioFlinger could not create record track, status: -1
E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -1.
E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
W/System.err: java.lang.Exception: AudioRecord init failed
W/System.err: at app.mobile.mobileecg.MainActivity.startReading(MainActivity.java:102)
W/System.err: at app.mobile.mobileecg.MainActivity$1.onClick(MainActivity.java:58)
W/System.err: at android.view.View.performClick(View.java:5697)
W/System.err: at android.view.View$PerformClick.run(View.java:22526)
W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
W/System.err: at android.os.Looper.loop(Looper.java:158)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7229)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
W/System.err: java.lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord.
W/System.err: at android.media.AudioRecord.startRecording(AudioRecord.java:943)
W/System.err: at app.mobile.mobileecg.MainActivity.startReading(MainActivity.java:114)
W/System.err: at app.mobile.mobileecg.MainActivity$1.onClick(MainActivity.java:58)
W/System.err: at android.view.View.performClick(View.java:5697)
W/System.err: at android.view.View$PerformClick.run(View.java:22526)
W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
W/System.err: at android.os.Looper.loop(Looper.java:158)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7229)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Step 1) Check your manifest to ensure add RECORD_AUDIO permission under application section. e.g.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.colibri.audioloopback">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
</manifest>
Step 2) If your device is M or later, you need to grant the permssion from Settings->App->Your App->Permissions.
Step 3) Refer to below code snippet if still doesn't work.
public void audioRecordLoop() throws Exception {
Log.e(TAG,"start audioRecordLoop");
int channelConfig = mChannels == 2?
AudioFormat.CHANNEL_IN_STEREO:
AudioFormat.CHANNEL_IN_MONO;
int bufferSize = AudioRecord.getMinBufferSize(
mSampleRateHz, channelConfig, mAudioEncoding);
mAudioRecord = new AudioRecord(
mAudioSource, mSampleRateHz, channelConfig, mAudioEncoding, bufferSize);// The RAW PCM sample recording
if (mAudioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
Log.e(TAG,"AudioRecord init failed");
return;
}
final short[] buffer = new short[mBlockSize];
mAudioRecord.startRecording();
int len = 0;
while (mbExit == false) {
len = mAudioRecord.read(buffer, 0, mBlockSize);
if (len < 0) {
Log.e(TAG,"read error " + len);
return;
}
}
mAudioRecord.stop();
mAudioRecord.release();
}
It should work now!
I think the problem may be that you had tied up the audio resources with a previous attempt, then got the code correct and now it doesn't work because there are no audio resources available. See this SO question. Also, you are throwing an exception when the constructor returns an uninitialized AudioRecord, but you catch your own exception and this results in a second exception (... called on uninitialized AudioRecord ...) in the log that can be ignored as it is a result of the first.
You might need to put some try/finally sections and/or an OnDestroy and or OnPause method in your activity to ensure that the audioRecord gets released when no longer used.
Once you have the cleanup code in place, you may need to kill off your app and/or reboot your phone to free the audio resources.
Of course it is possible that you left another app running that is holding the microphone but I doubt it.
This is the answer. It is stupid that this isn't something that android has.
https://stackoverflow.com/a/33769527/6530367
I know this is a very old question but in Android Marshmallow you have to go on "Settings > Apps > Your App > Permissions" and enble Microphone permission.
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 7 years ago.
Hi I have been trying for two days to get a simple ftp connection to transfer a small xml file. I have tried lots of different examples of code, but all seem to give the same errors.
Main FTP class code:
public class MyFTPClientFunctions {
public FTPClient mFTPClient = null;
public boolean ftpConnect(String host, String username, String password, int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
//Log.d(TAG, "Error: could not connect to host " + host);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private Context getApplicationContext() {
return null;
}
}
Main Activity code to send
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//set up FTP file transfer here
MyFTPClientFunctions ftpSend = new MyFTPClientFunctions();
ftpSend.ftpConnect("xxxxxx.asuscomm.com","admin","xxxxxxxxxx",21);
}
LogCat messages
06-22 12:09:21.460 17329-17329/com.example.rats.moham_2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.rats.moham_2, PID: 17329
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getByName(InetAddress.java:305)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:203)
at com.example.rats.moham_2.MyFTPClientFunctions.ftpConnect(MyFTPClientFunctions.java:25)
at com.example.rats.moham_2.MainActivity$3.onClick(MainActivity.java:155)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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)
This Exception is usualy thrown, if you are using the network on the main thread.
Please use Async Tasks.