0

I have made a signup form that sends the data taken from the signup function and post to the url(which is actually saved in another class) The problem is that the json object isnt being sent to the server. The reponse from the server states that " {"settings":{"success":"0","message":"Please enter a value for the first_name field.","fields":[]},"data":[]}"
Can someone please help me understand where have I gone wrong. Here are my code snippets:

public void signup() throws JSONException {
    String firstname = edittext_fname.getText().toString();
    String lastname = editext_lname.getText().toString();
    String email = editext_email.getText().toString();
    String mobile = editext_mobile.getText().toString();
    String pass = editext_pass.getText().toString();
    String username = editext_user.getText().toString();
    String address = editext_add.getText().toString();
    String cityname = editText_city.getText().toString();
    String zipcode = editText_Zip.getText().toString();
    String city_id = editText_cityid.getText().toString();
    String birthdate = textView_birth.getText().toString();
    String statename = textView_state.getText().toString();
    String stateid = state_id;

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("first_name", firstname);
    jsonObject.put("last_name", lastname);
    jsonObject.put("birth_date", birthdate);
    jsonObject.put("email", email);
    jsonObject.put("user_name", username);
    jsonObject.put("password", pass);
    jsonObject.put("mobile_no", mobile);
    jsonObject.put("address", address);
    jsonObject.put("zip_code", zipcode);
    jsonObject.put("city_id", city_id);
    jsonObject.put("city", cityname);
    jsonObject.put("state_id", stateid);
    jsonObject.put("reference_name", "xxx");
    jsonObject.put("country_id", "223");
    jsonObject.put("refer_by", "others");
    jsonObject.put("user_role_type", "3");

    if (jsonObject.length() > 0) {
        new sendJsonData().execute(String.valueOf(jsonObject));
    }


}

Async class that sets up HttpUrlConnection and appends json object

private class sendJsonData extends AsyncTask<String, Void, String> {
    ProgressDialog progressDialog;
    String Jsonresponse = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(FirstScreenActivity.this);
        progressDialog.setMessage("please wait");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        String Jsondata = params[0];

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        try {

            URL url = new URL(WsUtils.BASE_URL+WsUtils.SIGNUP);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setConnectTimeout(10000);
            urlConnection.setRequestProperty("Accept","application/json");
            urlConnection.setRequestProperty("Content-Type","application/json");

            //Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
            //writer.write(Jsondata);
           // writer.close();

            DataOutputStream printout = new DataOutputStream(urlConnection.getOutputStream ());
            printout.writeBytes("PostData=" + Jsondata);
            printout.writeBytes(Jsondata);
            Log.e("json", Jsondata);

           // printout.flush ();
           // printout.close ();

            DataInputStream in = new DataInputStream(urlConnection.getInputStream());
            Jsonresponse = convertStreamToString(in);




            return Jsonresponse;


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

        return null;
    }


    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        progressDialog.dismiss();
        Log.e("response", Jsonresponse);

    }


}

This is just to get the input (response) to string and get display!

