Telegram Java API- socket connection issue [duplicate] - java

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" />

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.

Unable to connect to Azure sql database using JDBC - error with SSL

I am trying to connect to my Azure sql database through a mobile app, using Android Studio.
String connectionURL = "jdbc:sqlserver://****.database.windows.net:1433;database=****;user=****#****;password=*****;encrypt=false;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30";
public void connect(){
Connection connection = null;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(connectionURL);
}
catch (Exception e) {
e.printStackTrace();
}
This is my code to connect to the database on Azure. The correct JDBC driver has been imported and I am using the correct username/password (marked in ***s).
I keep getting the same error regarding SSL which is as follows -
04-03 23:04:49.449 31439-31439/com.example.melissa.dbtest W/System.err: com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "Socket closed". ClientConnectionId:*****
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:2435)
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1816)
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2022)
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1687)
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1528)
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:866)
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:569)
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at java.sql.DriverManager.getConnection(DriverManager.java:569)
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at java.sql.DriverManager.getConnection(DriverManager.java:237)
04-03 23:04:49.453 31439-31439/com.example.melissa.dbtest W/System.err: at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1753)
I've looked through so many answers and documents but I still can't seem to fix the problem. How can I connect to the Azure database using an SSL?
Could you try using JTDS driver instead
try {
String SQL = "select * from dbo.Student";
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String url = String.format("jdbc:jtds:sqlserver://***.database.windows.net:1433/<your database name>;user=***;password=***;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString("name"));
}
close();
} catch (Exception e) {
e.printStackTrace();
}

Getting a crash on doInBackground() line on client.execute(httpGet). Why?

Crash is: java.lang.RuntimeException: An error occured while executing doInBackground()
Why I am getting a crash on the HttpResponse response = client.execute(httpGet); line here? Does it have something to do with my ThreadPolicy?
From my fragment I call this:
new ReadJSONFeedMainTask().execute(urlString);
....
private class ReadJSONFeedMainTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return Helper.readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
// do stuff
}
}
}
Then it's called here:
public static String readJSONFeed(String URL) {
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
String numberValue = URL.replaceAll(" ", "%20");
StringBuilder stringBuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(numberValue);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
} else {
Log.e("JSON", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
Stacktrace:
java.lang.RuntimeException: An error occured while executing doInBackground()
1 at android.os.AsyncTask$3.done(AsyncTask.java:299)
2 at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
3 at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
4 at java.util.concurrent.FutureTask.run(FutureTask.java:239)
5 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
6 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
7 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
8 at java.lang.Thread.run(Thread.java:856)
9Caused by: com.splunk.mint.network.util.DelegationException: java.net.ConnectException: failed to connect to 50-89-72-86.res.bhn.net/50.89.72.86 (port 80): connect failed: ETIMEDOUT (Connection timed out)
10 at com.splunk.mint.network.util.Delegator.invoke0(Delegator.java:62)
11 at com.splunk.mint.network.util.Delegator.invoke(Delegator.java:45)
12 at com.splunk.mint.network.socket.MonitoringSocketImpl.connect(MonitoringSocketImpl.java:118)
13 at java.net.Socket.connect(Socket.java:842)
14 at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
15 at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
16 at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
17 at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
18 at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
19 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
20 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
21 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
22 at com.sortitapps.movies.Helper.readJSONFeed(Helper.java:1282)
23 at com.sortitapps.movies.MainFragment$ReadJSONFeedMainTask.doInBackground(MainFragment.java:680)
24 at com.sortitapps.movies.MainFragment$ReadJSONFeedMainTask.doInBackground(MainFragment.java:678)
25 at android.os.AsyncTask$2.call(AsyncTask.java:287)
26 at java.util.concurrent.FutureTask.run(FutureTask.java:234)
27 ... 4 more
28Caused by: java.net.ConnectException: failed to connect to 50-89-72-86.res.bhn.net/50.89.72.86 (port 80): connect failed: ETIMEDOUT (Connection timed out)
29 at libcore.io.IoBridge.connect(IoBridge.java:114)
30 at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
31 at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
32 at java.lang.reflect.Method.invokeNative(Native Method)
33 at java.lang.reflect.Method.invoke(Method.java:511)
34 at com.splunk.mint.network.util.Delegator.invoke0(Delegator.java:56)
35 ... 20 more
36Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
37 at libcore.io.Posix.connect(Native Method)
38 at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
39 at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
40 at libcore.io.IoBridge.connect(IoBridge.java:112)
I had the same problem after updating from BugSense to Splunk Mint and there was nothing wrong with my code. After I commented out Splunk.init(...) method invocation everything started to work again. Problem was occuring only on HTC devices and with Splunk Mint enabled - all calls of HttpClient#execute() method were throwing DelegationException. Not sure if this is your case but maybe my answer will help someone with the same problem as mine.
It seems pretty clear, the end of the stack trace indicates Connection timed out. Your server is unreachable.
You should use Asynctask for any work with server, see http://developer.android.com/reference/android/os/AsyncTask.html

Can`t create and copy the file

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.

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