I have my GameActivity that is a simple quiz. I set up two Runnables, mRunnableQuestion and mRunnableQuestionWithPenalty. The logic is: mRunnableQuestion shows new question and waits 30 seconds, when user doesn't answer in this time, the other Runnable is called, which gives user points penalty:
private Runnable mRunnableQuestion = new Runnable() {
#Override
public void run() {
new AsyncAPIGetQuestion().execute(mCategoryId);
mHandler.postDelayed(mRunnableQuestionWithPenalty, 30000);
}
};
Of course, when user answers in time, I give user points and restart the Runnable:
mHandler.removeCallbacksAndMessages(null);
mHandler.post(mRunnableQuestion);
It works very well. However, I wanted to color the Cards based on correct/wrong answer and wait 5 seconds. So i changed code above to:
mHandler.removeCallbacksAndMessages(null);
colorAnswers();
mHandler.postDelayed(mRunnableQuestion, 5000);
This is where the problem begins. When I run my app, after 2, 3 or 4 questions I get a EOF/BufferedInputStream error:
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: java.io.EOFException
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:95)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.
android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:175)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:101)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:616)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:379)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:190)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at com.my.pkg.JSONParser.getJSONFromUrl(JSONParser.java:45)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at com.my.pkg.GameActivity$AsyncAPIGetQuestion.doInBackground(GameActivity.java:317)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at com.my.pkg.GameActivity$AsyncAPIGetQuestion.doInBackground(GameActivity.java:299)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at java.lang.Thread.run(Thread.java:818)
03-04 13:38:24.108 16506-16532/com.my.pkg E/JSONParser.java: Error converting result java.io.IOException: BufferedInputStream is closed
It ONLY happens, when I add the extra postDelayed() there. No problems before.
My doInBackground part of AsyncTask that is executed by Runnable and that returns an error as stated above
#Override
protected JSONArray doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(apiURL);
return json;
}
And the JSONParser.getJSONFromURL:
public JSONArray getJSONFromUrl(String urlSource) {
try {
URL url = new URL(urlSource);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
inputStream = new BufferedInputStream(urlConnection.getInputStream());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
if(!reader.ready()) {
break;
}
}
inputStream.close();
json = sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
}
try {
jArr = new JSONArray(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
return jArr;
}
I would really appreciate any help. All the best!
It looks like I solved this issue.
The problem was in my jParser.getJSONFromUrl() method, specifically these lines:
URL url = new URL(urlSource);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
It seems that you only set setDoOutput parameter as true, when you are using POST/PUT requests. If you want only perform a GET request, such as in my case, you should set it as false:
urlConnection.setDoOutput(false);
Otherwise, you can end up getting errors as described above.
Best regards to the Community!
Related
I created an Android test program with service and activity.
In activity I start sticky service. Service make http requests every 10 seconds.
If I not exit from activity, all works fine. If I exit, service works sometime, then killed by system and restarted. After restart sometimes http requests works, sometimes gives an error message:
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: java.net.ConnectException: failed to connect to www.ya.ru/87.250.250.242 (port 80) after 15000ms: isConnected failed: ECONNREFUSED (Connection refused)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:238)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:171)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.net.Socket.connect(Socket.java:882)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:174)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.Connection.connect(Connection.java:152)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at home.xmpp.MyService.sendPostRequest(MyService.java:160)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at home.xmpp.MyService$MyTask.doInBackground(MyService.java:128)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at home.xmpp.MyService$MyTask.doInBackground(MyService.java:109)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.lang.Thread.run(Thread.java:818)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:223)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: ... 21 more
After the appearance of this error, the following requests will also fail.
I tried to start service in another process, tried to start each http request in new IntentService, tried to restart service after this error, but no results.
If an error has occurred, then other subsequent requests will also give an error. Only application restart helps.
Has anyone encountered such problem? How to make a stable connection? I read a lot of topics, but did not find the right answer.
MyService.java
package home.xmpp;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentCallbacks2;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class MyService extends Service implements ComponentCallbacks2 {
private Boolean disconnectAppeared = false;
static MyService instance;
private Handler mHandler = new Handler();
MyTask mt;
Boolean mtruned = false;
public static MyService getInstance(){
return instance;
}
#Override
public IBinder onBind(final Intent intent) {
//throw new UnsupportedOperationException("Not yet implemented");
return new LocalBinder<MyService>(this);
}
#Override
public void onCreate() {
super.onCreate();
instance = this;
mHandler.postDelayed(timeUpdaterRunnable, 100);
Log.e("MyService"," created");
}
#Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
return Service.START_STICKY;
}
#Override
public boolean onUnbind(final Intent intent) {
return super.onUnbind(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("MyService"," destroyed");
mHandler.removeCallbacks(timeUpdaterRunnable);
}
public void onTrimMemory(int level) {
switch (level) {
case ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL: //Release any memory that your app doesn't need to run.
//the system will begin killing background processes. !!!
Log.e("Memory level","4");
break;
default:
break;
}
}
private Runnable timeUpdaterRunnable = new Runnable() {
public void run() {
if (mtruned == false) {
Log.e("Time", " update");
mt = new MyTask();
mt.execute();
mHandler.postDelayed(this, 10000);
} else {
cancelTask();
}
}
};
private void cancelTask() {
if (mt == null) return;
Log.d("MyService", "cancel result: " + mt.cancel(false));
}
class MyTask extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
mtruned = true;
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("http","updated");
mtruned = false;
}
#Override
protected String doInBackground(String... params) {
String result = "";
HashMap<String,String> data = new HashMap<>();
data.put("data", "data");
result = sendPostRequest("http://www.ya.ru", data);
return result;
}
#Override
protected void onCancelled() {
super.onCancelled();
mtruned = false;
}
}
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
//Creating a URL
URL url;
//StringBuilder object to store the message retrieved from the server
StringBuilder sb = new StringBuilder();
try {
//Initializing Url
url = new URL(requestURL);
//Creating an httmlurl connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Configuring connection properties
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//Creating an output stream
OutputStream os = conn.getOutputStream();
//Writing parameters to the request
//We are using a method getPostDataString which is defined below
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
//Reading server response
while ((response = br.readLine()) != null){
sb.append(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
Update 05.10.17 I still not find a solution. I tested this programm on Android 4.1.2. It works fine. On Android 5.1.1 it works about 3 minutes after exiting the activity and then I receive connection refused error. When I return to activity, errors disappears. On Android 6.0.1 similar situation, but the error is slightly different java.net.SocketTimeoutException: failed to connect to /94.130.25.242 (port 80) after 10000ms. I think that the system blocks network activity in services after a while, but never in activities (?).
Update 05.10.17
I noticed that the connection disappears not only after the restart of the service, but also after 2-3 minutes, when exiting activity. When I return to activity, connections are restored.
I have made a video Link
Update 06.10.17
One Android specialist told me, that this problem appear only in Xiaomi phones. MIUI rejects network connections after some minutes. Only OkHttp helps. I will try it and will make feedback here.
A "connect failed: ECONNREFUSED (Connection refused)" most likely means that there is nothing listening on that port AND that IP address. Possible explanations include:
the service has crashed or hasn't been started,
your client is trying to connect using the wrong IP address or port,
or
server access is being blocked by a firewall that is "refusing" on
the server/service's behalf. This is pretty unlikely given that
normal practice (these days) is for firewalls to "blackhole" all
unwanted connection attempts.
It is impossible to use long network connections in background on Xiaomi phones. It's MIUI blocks any network connections after some time. For critical network connections, you can use Firebase Cloud Messaging, which have high priority in Android system. It can initiate necesary background job.
I'm trying to test android studio connection to mysql based on this tutorial using my android device for debugging purposes instead of android emulator. But the problem is, it results to:
java.net.ConnectException: failed to connect to /192.168.15.186 (port 80): connect failed: ETIMEDOUT (Connection timed out)
Take note that this is running on real device. localhost or 127.0.0.1:80 would return a result of ECONNREFUSED because obviously, this are computer addresses that the database aren't in the device but in the computer itself so it would be a completely waste of time if I test these 2 out or any alternative IP's.
I've tested out 10.0.2.2:80/login.php on emulator and it returns a true result hinting that the login and connection is success.
So I'm guessing that maybe the connection is block through the windows firewall, but I dont know how to modify it.
LOGCAT
03-06 13:59:29.935 20951-20951/com.example.smdojt.mysqldemo W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: java.net.ConnectException: failed to connect to /192.168.15.186 (port 80): connect failed: ETIMEDOUT (Connection timed out)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:124)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:513)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.net.Socket.connect(Socket.java:894)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:174)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.Connection.connect(Connection.java:152)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.example.smdojt.mysqldemo.BackgroundWorker.doInBackground(BackgroundWorker.java:48)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.example.smdojt.mysqldemo.BackgroundWorker.doInBackground(BackgroundWorker.java:23)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.lang.Thread.run(Thread.java:818)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: Caused by: android.system.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at libcore.io.Posix.connect(Native Method)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: ... 18 more
03-06 14:01:30.748 20951-20951/com.example.smdojt.mysqldemo D/wangcy9: setStatusIcon occur wrong theme!
03-06 14:01:30.782 20951-20951/com.example.smdojt.mysqldemo D/ViewRootImpl: loadSystemProperties PersistDebugEvent: false RoDebugEvent: false
03-06 14:02:30.313 20951-20951/com.example.smdojt.mysqldemo W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
MAINACTIVITY.java
public class MainActivity extends AppCompatActivity {
EditText UsernameEt, PasswordEt;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UsernameEt = (EditText) findViewById(R.id.etUserName);
PasswordEt = (EditText) findViewById(R.id.etPassword);
}
public void OnLogin(View view)
{
String username = UsernameEt.getText().toString();
String password = PasswordEt.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, username, password);
}
}
BACKGROUNDWORKER.java
public class BackgroundWorker extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx)
{
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://192.168.15.186:80/login.php"; //declare want you want to connect with
if (type.equals("login"))
{
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); //declare http connection class
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name","UTF-8") + "=" +URLEncoder.encode(user_name, "UTF-8")+"&"
+URLEncoder.encode("password","UTF-8") + "=" +URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//below: read and get post respone
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result="";
String line="";
while ((line = bufferedReader.readLine())!=null)
{
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
}
//Clause for httpurlconnection
catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
I had the same Issue today, and i solved it by making my PC discoverable in private networks.
Steps to make your PC Discoverable:
Go to network settings.
>Go to Manage known networks.
>Choose your network.
>Now turn on the PC discoverable feature.
It helped for me, i hope it will help you.
I have faced such problem but overcome through allow port 1433(my port) to firewall .
I have Followed below Steps:
Configure Firewall and Security Setting -> Advanced Setting ->Inbound Rules -> New Rule-> Port -> Next ->Specific Local Port(1433)->Next-> Allow the Connection -> Next ->Next-> Add Name-> Finish
I also faced the same problem today and I solved it when I turned off the fire wall and network protection setting.
I solved my problem when I change Network profile from private to public.
I a new to Android programming.While trying to connect to PHP from my Android Client (WAMP) I get the following error
java.net.SocketTimeoutException: failed to connect to /192.168.1.8 (port 8383) after 10000ms
'I had searched for this type of error and had made all prescribed changes including Changing localhost to ipv address, changing the Timeout interval, configuring the httpd.conf file, still couldn't resolve.Pls find below the code, conf file changes and error log
Error Log:
java.net.SocketTimeoutException: failed to connect to /192.168.1.8 (port 8383) after 10000ms
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:169)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.net.Socket.connect(Socket.java:882)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:139)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.Connection.connect(Connection.java:148)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:491)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.example.vijayar.phpconnect.MainActivity$AsyncRetrieve.doInBackground(MainActivity.java:80)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.example.vijayar.phpconnect.MainActivity$AsyncRetrieve.doInBackground(MainActivity.java:33)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.lang.Thread.run(Thread.java:818)
02-20 07:42:35.007 3370-3510/com.example.vijayar.phpconnect V/RenderScript: 0xb0f4b600 Launching thread(s), CPUs 3
Java Code
public class MainActivity extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 10000;
TextView textPHP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textPHP = (TextView) findViewById(R.id.textPHP);
//Make call to AsyncRetrieve
new AsyncRetrieve().execute();
}
private class AsyncRetrieve extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
//this method will interact with UI, here display loading message
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
// This method does not interact with UI, You need to pass result to onPostExecute to display
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://192.168.1.8:8383/Checking/Checking.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
// this method will interact with UI, display result sent from doInBackground method
#Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
if(result.equals("Success! This message is from PHP")) {
textPHP.setText(result.toString());
}else{
// you to understand error returned from doInBackground method
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Manifest File
<uses-permission android:name="android.permission.INTERNET"/>
In Httpd.conf the following changes are made
#Listen 12.34.56.78:8383
Listen 0.0.0.0:8383
Listen [::0]:8383
<Directory />
AllowOverride None
Options None
Allow from All
Require all granted
</Directory>
PHP file -> Checking.Php
<?php
echo "Success! This message is from PHP";
?>
The PHP page works fine when invoked from browser.
The problem looks like your Apache configuration might be listening on the wrong ip address. Android is trying to access the ip address 192.168.1.8:8383 and your Apache server needs to be on the same network with your Android device. I would recommend that you make sure your Android device is on the same network as the Apache server and that your server is setup to listen on the correct ip address that Android is trying to connect too.
Timeout issue is resolved, this is what I did, I had added IPV4 to Listen command in httpd.conf file and disabled temporarily the antivirus gateway (that was preventing request from hitting the server) –
I'm trying to upload an image from Android to Cloud Storage. I'm following this official guide on how to upload files to Google Cloud Storage using the JSON API. Here is my code
private class uploadImage extends AsyncTask<File, Void, String> {
File file = mPhotoFile;
private String delimiter = "--";
#Override
protected void onPreExecute() {
Toast.makeText(getActivity(), mPhotoFile.getPath(), Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(File... params) {
try {
URL url = new URL("https://www.googleapis.com/upload/storage/v1/b/backend-images/o?uploadType=media&name=myObject?key=my_key");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setChunkedStreamingMode(0);
urlConnection.setRequestProperty("Content-Type", "image/jpeg");
urlConnection.setRequestProperty("Content-Length", String.valueOf(mPhotoFile.getPath().getBytes().length));
urlConnection.setRequestProperty("Authorization", "my_key");
urlConnection.setDoOutput(true);
urlConnection.setDoOutput(true);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
InputStream responseStream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
out.write(("Content-Type: image/jpeg\r\n").getBytes());
out.write(("Content-Length: " + String.valueOf(mPhotoFile.getPath().getBytes().length)).getBytes());
out.write("\r\n".getBytes());
out.write(mPhotoFile.getPath().getBytes());
out.write("\r\n".getBytes());
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
String response = stringBuilder.toString();
Log.i("CloudStorage", response);
} catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
return "Everything was a success";
}
}
I'm using the Public API access method and appending the Api key to the link like the guide says I could to authorize requests
Here is the error i'm getting
05-22 10:24:01.798 3747-4045/com.example.kid.uimockup W/System.err: java.io.FileNotFoundException:https://www.googleapis.com/upload/storage/v1/b/backend-images/o?uploadType=media&name=myObject?key=my_key
05-22 10:24:01.798 3747-4045/com.example.kid.uimockup W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:197)
05-22 10:24:01.798 3747-4045/com.example.kid.uimockup W/System.err: at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
05-22 10:24:01.798 3747-4045/com.example.kid.uimockup W/System.err: at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)
05-22 10:24:01.798 3747-4045/com.example.kid.uimockup W/System.err: at com.example.kid.uimockup.HomeFragment$uploadImage.doInBackground(HomeFragment.java:636)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at com.example.kid.uimockup.HomeFragment$uploadImage.doInBackground(HomeFragment.java:605)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at java.lang.Thread.run(Thread.java:818)
I don't have a clue if this is a problem on the client side or the server side
I got it work after making a few changes. I was getting a 401 Unauthorized Error code which means I didn't have authorization to access the bucket.
So instead of appending the query parameter key=api_key, i appended access_token=auth_token to authorize requests.
I then added allUsers permission to my bucket (making it public for everyone to write and read) and it worked.
I have been stuck on this problem for a day or two now, so i decided to see if anyone out there could help me.
The current goal i have, is to make a HttpPost that connects to, and executes a script that i have on my Wamp server. I have implemented a class that extends AsyncTask, and includes the 3 necessary methods, that are required in order for it to work effectively.
I will first show you the code that i have used to put the variables into a Json Object, followed by the JSONParser class, that initializes the HttpPost and then executes it.
Afterwards i will tell you all about the log errors and the narrowing down of the problem; you all problem know what the problem may be already, and if you don't want to read below, briefly, it is caused by the line of code that calls the parser class.
Note: I am using this as a starting point for this type of work, so please understand that it is simple in terms of its passed parameters.
Further Note: I am using Eclipse, and i am testing with the inbuilt Emulator.
METHOD - CreateNewUser
/**
* Background Async Task to Create new user
*/
class CreateNewUser extends AsyncTask<String, String, String>{
/**
* Before starting background thread show progress dialog
*/
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(AddUserActivity.this);
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/*
* Creating user
*/
#Override
protected String doInBackground(String... args){
String username = inputUsername.getText().toString();
String password = inputPassword.getText().toString();
// Building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
// getting JSON object
// Note that create user url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_user, "POST",params);
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
Next, the JSONParser Class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get JSON from URL
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
If i remove the line : ( JSONObject json = jsonParser.makeHttpRequest(url_create_user, "POST",params); ) - of course with intending the try catch out, then the program does not crash, when i press the button that calls the CreateNewUser class.
If i do not do that, my program brings up a loading screen that swirls around until it becomes unresponsive, and asks me to close down the application.
The logs describe Async errors, and illegal state ones:
E/AndroidRuntime(1132): FATAL EXCEPTION: AsyncTask #2
E/AndroidRuntime(1132): Process: com.example.propertypanther, PID: 1132
E/AndroidRuntime(1132): java.lang.RuntimeException: An error occured while executing
doInBackground()
E/AndroidRuntime(1132): at android.os.AsyncTask$3.done(AsyncTask.java:300)
E/AndroidRuntime(1132): at
java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
E/AndroidRuntime(1132): at
java.util.concurrent.FutureTask.setException(FutureTask.java:222)
E/AndroidRuntime(1132): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
E/AndroidRuntime(1132): at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
E/AndroidRuntime(1132): at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
E/AndroidRuntime(1132): at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
E/AndroidRuntime(1132): at java.lang.Thread.run(Thread.java:841)
E/AndroidRuntime(1132): Caused by: java.lang.IllegalStateException: Target host must not
be null, or set in parameters. scheme=null, host=null,
path=localhost/android_connect/sqlconfig/create_user.php
E/AndroidRuntime(1132): at
org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.jav
a:591)
E/AndroidRuntime(1132): at
org.apache.http.impl.client.DefaultRequestDirector.execute
(DefaultRequestDirector.java:293)
E/AndroidRuntime(1132): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
E/AndroidRuntime(1132): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
E/AndroidRuntime(1132): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
E/AndroidRuntime(1132): at
com.example.propertypanther.JSONParser.makeHttpRequest(JSONParser.java:51)
E/AndroidRuntime(1132): at
com.example.propertypanther.AddUserActivity$CreateNewUser.doInBackground
(AddUserActivity.java:116)
E/AndroidRuntime(1132): at
com.example.propertypanther.AddUserActivity$CreateNewUser.doInBackground
(AddUserActivity.java:1)
E/AndroidRuntime(1132): at android.os.AsyncTask$2.call(AsyncTask.java:288)
E/AndroidRuntime(1132): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
E/AndroidRuntime(1132): ... 4 more
I/Choreographer(1132): Skipped 82 frames! The application may be doing too much work on
its main thread.
I/Choreographer(1132): Skipped 58 frames! The application may be doing too much work on
its main thread.
E/WindowManager(1132): android.view.WindowLeaked: Activity
com.example.propertypanther.AddUserActivity has leaked window
com.android.internal.policy.impl.PhoneWindow$DecorView{b1e3d240 V.E..... R.....ID 0,0-
729,192} that was originally added here
E/WindowManager(1132): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)
E/WindowManager(1132): at
android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
E/WindowManager(1132): at
android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
E/WindowManager(1132): at android.app.Dialog.show(Dialog.java:286)
E/WindowManager(1132): at
com.example.propertypanther.AddUserActivity$CreateNewUser.onPreExecute
(AddUserActivity.java:97)
E/WindowManager(1132): at
android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
E/WindowManager(1132): at android.os.AsyncTask.execute(AsyncTask.java:535)
E/WindowManager(1132): at
com.example.propertypanther.AddUserActivity$2.run(AddUserActivity.java:78)
E/WindowManager(1132): at android.os.Handler.handleCallback(Handler.java:733)
E/WindowManager(1132): at android.os.Handler.dispatchMessage(Handler.java:95)
E/WindowManager(1132): at android.os.Looper.loop(Looper.java:136)
E/WindowManager(1132): at android.app.ActivityThread.main(ActivityThread.java:5017)
E/WindowManager(1132): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager(1132): at java.lang.reflect.Method.invoke(Method.java:515)
E/WindowManager(1132): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/WindowManager(1132): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/WindowManager(1132): at dalvik.system.NativeStart.main(Native Method)
The script files themselves work as far as i am aware - besides, the program never executes the script from what i can tell.
If anyone could help me out, i would really appreciate it! I understand you are all busy people, so thank you so much for taking some time out of your day if you do post ideas :)
The clue is in the exception thrown:
Caused by: java.lang.IllegalStateException: Target host must not be
null, or set in parameters. scheme=null, host=null,
path=localhost/android_connect/sqlconfig/create_user.php
I'm going to guess that there is an encoding problem, have you correctly included the "http://" at the beginning of your URL and have you printed the url you are requesting to LogCat to make sure it looks correct?