AsyncTask does not return a JSON response on onPostExecute in the first try, but works fine starting from second try

63 views Asked by At

So, I have a method that's called when a button it's pressed and it should add some info to my database(latitude, longitude etc). The weird behaviors it's that when I open the app,(the app adds a marker, and the button comes alive onMarkerClick) if I press that button, it wont work, the JSON response will be null, but with the same marker, on a second try it will work just fine(I get latitude and longitude inside onMarkerClick. I have checked the values of every param I send using doInBackground and every parameter looks fine, has a value etc.

This si the method:

  public void RaporteazaAlerta() {
        User user = SharedPrefManager.getInstance(this).getUser();
        final String lat = String.valueOf(latitudine_marker);
        final String longit = String.valueOf(longitudine_marker);
        final String problema1 = String.valueOf(problema+1);
        final String descriere1 = descriere;
        final String id_user =  String.valueOf(user.getId());
        id= id_user;
        class  RaporteazaAlerta extends AsyncTask<Void, Void, String> {

            @Override
            protected String doInBackground(Void... voids) {
                //creating request handler object
                RequestHandler requestHandler = new RequestHandler();

                //creating request parameters
                HashMap<String, String> params = new HashMap<>();
                params.put("latitudine", lat);
                params.put("longitudine", longit);
                params.put("id_problema", problema1);
                params.put("ID_user", id_user);
                params.put("descriere", descriere1);

                //returing the response
                return requestHandler.sendPostRequest(URLs.URL_ALERTA, params);
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                //displaying the progress bar while user registers on the server
            }

            @Override
            protected void onPostExecute(String s) {{
                super.onPostExecute(s);


                try {
                    JSONObject obj = new JSONObject(s);

                    //if no error in response
                    if (!obj.getBoolean("error")) {
                        Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();

                    } else {
                        Toast.makeText(getApplicationContext(), "Nu se poate adauga alerta", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                layout_buton.setVisibility(View.GONE);
                linearLayout.setVisibility(View.GONE);
                linearLayout_obs.setVisibility(View.GONE);
                linearLayout_obs_inapoi.setVisibility(View.GONE);
                observatii.setText(null);
                hideSoftKeyboard(observatii);
            }
            }
        }
        RaporteazaAlerta report = new RaporteazaAlerta();
        report.execute();
    }

Checking the log for more info, I found out that there's an System.err:

W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference at:

2020-03-12 13:29:40.385 23142-23262/com.scopesystems.cityalert W/System.err:     at java.net.URLEncoder.encode(URLEncoder.java:205)
2020-03-12 13:29:40.385 23142-23262/com.scopesystems.cityalert W/System.err:     at com.scopesystems.cityalert.suport.RequestHandler.getPostDataString(RequestHandler.java:69)
2020-03-12 13:29:40.385 23142-23262/com.scopesystems.cityalert W/System.err:     at com.scopesystems.cityalert.suport.RequestHandler.sendPostRequest(RequestHandler.java:35)
2020-03-12 13:29:40.386 23142-23262/com.scopesystems.cityalert W/System.err:     at com.scopesystems.cityalert.ui.Harta$1RaporteazaAlerta.doInBackground(Harta.java:579)
2020-03-12 13:29:40.386 23142-23262/com.scopesystems.cityalert W/System.err:     at com.scopesystems.cityalert.ui.Harta$1RaporteazaAlerta.doInBackground(Harta.java:563)

The RequestHandler which works fine on second try, and with any other AsyncTask:

public class RequestHandler {
    public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) {
        URL url;

        StringBuilder sb = new StringBuilder();
        try {
            url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();

            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;

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

}

In the log there's also something about org.json.JSONException: End of input at character 0 of but that I assume it's because I do not have any response from the server.

EDIT: Full logput output:

2020-03-12 13:50:13.901 23545-23598/com.scopesystems.cityalert W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
2020-03-12 13:50:13.901 23545-23598/com.scopesystems.cityalert W/System.err:     at java.net.URLEncoder.encode(URLEncoder.java:205)
2020-03-12 13:50:13.901 23545-23598/com.scopesystems.cityalert W/System.err:     at com.scopesystems.cityalert.suport.RequestHandler.getPostDataString(RequestHandler.java:69)
2020-03-12 13:50:13.901 23545-23598/com.scopesystems.cityalert W/System.err:     at com.scopesystems.cityalert.suport.RequestHandler.sendPostRequest(RequestHandler.java:35)
2020-03-12 13:50:13.902 23545-23598/com.scopesystems.cityalert W/System.err:     at com.scopesystems.cityalert.ui.Harta$1RaporteazaAlerta.doInBackground(Harta.java:579)
2020-03-12 13:50:13.902 23545-23598/com.scopesystems.cityalert W/System.err:     at com.scopesystems.cityalert.ui.Harta$1RaporteazaAlerta.doInBackground(Harta.java:563)
2020-03-12 13:50:13.902 23545-23598/com.scopesystems.cityalert W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:304)
2020-03-12 13:50:13.902 23545-23598/com.scopesystems.cityalert W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
2020-03-12 13:50:13.902 23545-23598/com.scopesystems.cityalert W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
2020-03-12 13:50:13.902 23545-23598/com.scopesystems.cityalert W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
2020-03-12 13:50:13.902 23545-23598/com.scopesystems.cityalert W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
2020-03-12 13:50:13.902 23545-23598/com.scopesystems.cityalert W/System.err:     at java.lang.Thread.run(Thread.java:761)
2020-03-12 13:50:13.906 23545-23545/com.scopesystems.cityalert W/System.err: org.json.JSONException: End of input at character 0 of 
2020-03-12 13:50:13.906 23545-23545/com.scopesystems.cityalert W/System.err:     at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
2020-03-12 13:50:13.906 23545-23545/com.scopesystems.cityalert W/System.err:     at org.json.JSONTokener.nextValue(JSONTokener.java:97)
2020-03-12 13:50:13.906 23545-23545/com.scopesystems.cityalert W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:156)
2020-03-12 13:50:13.906 23545-23545/com.scopesystems.cityalert W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
2020-03-12 13:50:13.906 23545-23545/com.scopesystems.cityalert W/System.err:     at com.scopesystems.cityalert.ui.Harta$1RaporteazaAlerta.onPostExecute(Harta.java:594)
2020-03-12 13:50:13.906 23545-23545/com.scopesystems.cityalert W/System.err:     at com.scopesystems.cityalert.ui.Harta$1RaporteazaAlerta.onPostExecute(Harta.java:563)
2020-03-12 13:50:13.906 23545-23545/com.scopesystems.cityalert W/System.err:     at android.os.AsyncTask.finish(AsyncTask.java:660)
2020-03-12 13:50:13.906 23545-23545/com.scopesystems.cityalert W/System.err:     at android.os.AsyncTask.-wrap1(AsyncTask.java)
2020-03-12 13:50:13.907 23545-23545/com.scopesystems.cityalert W/System.err:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
2020-03-12 13:50:13.907 23545-23545/com.scopesystems.cityalert W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
2020-03-12 13:50:13.907 23545-23545/com.scopesystems.cityalert W/System.err:     at android.os.Looper.loop(Looper.java:154)
2020-03-12 13:50:13.907 23545-23545/com.scopesystems.cityalert W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6077)
2020-03-12 13:50:13.907 23545-23545/com.scopesystems.cityalert W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
2020-03-12 13:50:13.907 23545-23545/com.scopesystems.cityalert W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
2020-03-12 13:50:13.907 23545-23545/com.scopesystems.cityalert W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
1

There are 1 answers

0
Costin On

As per @Mike M., I actually misschecked a value, of descriere1 which was indeed null. The null meant that there was no description added, so I changed the code:

    public void RaporteazaAlerta() {
        User user = SharedPrefManager.getInstance(this).getUser();
        final String lat = String.valueOf(latitudine_marker);
        final String longit = String.valueOf(longitudine_marker);
        final String problema1 = String.valueOf(problema+1);
        String descriere1 = descriere;
        if(descriere1 == null){
            descriere1 = "null";
        }

      final String id_user =  String.valueOf(user.getId());
        id= id_user;
        final String finalDescriere = descriere1;
        class  RaporteazaAlerta extends AsyncTask<Void, Void, String> {

            @Override
            protected String doInBackground(Void... voids) {
                //creating request handler object
                RequestHandler requestHandler = new RequestHandler();

                //creating request parameters
                HashMap<String, String> params = new HashMap<>();
                params.put("latitudine", lat);
                params.put("longitudine", longit);
                params.put("id_problema", problema1);
                params.put("ID_user", id_user);
                params.put("descriere", finalDescriere);

                //returing the response
                return requestHandler.sendPostRequest(URLs.URL_ALERTA, params);
            }