public String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
4
  • can you show us the response which you are ggetting Commented Mar 2, 2017 at 10:12
  • response: {"settings":{"success":"0","message":"Please enter a value for the first_name field.","fields":[]},"data":[]} Commented Mar 2, 2017 at 10:18
  • i think first name is null. did you check whether first name is null before sending? Commented Mar 2, 2017 at 10:22
  • see my json object as recieved at the log after into doinbackground gives this::::::::::::::::::::>>>>E/json: {"first_name":"sana","last_name":"Baid","birth_date":"7-3-2017","email":"[email protected]","user_name":"sbaid","password":"Da1=","mobile_no":"9898813889","address":"fdfd","zip_code" Commented Mar 2, 2017 at 10:33

4 Answers 4

2

Here You can see that how to post data using HttpURLConnection

public class sendJsonData  extends AsyncTask<String, Void, String> {

    protected void onPreExecute(){}

    protected String doInBackground(String... arg0) {

      try {

          URL url = new URL(WsUtils.BASE_URL+WsUtils.SIGNUP); // here is your URL path

        JSONObject jsonObject = new JSONObject();
jsonObject.put("first_name", firstname);
jsonObject.put("last_name", lastname);
jsonObject.put("birth_date", birthdate);
jsonObject.put("email", email);
jsonObject.put("user_name", username);
jsonObject.put("password", pass);
jsonObject.put("mobile_no", mobile);
jsonObject.put("address", address);
jsonObject.put("zip_code", zipcode);
jsonObject.put("city_id", city_id);
jsonObject.put("city", cityname);
jsonObject.put("state_id", stateid);
jsonObject.put("reference_name", "xxx");
jsonObject.put("country_id", "223");
jsonObject.put("refer_by", "others");
jsonObject.put("user_role_type", "3");
        Log.e("params",postDataParams.toString());

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        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(jsonObject));

            writer.flush();
            writer.close();
            os.close();

            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                BufferedReader in=new BufferedReader(
                           new InputStreamReader(
                             conn.getInputStream()));
                StringBuffer sb = new StringBuffer("");
                String line="";

                while((line = in.readLine()) != null) {

                    sb.append(line);
                    break;
                }

                in.close();
                return sb.toString();

            }
            else {
                return new String("false : "+responseCode);
            }
        }
        catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }

    }

    @Override
    protected void onPostExecute(String result) {
         progressDialog.dismiss();
         Log.e("response", result);
    }
}

public String getPostDataString(JSONObject params) throws Exception {

    StringBuilder result = new StringBuilder();
    boolean first = true;

    Iterator<String> itr = params.keys();

    while(itr.hasNext()){

        String key= itr.next();
        Object value = params.get(key);

        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(key, "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(value.toString(), "UTF-8"));

    }
    return result.toString();
}
Sign up to request clarification or add additional context in comments.

7 Comments

THIS HAS SOLVED THE PROBLEM!! THANKYOU VERY VERY MUCH,, But i just wanted to ask why do we need to change the json object to the input parameter style as you have done in getPostDataString? if we have to change this then why do we use json objects in the first place?
Your most welcome, if this answer really solve your problem then please don't forget to accept the answer.
But i just wanted to ask why do we need to change the json object to the input parameter style as you have done in getPostDataString? if we have to change this then why do we use json objects in the first place? –
It is not compulsory to use JsonObject only you can also use HashMap. OR any other class object which can hold multiple values inside it and we pass it to getPostDataString() method which will iterate and use all parameters.
Thanks for accepting the answer and also requested to up vote the answer.
|
0

Use this library called ion: https://github.com/koush/ion . All you have to do is add it the dependency in your app build.gradle like this:

compile 'com.koushikdutta.ion:ion:2.+'

Then sending json data to your server is as simple as this:

public void signup() throws JSONException {
        String firstname = edittext_fname.getText().toString();
        String lastname = editext_lname.getText().toString();
        String email = editext_email.getText().toString();
        String mobile = editext_mobile.getText().toString();
        String pass = editext_pass.getText().toString();
        String username = editext_user.getText().toString();
        String address = editext_add.getText().toString();
        String cityname = editText_city.getText().toString();
        String zipcode = editText_Zip.getText().toString();
        String city_id = editText_cityid.getText().toString();
        String birthdate = textView_birth.getText().toString();
        String statename = textView_state.getText().toString();
        String stateid = state_id;

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("first_name", firstname);
        jsonObject.addProperty("last_name", lastname);
        jsonObject.addProperty("birth_date", birthdate);
        jsonObject.addProperty("email", email);
        jsonObject.addProperty("user_name", username);
        jsonObject.addProperty("password", pass);
        jsonObject.addProperty("mobile_no", mobile);
        jsonObject.addProperty("address", address);
        jsonObject.addProperty("zip_code", zipcode);
        jsonObject.addProperty("city_id", city_id);
        jsonObject.addProperty("city", cityname);
        jsonObject.addProperty("state_id", stateid);
        jsonObject.addProperty("reference_name", "xxx");
        jsonObject.addProperty("country_id", "223");
        jsonObject.addProperty("refer_by", "others");
        jsonObject.addProperty("user_role_type", "3");

        Ion.with(context)
                .load(WsUtils.BASE_URL+WsUtils.SIGNUP)
                .setJsonObjectBody(jsonObject)
                .asJsonObject()
                .setCallback(new FutureCallback<JsonObject>() {
                    @Override
                    public void onCompleted(Exception e, JsonObject result) {
                        if(e != null) {
                            //AN ERROR OCCURRED
                            return;
                        }

                        //REQUEST WAS SUCCESSFUL
                    }
                });


    }

2 Comments

Can u please explain how what change will it bring? Also it would really nice if u could help me know where i went wrong. Thanks :)
How will i get to know whether the server has received the data or not?
0

