1

all of a sudden my mobile device can't connect to the local server anymore. async tasks are not executed and i just can't figure out why. slowly i'm getting really desperate because in my opinion i didn't change anything to cause this. as an example, this is a background task which is not working

public class Login extends AsyncTask<String, Void, String>{
    private String loginUrl = "http://...";

    private int loginSuccess = 0;

    public String getToken(String fromJson) throws JSONException {
        JSONObject json = new JSONObject(fromJson);


        if(json.has("api_authtoken")) {
            loginSuccess = 1;
            String appToken = json.getString("api_authtoken");
            return appToken;
        }

        else {
            return json.toString();
        }
    }

    public String doInBackground(String... arg0) {

            // so that they can be closed in the finally block.
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
            String authToken;

            try {
                // get logged in to get the api_authtoken
                String email = (String) arg0[0];
                String password = (String) arg0[1];

                URL url = new URL(loginUrl);

                // Create the request and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type", "application/json");
                urlConnection.setRequestProperty("Accept", "application/json");

                //put values of edittexts into json-Object
                JSONObject data = new JSONObject();
                try {
                    data.put("email", email);
                    data.put("password", password);
                } catch(JSONException e) {
                    Log.e("EXCEPTION", "unexpected JSON exception", e);
                    e.printStackTrace();
                }

            urlConnection.connect();
            OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
            wr.write(data.toString());
            wr.flush();

            reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            //read server response
            while((line = reader.readLine()) != null) {
                sb.append(line);
            }

            //receive server "answer"
            try {
                return getToken(sb.toString());
            }catch(JSONException e) {
                Log.e("LOG", "unexpected JSON exception", e);
                e.printStackTrace();
            }  finally{
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e("MainActivity", "Error closing stream", e);
                    }
                }
            }

            //return sb.toString();
            return null;
        }
        catch(IOException e) {
            Log.e("LoginTask", "Error ", e);
            // If the code didn't successfully get the data, there's no point in attempting
            // to parse it.
            //forecastJsonStr = null;
            return null;
        }
    }

    public void onPostExecute(String result) {
        super.onPostExecute(result);
        //Log.v("RESULT", result);
        if(result == null) {
            CharSequence text = "no internet connection";
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(MainActivity.this, text, duration);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.show();
        }

        if(loginSuccess == 0) {
            // if the request wasn't successful
            // give user a message via toast
            CharSequence text = "wrong password or user. please try again";
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(MainActivity.this, text, duration);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.show();
        }

        else {
            // save token in shared preferences
            SharedPreferences tokenPref = getSharedPreferences(getString(R.string.preference_token), Context.MODE_PRIVATE);
            SharedPreferences.Editor editorToken = tokenPref.edit();
            editorToken.putString(getString(R.string.saved_auth_token), result);
            editorToken.commit();

            //save login status = 1 in shared preferences
            SharedPreferences loginPref = getSharedPreferences(getString(R.string.preference_logged_in), Context.MODE_PRIVATE);
            SharedPreferences.Editor editorLogin = loginPref.edit();
            editorLogin.putString(getString(R.string.saved_login), "1");
            editorLogin.commit();

            Intent mapsIntent = new Intent(getApplicationContext(), MapsActivity.class);
            startActivity(mapsIntent);

        }
    }
}
rudi
  • 75
  • 8

3 Answers3

0

HttpClient is not supported any more in sdk 23. You have to use URLConnection or downgrade to sdk 22 (compile 'com.android.support:appcompat-v7:22.2.0')

If you need sdk 23, add this to your gradle:

android {
    useLibrary 'org.apache.http.legacy'
}

HttpClient won't import in Android Studio

Community
  • 1
  • 1
Naveen Tamrakar
  • 3,349
  • 1
  • 19
  • 28
0

You should think about using a HTTP library, there is a bunch of them on internet, some are really easy to use, optimize and errorless.

For example, Volley (made by Google, I really like this one), okHttp or Picasso (for image).

You should take a look at this.

