Can`t create and copy the file - java

My program should work as follows:
1.Copy the new database in the program folder
2.Import the records from the old database to the new one.
But I for some reason get an exception. Why?
protected Object doInBackground(Object[] objects) {
String LOCAL_DATABASE_PATH = getApplicationInfo().dataDir + File.separator +
"databases" + File.separator;
File fileDir = new File(LOCAL_DATABASE_PATH);
if (!fileDir.exists())
fileDir.mkdirs();
File tempFile = new File(LOCAL_DATABASE_PATH + DATABASE_NAME);
try {
tempFile.createNewFile(); // here I catch exception
InputStream is = SplashActivity.this.getAssets().open(
DATABASE_NAME);
FileOutputStream os = new FileOutputStream(new File(
LOCAL_DATABASE_PATH, DATABASE_NAME));
int bufferLength = 0;
byte[] buffer = new byte[2048];
while ((bufferLength = is.read(buffer)) > 0) {
os.write(buffer, 0, bufferLength);
}
Preferences.getInstance(SplashActivity.this).
set(Preferences.IS_DATABASE_COPYING_ON_DEVICE, true);
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
I am getting the following error
java.io.IOException: open failed: EACCES (Permission denied)
08-28 09:32:27.977 32558-32558/com.DriverNotes.AndroidMobileClientTest D/libEGL﹕ loaded /system/lib/egl/libGLES_hawaii.so
08-28 09:32:27.977 32558-32587/com.DriverNotes.AndroidMobileClientTest W/System.err﹕ at java.io.File.createNewFile(File.java:948)
08-28 09:32:27.977 32558-32587/com.DriverNotes.AndroidMobileClientTest W/System.err﹕ at com.DriverNotes.AndroidMobileClientTest.SplashActivity$DataBaseLoadTask.doInBackground(SplashActivity.java:73)
08-28 09:32:27.977 32558-32587/com.DriverNotes.AndroidMobileClientTest W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-28 09:32:27.977 32558-32587/com.DriverNotes.AndroidMobileClientTest W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
08-28 09:32:27.977 32558-32587/com.DriverNotes.AndroidMobileClientTest W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-28 09:32:27.977 32558-32587/com.DriverNotes.AndroidMobileClientTest W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-28 09:32:27.977 32558-32587/com.DriverNotes.AndroidMobileClientTest W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-28 09:32:27.977 32558-32587/com.DriverNotes.AndroidMobileClientTest W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
08-28 09:32:27.987 32558-32587/com.DriverNotes.AndroidMobileClientTest W/System.err﹕ Caused by: libcore.io.ErrnoException: open failed: EACCES (Permission denied)
08-28 09:32:27.987 32558-32587/com.DriverNotes.AndroidMobileClientTest W/System.err﹕ at libcore.io.Posix.open(Native Method)
08-28 09:32:27.987 32558-32587/com.DriverNotes.AndroidMobileClientTest W/System.err﹕ at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
08-28 09:32:27.987 32558-32587/com.DriverNotes.AndroidMobileClientTest W/System.err﹕ at java.io.File.createNewFile(File.java:941)
08-28 09:32:27.987 32558-32587/com.DriverNotes.AndroidMobileClientTest W/System.err﹕ ... 7 more

When creating the tempFile try using the fileDir you already created to get sure it exists.
File tempFile = new File(fileDir, DATABASE_NAME);
Before you create a new file you should check if it already exists by calling its exits() method. And then instead of opening it again you should actually keep on using it. Or at least close it before opening again.
if(!tempFile.exists())
tempFile.createNewFile();
InputStream is = SplashActivity.this.getAssets().open(
DATABASE_NAME);
FileOutputStream os = new FileOutputStream(tempFile);
Create you FileOutPutStream using the tempFile or close tempFile to get sure your file is not locked.

Related

java.io.FileNotFoundException: open failed: EACCES (Permission denied) while trying to record using JobIntentService

I'm trying to set up an android call recorder using a Broadcast Receiver and a JobIntentService. However, whenever I launch the JobIntentService, the Mediarecorder.prepare() method throws an error as follows:
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Music/filename.3gp: open failed: EACCES (Permission denied)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:496)
W/System.err: at java.io.RandomAccessFile.<init>(RandomAccessFile.java:289)
W/System.err: at java.io.RandomAccessFile.<init>(RandomAccessFile.java:152)
W/System.err: at android.media.MediaRecorder.prepare(MediaRecorder.java:1046)
W/System.err: at com.example.callrecorder.Job.recordCall(Job.java:77)
W/System.err: at com.example.callrecorder.Job.onHandleWork(Job.java:38)
W/System.err: at androidx.core.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:392)
W/System.err: at androidx.core.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:383)
W/System.err: at android.os.AsyncTask$3.call(AsyncTask.java:378)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err: at java.lang.Thread.run(Thread.java:919)
W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
W/System.err: at libcore.io.Linux.open(Native Method)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:252)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7255)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:482)
W/System.err: ... 12 more
I/Try: java.io.FileNotFoundException: /storage/emulated/0/Music/filename.3gp: open failed: EACCES (Permission denied)
E/MediaRecorder: start called in an invalid state: 4
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.callrecorder, PID: 10311
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$4.done(AsyncTask.java:399)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Caused by: java.lang.IllegalStateException
at android.media.MediaRecorder.start(Native Method)
at com.example.callrecorder.Job.recordCall(Job.java:82)
at com.example.callrecorder.Job.onHandleWork(Job.java:38)
at androidx.core.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:392)
at androidx.core.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:383)
at android.os.AsyncTask$3.call(AsyncTask.java:378)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:919)
The code for my JobIntentService is as follows:
public class Job extends JobIntentService {
static final int JOB_ID = 1000;
String state;
MediaRecorder mediaRecorder;
static void enqueueWork(Context context, Intent intent) {
enqueueWork(context, Job.class, JOB_ID, intent);
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
Log.i("Job", "Triggered");
state = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
switch (state) {
case "OFFHOOK": {
recordCall();
}
break;
case "IDLE": {
stopRecording();
}
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void stopRecording() {
Log.i("Stato", "Stopped");
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
}
private void recordCall() {
String recordPath = null;
String path = Environment.getExternalStoragePublicDirectory(DIRECTORY_MUSIC).getAbsolutePath();
File dir = new File(path);
if(!dir.exists()) {
dir.mkdirs();
}
String myFile = "filename.3gp";
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setOutputFile(dir + "/" + myFile);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mediaRecorder.prepare();
} catch (Exception e) {
e.printStackTrace();
Log.i("Try", String.valueOf(e));
}
mediaRecorder.start();
Log.i("Stato", "Started");
}
}
The intent for this service is passed from a Broadcast Receiver and it all runs fine is I try to check by removing the media recorder part. For some reason, it throws errors whenever I try to start the media recorder saying Permission Denied.
I have given WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE, RECORD_AUDIO, READ_PHONE_STATE, PROCESS_OUTGOING_CALLS permissions in the Android Manifest file.
The jobservice and receiver have been registered as well.
From Android 10 onwards, you need legacy permission to access storage the old way or switch to using the new methods.
Add this under applications in Manifest for legacy storage.
android:requestLegacyExternalStorage="true"
Recording calls feature has also been stopped from android 10 so you can no longer record calls on it without accessibility options.

Error when connecting to MS SQL Server Database

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);

OutputStreamWriter IOException occurs [duplicate]

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

Telegram Java API- socket connection issue [duplicate]

This question already has answers here:
Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'
(10 answers)
Closed 8 years ago.
I'm trying to use Telegram Java API https://github.com/ardock/telegram-api
and I started with some simple RPC call:
SampleApiState apiState = new SampleApiState(connections);
TLRequestAuthCheckPhone checkRequest = new TLRequestAuthCheckPhone("+1234567890");
TelegramApi api = new TelegramApi(apiState, new ApplicationInfo(),
new ApiCallback() {
#Override
public void onUpdatesInvalidated(TelegramApi api) {
// TODO Auto-generated method stub
Log.i(TAG, "onUpdatesInvalidated");
}
#Override
public void onAuthCancelled(TelegramApi api) {
// TODO Auto-generated method stub
Log.i(TAG, "onAuthCancelled");
}
#Override
public void onUpdate(TLAbsUpdates updates) {
// TODO Auto-generated method stub
Log.i(TAG, "onUpdate");
}
});
TLCheckedPhone checkedPhone = api.doRpcCall(checkRequest);
And here is log:
11524-11580/com.example.tltest W/System.err﹕ java.net.SocketException: socket failed: EACCES (Permission denied)
11524-11580/com.example.tltest W/System.err﹕ at libcore.io.IoBridge.socket(IoBridge.java:576)
11524-11580/com.example.tltest W/System.err﹕ at java.net.PlainSocketImpl.create(PlainSocketImpl.java:201)
11524-11580/com.example.tltest W/System.err﹕ at java.net.Socket.checkOpenAndCreate(Socket.java:664)
11524-11580/com.example.tltest W/System.err﹕ at java.net.Socket.connect(Socket.java:808)
11524-11580/com.example.tltest W/System.err﹕ at org.telegram.mtproto.transport.PlainTcpConnection.<init>(PlainTcpConnection.java:32)
11524-11580/com.example.tltest W/System.err﹕ at org.telegram.mtproto.pq.Authorizer.doAuth(Authorizer.java:198)
11524-11580/com.example.tltest W/System.err﹕ at org.telegram.api.engine.TelegramApi$ConnectionThread.waitForDc(TelegramApi.java:842)
11524-11580/com.example.tltest W/System.err﹕ at org.telegram.api.engine.TelegramApi$ConnectionThread.run(TelegramApi.java:907)
11524-11588/com.example.tltest I/System.out﹕ api#1001#Uploader:UploadFileThread iteration
11524-11580/com.example.tltest W/System.err﹕ Caused by: libcore.io.ErrnoException: socket failed: EACCES (Permission denied)
11524-11580/com.example.tltest W/System.err﹕ at libcore.io.Posix.socket(Native Method)
11524-11580/com.example.tltest W/System.err﹕ at libcore.io.BlockGuardOs.socket(BlockGuardOs.java:181)
11524-11580/com.example.tltest W/System.err﹕ at libcore.io.IoBridge.socket(IoBridge.java:561)
11524-11580/com.example.tltest W/System.err﹕ ... 7 more
11524-11580/com.example.tltest I/System.out﹕ TransportRate:onConnectionFailure #1
11524-11580/com.example.tltest I/System.out﹕ TransportRate:Transport: #1 173.240.5.1:443 #1.0
11524-11580/com.example.tltest I/System.out﹕ TransportRate:tryConnection #1
After connection failure, it tries to connect again and again, but not very successfully. I couldn't find out what's the reason and how to solve this problem. Maybe someone had same problem? Will be very gratefull for some help)
From the exception you posted it seems it is an android app and this is a permission problem.
java.net.SocketException: socket failed: EACCES (Permission denied)
Try to add this to the manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

The right way to connect to MySQL every second

I want to check my MySQL database every second and get the data from it
This is what I tried I made the connection in a separate thread and make it sleep
Thread:
class Updater extends Thread {
ArrayList<chatData> list = new ArrayList<chatData>();
Boolean thereIsNewData = false;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String yourID = prefs.getString("KEY_USERNAME", "No login info available");
void getData(){
chatServiceHandler jsonParser = new chatServiceHandler();
ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("yourID", yourID));
String json = jsonParser.makeServiceCall("http://example.com/getMSG.php", contactsServiceHandler.GET, nvp);
Log.d("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
list.clear();
JSONArray contactsArray = jsonObj.getJSONArray("MSGhandling");
for (int i = 0; i < contactsArray.length(); i++) {
JSONObject catObj = (JSONObject) contactsArray.get(i);
chatData cat = new chatData(catObj.getString("sender"), catObj.getString("receiver"),catObj.getString("msg"),catObj.getString("msgID"));
list.add(cat);
thereIsNewData = true;
}
}
} catch (JSONException e) {
e.printStackTrace();
thereIsNewData = false;
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
thereIsNewData = false;
}
}
#Override
public void run() {
while (true) {
try {
DatabaseAdapter helper = new DatabaseAdapter(UpdaterService.this);
getData();
if(thereIsNewData){
for(int i =0; i < list.size(); i++){
chatData messages = list.get(i);
Log.d(TAG, "From: "+messages.getSenderID()+" TO:"+messages.getReceiverID()+" MSG: "+messages.getMSG());
helper.storeMSG(messages.getSenderID() , messages.getReceiverID() , messages.getMSG() , messages.getMsgID());
Intent newMessage = new Intent();
newMessage.setAction("NEW_MESSAGE");
sendBroadcast(newMessage);
}
list.clear();
thereIsNewData = false;
}else{
Log.d(TAG, "There is no new data");
}
sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
It does it work but stops after a few seconds for half a minute and shows an error than back to do the same thing again:
-----------------------------------EDIT--------------------------------
LOG_CAT:
`190-318/system_process E/ThrottleService﹕ problem during onPollAlarm: java.lang.IllegalStateException: problem parsing stats: java.io.FileNotFoundException: /proc/net/xt_qtaguid/iface_stat_all: open failed: ENOENT (No such file or directory) 03
04-02 10:37:44.162 389-403/com.android.systemui E/JavaBinder﹕ *** Uncaught remote exception! (Exceptions are not yet supported across processes.)
java.lang.RuntimeException: android.os.DeadObjectException
at android.os.Parcel.writeException(Parcel.java:1326)
at android.os.Binder.execTransact(Binder.java:370)
at dalvik.system.NativeStart.run(Native Method)
Caused by: android.os.DeadObjectException
at android.os.BinderProxy.transact(Native Method)
at android.content.IIntentReceiver$Stub$Proxy.performReceive(IIntentReceiver.java:121) at android.app.ActivityThread$ApplicationThread.scheduleRegisteredReceiver(ActivityThread.java:771) at android.app.ApplicationThreadNative.onTransact(ApplicationThreadNative.java:381)
at android.os.Binder.execTransact(Binder.java:367)
            at dalvik.system.NativeStart.run(Native Method)