// make a Global class for connection

public class ConnectAsynchronously {

private static int requestCode;
private static String myMessage;

public static String connectAsynchronously(String uri) {
    String result ="";
    try {
        //Connect
        HttpURLConnection urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
        urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        urlConnection.setRequestMethod("GET");

        urlConnection.connect();
        requestCode=urlConnection.getResponseCode();
        myMessage = urlConnection.getResponseMessage();
        //Read
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        bufferedReader.close();
        result = sb.toString();
    }  catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

public static String connectAsynchronously(String uri, JSONObject jobj) {
    String result ="";
    try {
        //Connect
        HttpURLConnection urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
        urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.connect();

        //Write
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(jobj.toString());
        writer.close();
        outputStream.close();
        requestCode=urlConnection.getResponseCode();
        myMessage = urlConnection.getResponseMessage();

        //Read
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
        String line ;
        StringBuilder sb = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        bufferedReader.close();
        result = sb.toString();
    }  catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}



public static int getRequestCode(){

    return requestCode;
}

public static String getRequestMessage(){

    return myMessage;
}

}

//And Now in your main Activity post data like

//Make a Class

 private class RegistrationTask extends AsyncTask<String, Void, String> {
    final JSONObject jsonObject;

    public RegistrationTask(JSONObject jsonObject) {
        this.jsonObject = jsonObject;
    }

    @Override
    protected String doInBackground(String... params) {
        return ConnectAsynchronously.connectAsynchronously(params[0],jsonObject);
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        int requestCode =ConnectAsynchronously.getRequestCode();
        if(requestCode== HttpURLConnection.HTTP_OK){
            //sucess
        }else {
            Toast.makeText(getApplicationContext(),ConnectAsynchronously.getRequestMessage(),Toast.LENGTH_LONG).show();
        }

    }
}

//and finally do request

 JSONObject jsonObject =new JSONObject();
    try {
        jsonObject.put("","");
       /* make ur Json Object like this*/
    } catch (JSONException e) {
        e.printStackTrace();
    }

    new RegistrationTask(jsonObject).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"YOUR_POST_URL");

4 Comments

@Have you make sure what ever api you are using is correct? If there is any doubt then i will suggest you install postman plugin for chrome and hit api directly with your data .
@this api was given to me by my sir! also the webserver is giving the above mentioned response !
@sana baid,Have you resolved the problem? And above code is working fine, i have checked.
ya actually i converted my json object to to key=value& format by the help of iterator as mentioned in solutions in my accepted answer. It works, but Is it the correct way?
0

use :

   OutputStream os = conn.getOutputStream();
   os.write(json.toString().getBytes("UTF-8"));
   os.close();

instead of:

DataOutputStream printout = new DataOutputStream(urlConnection.getOutputStream ());
printout.writeBytes("PostData=" + Jsondata);
printout.writeBytes(Jsondata);

4 Comments

Same response!! can there be a different error? As in not my code's error?
sodhankit's code worked for me. Thanks for your help!
@sanabaid i am kushaal singla :P
i meant sodhankits code worked for me! :p and thanks for trying to help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.