gouy_e
  • 188
  • 2
  • 7
  • yes you are right, i will have to. and thanks for the video link! will take a deeper look into caching later – rudi Feb 15 '16 at 12:52
0

If you want to send (output), for example with POST or PUT requests you need to use this :-

urlConnection.setDoOutput(true);

In your code :-

public class Login extends AsyncTask<String, Void, String>{
    private String loginUrl = "http://...";

    private int loginSuccess = 0;

    public String getToken(String fromJson) throws JSONException {
        JSONObject json = new JSONObject(fromJson);


        if(json.has("api_authtoken")) {
            loginSuccess = 1;
            String appToken = json.getString("api_authtoken");
            return appToken;
        }

        else {
            return json.toString();
        }
    }

    public String doInBackground(String... arg0) {

            // so that they can be closed in the finally block.
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
            String authToken;

            try {
                // get logged in to get the api_authtoken
                String email = (String) arg0[0];
                String password = (String) arg0[1];

                URL url = new URL(loginUrl);

                // Create the request and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type", "application/json");
                urlConnection.setRequestProperty("Accept", "application/json");

                urlConnection.setDoOutput(true); //  HERE

                //put values of edittexts into json-Object
                JSONObject data = new JSONObject();
                try {
                    data.put("email", email);
                    data.put("password", password);
                } catch(JSONException e) {
                    Log.e("EXCEPTION", "unexpected JSON exception", e);
                    e.printStackTrace();
                }


            OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
            wr.write(data.toString());
            wr.flush();

            urlConnection.connect();

            reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            //read server response
            while((line = reader.readLine()) != null) {
                sb.append(line);
            }

            //receive server "answer"
            try {
                return getToken(sb.toString());
            }catch(JSONException e) {
                Log.e("LOG", "unexpected JSON exception", e);
                e.printStackTrace();
            }  finally{
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e("MainActivity", "Error closing stream", e);
                    }
                }
            }

            //return sb.toString();
            return null;
        }
        catch(IOException e) {
            Log.e("LoginTask", "Error ", e);
            // If the code didn't successfully get the data, there's no point in attempting
            // to parse it.
            //forecastJsonStr = null;
            return null;
        }
    }

    public void onPostExecute(String result) {
        super.onPostExecute(result);
        //Log.v("RESULT", result);
        if(result == null) {
            CharSequence text = "no internet connection";
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(MainActivity.this, text, duration);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.show();
        }

        if(loginSuccess == 0) {
            // if the request wasn't successful
            // give user a message via toast
            CharSequence text = "wrong password or user. please try again";
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(MainActivity.this, text, duration);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.show();
        }

        else {
            // save token in shared preferences
            SharedPreferences tokenPref = getSharedPreferences(getString(R.string.preference_token), Context.MODE_PRIVATE);
            SharedPreferences.Editor editorToken = tokenPref.edit();
            editorToken.putString(getString(R.string.saved_auth_token), result);
            editorToken.commit();

            //save login status = 1 in shared preferences
            SharedPreferences loginPref = getSharedPreferences(getString(R.string.preference_logged_in), Context.MODE_PRIVATE);
            SharedPreferences.Editor editorLogin = loginPref.edit();
            editorLogin.putString(getString(R.string.saved_login), "1");
            editorLogin.commit();

            Intent mapsIntent = new Intent(getApplicationContext(), MapsActivity.class);
            startActivity(mapsIntent);

        }
    }
}
Frosty
  • 500
  • 4
  • 14
  • this did not help :( – rudi Feb 15 '16 at 12:54
  • hi could you try out the edit as well. I just moved the connect() method call after output write. – Frosty Feb 15 '16 at 13:02
  • don't know why but today it works again though i didn't change a thing. i'm afraid the problem will show up again in the future but don't know what caused the problem – rudi Feb 16 '16 at 13:48
  • Hope it does'nt show up again but i would suggest you add this line "urlConnection.setDoOutput(true);" if you writing something on output stream. – Frosty Feb 17 '16 at 11:20