Paula Daniela
Paula Daniela

Reputation: 115

Error receiving response from the server?

I'm making an app that stores some data on a database, then it retrieves it. On the server side I'm working with PHP, and on the client side I've got this file that gets the input and pass it to the PHP file.

new AsyncTask<String, String, String>() {

                JSONParser jsonParser = new JSONParser();
                private ProgressBar pBar;
                private String url_post_pet = "http://192.168.0.13/Android/post_pet.php";

                // JSON Node names
                private static final String TAG_SUCCESS = "success";

                /**
                 * Before starting background thread Show Progress Dialog
                 */
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    //pBar = new ProgressBar();
                    //pBar.setIndeterminate(false);
                    //pBar.setVisibility(View.VISIBLE);
                }

                @Override
                protected String doInBackground(String... args) {
                    // Building Parameters
                    HashMap<String, String> params = new HashMap<>();
                    params.put("name", a);
                    params.put("breed", BREED);
                    params.put("type", TYPE);
                    params.put("images", "Whatever");
                    params.put("description", c);
                    params.put("coords", b);

                    // getting JSON Object
                    // Note that create product url accepts POST method
                    JSONObject json = jsonParser.makeHttpRequest(url_post_pet,
                            "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) {
                        System.out.println("exception" + e);
                        e.printStackTrace();
                    }
                    System.out.println("nul");
                    return null;
                }

                /**
                 * After completing background task Dismiss the progress dialog
                 **/
                protected void onPostExecute(String file_url) {
                    // dismiss the dialog once done
                    //pBar.dismiss();
                }
            }.execute();

        }
    });
}

Also, i've got this JSONParser:

public class JSONParser {

String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;

public JSONObject makeHttpRequest(String url, String method,
                                  HashMap<String, String> params) {

    sbParams = new StringBuilder();
    int i = 0;
    for (String key : params.keySet()) {
        try {
            if (i != 0){
                sbParams.append("&");
            }
            sbParams.append(key).append("=")
                    .append(URLEncoder.encode(params.get(key), charset));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        i++;
    }

    if (method.equals("POST")) {
        // request method is POST
        try {
            urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept-Charset", charset);
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.connect();

            paramsString = sbParams.toString();

            wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(paramsString);
            wr.flush();
            wr.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    else if(method.equals("GET")){
        // request method is GET

        if (sbParams.length() != 0) {
            url += "?" + sbParams.toString();
        }

        try {
            urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setDoOutput(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept-Charset", charset);
            conn.setConnectTimeout(15000);
            conn.connect();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    try {
        //Receive the response from the server
        InputStream in = new BufferedInputStream(conn.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        Log.d("JSON Parser", "result: " + result.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

    conn.disconnect();

    // try parse the string to a JSON object
    try {
        System.out.println(jObj);
        jObj = new JSONObject(result.toString());
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON Object
    return jObj;
}

And this is the error i get every time i submit the data:

08-26 12:51:08.236 5089-5156/chtecnologies.myapplication D/JSON Parser: result:08-26 12:51:08.239 5089-5156/chtecnologies.myapplication E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of 08-26 12:51:08.793 5089-5096/chtecnologies.myapplication W/art: Suspending all threads took: 190.496ms 08-26 12:51:09.245 5089-5096/chtecnologies.myapplication W/art: Suspending all threads took: 137.277ms 08-26 12:51:09.267 5089-5156/chtecnologies.myapplication E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1 Process: chtecnologies.myapplication, PID: 5089 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:304) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference at chtecnologies.myapplication.PostPet$4$1.doInBackground(PostPet.java:154) at chtecnologies.myapplication.PostPet$4$1.doInBackground(PostPet.java:118) at android.os.AsyncTask$2.call(AsyncTask.java:292) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)  at java.lang.Thread.run(Thread.java:818) 

The data successfully goes into the database, but there seems to be a problem in the JSONParser, than can't get the result of the PHP file.

Would you tell me if there's anything wrong in the JSONParser file or somewhere else? This is the first time that i implement a server in my app, i hope you can help me! Thanks

Upvotes: 0

Views: 861

Answers (1)

Ashvin Sharma
Ashvin Sharma

Reputation: 583

The way you are sending data looks fishy. If you want to send data in POST use HttpURLConnection like

String postParam = "name=" + a + "&breed=" + BREED + "&type=" + "&images=" +
        Whatever + "&description=" + c + "&coords=" + b;

try {
    URL url = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");

    OutputStream os = connection.getOutputStream();
    os.write(postParam.getBytes());
    os.flush();
    os.close();

    // Fetching the response code
    responseCode = connection.getResponseCode();
    Log.d(TAG, "POST Response Code: " + responseCode);
} catch (Exception e) {
    e.printStackTrace();
}

connection.setRequestMethod- sets Method you want to send your data with GET/POST

connection.setDoOutput(true)- to let you sent the output

connection.setDoInput(true)- to let you receive input after sending the data (if any)

Hope this solves your problem!

Upvotes: 1

Related Questions