0

I am trying to make a JSON AsynTack service call to login in my user. Unfortunately it is crashing on the openConnection with error message: an error occurred while executing doInBackground(). I am an iOS developer who is trying to learn Android so I apologies if I am missing something simple.

 public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;
        private final String mPassword;

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        UserLoginTask(String email, String password) {
            mEmail = email;
            mPassword = password;
        }


        @Override
        protected Boolean doInBackground(Void... params) {
            ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo info = cm.getActiveNetworkInfo();

            if(info==null || !info.isConnected()) {
                return false;
            }
                try {

                    URL url = new URL("http://urlForLoginHere");
                    urlConnection = (HttpsURLConnection) url.openConnection();
                    urlConnection.setReadTimeout(10000);
                    urlConnection.setConnectTimeout(15000);
                    urlConnection.setRequestMethod("POST");
                    urlConnection.setDoInput(true);
                    urlConnection.setDoOutput(true);

                    Uri.Builder builder = new Uri.Builder()
                            .appendQueryParameter("username", mEmail)
                            .appendQueryParameter("password", mPassword);
                    String query = builder.build().getEncodedQuery();

                    OutputStream os = urlConnection.getOutputStream();
                    BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(os, "UTF-8"));
                    writer.write(query);
                    writer.flush();
                    writer.close();
                    os.close();

                    urlConnection.connect();


                    // Read the input stream into a String
                    InputStream inputStream = urlConnection.getInputStream();
                    StringBuffer buffer = new StringBuffer();
                    if (inputStream == null) {
                        // Nothing to do.
                        return false;
                    }
                   // reader = new BufferedReader(new InputStreamReader(inputStream));

                    if (buffer.length() == 0) {
                        // Stream was empty.  No point in parsing.
                        return false;
                    }

                    String jsonString = buffer.toString();


                    urlConnection.setConnectTimeout(3000);
                    urlConnection.connect();
                    if (urlConnection.getResponseCode() == 200) {
//                        try {
//
//                        }
                        return true;
                    }
                } catch (MalformedURLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            return  false;
        }
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
user1079052
  • 3,803
  • 4
  • 30
  • 55

1 Answers1

0

Not sure if this is the cause but, your urlConnection statements seems incorrect. Try with the following code:

    URL url = new URL("http://urlForLoginHere");
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);

    Uri.Builder builder = new Uri.Builder()
            .appendQueryParameter("username", mEmail)
            .appendQueryParameter("password", mPassword);
    String query = builder.build().getEncodedQuery();

    OutputStream os = urlConnection.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
    writer.write(query);
    writer.flush();
    writer.close();
    os.close();

    // reader = new BufferedReader(new InputStreamReader(inputStream));

    String jsonString = buffer.toString();

    if (urlConnection.getResponseCode() == 200) {
        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        // do stuff here
        return true;
    }
    else {
        InputStream inputStream = urlConnection.getErrorStream();
        // :(
    } 
Shaishav
  • 5,282
  • 2
  • 22
  • 41
  • i tried and it crashed on HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); with error HostConnection::get() New Host Connection established 0x7f563540dd40, tid 5477 09-01 14:58:59.278 5382-5477/ctsapp.purple.com.setec I/OpenGLRenderer: Initialized EGL, version 1.4 09-01 14:59:00.114 5382-5382/ctsapp.purple.com.setec I/Choreographer: Skipped 38 frames! The application may be doing too much work on its main thread. – user1079052 Sep 01 '16 at 19:00
  • So, the same error as earlier. Wait. Are you executing this method by manually calling `doInBackground()`? – Shaishav Sep 01 '16 at 19:02
  • I have updated my code to show all of it. I am calling it with mAuthTask = new UserLoginTask(email, password); mAuthTask.execute((Void) null); – user1079052 Sep 02 '16 at 12:33
  • @user1079052 You don't need to call `urlConnection.connect()` anywhere (open connection should do it). Also, if you feel like it, post your updated code in your question itself so others can check it too. – Shaishav Sep 02 '16 at 12:39