04-02 10:41:00.282 630-644/com.khaled.zg W/System.err﹕ org.apache.http.conn.HttpHostConnectException: Connection to http://example.com refused
04-02 10:41:00.292 630-644/com.khaled.zg W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
04-02 10:41:00.292 630-644/com.khaled.zg W/System.err﹕ at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
04-02 10:41:00.292 630-644/com.khaled.zg W/System.err﹕ at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
04-02 10:41:00.306 630-644/com.khaled.zg W/System.err﹕ at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
04-02 10:41:00.306 630-644/com.khaled.zg W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
04-02 10:41:00.306 630-644/com.khaled.zg W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-02 10:41:00.306 630-644/com.khaled.zg W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
04-02 10:41:00.313 630-644/com.khaled.zg W/System.err﹕ at com.khaled.zg.contactsServiceHandler.makeServiceCall(contactsServiceHandler.java:79)
04-02 10:41:00.326 630-644/com.khaled.zg W/System.err﹕ at com.khaled.zg.UpdaterService$Updater.getContacts(UpdaterService.java:101)
04-02 10:41:00.326 630-644/com.khaled.zg W/System.err﹕ at com.khaled.zg.UpdaterService$Updater.run(UpdaterService.java:135)
04-02 10:41:00.333 630-644/com.khaled.zg W/System.err﹕ Caused by: java.net.ConnectException: failed to connect to /185.27.134.163 (port 80): connect failed: ETIMEDOUT (Connection timed out)
04-02 10:41:00.345 630-644/com.khaled.zg W/System.err﹕ at libcore.io.IoBridge.connect(IoBridge.java:114)
04-02 10:41:00.345 630-644/com.khaled.zg W/System.err﹕ at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
04-02 10:41:00.345 630-644/com.khaled.zg W/System.err﹕ at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
04-02 10:41:00.353 630-644/com.khaled.zg W/System.err﹕ at java.net.Socket.connect(Socket.java:842)
04-02 10:41:00.353 630-644/com.khaled.zg W/System.err﹕ at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
04-02 10:41:00.364 630-644/com.khaled.zg W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
04-02 10:41:00.364 630-644/com.khaled.zg W/System.err﹕ ... 9 more
04-02 10:41:00.364 630-644/com.khaled.zg W/System.err﹕ Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
04-02 10:41:00.383 630-644/com.khaled.zg W/System.err﹕ at libcore.io.Posix.connect(Native Method)
04-02 10:41:00.383 630-644/com.khaled.zg W/System.err﹕ at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
04-02 10:41:00.393 630-644/com.khaled.zg W/System.err﹕ at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
04-02 10:41:00.393 630-644/com.khaled.zg W/System.err﹕ at libcore.io.IoBridge.connect(IoBridge.java:112)`
Am I doing it wrong? is there any other way or a solution to my problem?
Or does the host is what causes the problem?

Categories