0

I am trying to send text values to server which are name, phone, location, remarks but every time each value is missing first time name is not going , next time phone and next location...

Update:

Jsoncode:

public static String POST(String url, Persoenter code heren person){
    InputStream inputStream = null;
    String result = "";
    try {

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        String json = "";
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("name",person.getName());
        jsonObject.accumulate("phone", person.getPhone());
        jsonObject.accumulate("remarrks",person.getRemarks());
        jsonObject.accumulate("credated_dt", person.getCreatedat());

        jsonObject.accumulate("emp_code", person.getCreatedby());

        jsonObject.accumulate("location", person.getLocation());
        jsonObject.accumulate("add_fld1", "Test");
        jsonObject.accumulate("add_fld2", "Test");
        jsonObject.accumulate("add_fld3", "Test");




        json = jsonObject.toString();
        StringEntity se = new StringEntity(json);
        Log.e("sent",""+json);
        httpPost.setEntity(se);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        HttpResponse httpResponse = httpclient.execute(httpPost);

        inputStream = httpResponse.getEntity().getContent();
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";
    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }
    return result;
}

Httppost

private class sync extends AsyncTask<String, String, String> {


    InputStream inputStream = null;
    OutputStream outputStream = null;

    protected String doInBackground(String... urls) {

        person = new Person();

        person.setName(eName.getText().toString());
        person.setPhone(ePhonenumber.getText().toString());
        person.setLocation(eLocation.getText().toString());
        person.setRemarks(eRemarks.getText().toString());
        person.setCreatedby(eCreatedby.getText().toString());
        person.setCreatedat(eCreatedat.getText().toString());
        return POST(urls[0],person);
    }
@Override
    protected void onPreExecute() {
        progress.setTitle("Connecting to server");
        progress.setMessage("Sending Data.... Please wait!");
        progress.setCanceledOnTouchOutside(false);
        progress.show();
    }

    @Override
    protected void onPostExecute(String s) {
                progress.dismiss();
                 Intent Homeintent = getIntent();
Homeintent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(Homeintent);

    }

Output 1:{"name":"beta33","phone":"33","remarrks":"33","credated_dt":"2017-12-20 11:56:32","emp_code":"test@gmail.com","location":"33"} 2:{"name":"beta33","phone":"33","remarrks":"33","credated_dt":"2017-12-20 11:56:43","emp_code":"test@gmail.com","location":"33"} 3:{"name":"","phone":"34","remarrks":"34","credated_dt":"2017-12-20 11:56:52","emp_code":"test@gmail.com","location":"34"}

After trying one or two attemps now the name is not going i don't know why..please someone help me out of this

Flash
  • 13
  • 5
  • 2
    I suggest you use a networking library such as volley or retrofit to handle these kind of operations. This kind of procedure is outdated and it becomes difficult to maintain as your project expands. – stebak Dec 18 '17 at 11:29
  • yeah i thought to using volley..but as of now this is required – Flash Dec 18 '17 at 11:34
  • Check the value of `JSONObject joj = getonline();` in debug mode. Whether you are getting expected values. – Monish Kamble Dec 18 '17 at 11:40
  • I suggest passing values through url. refer https://stackoverflow.com/a/8655039/5193533 "data" is passed as part of the url string. – stebak Dec 18 '17 at 11:47
  • @KBJ Actually my URL Connection is a working one only..which is sending values correctly for other option.The error which i am getting is when net is online and if i click save the values from the Edit Fields should go to server, first time all values went successfully and from then some values are going null – Flash Dec 18 '17 at 11:54
  • Please edit your question and be specific about what really is the problem here. Also i suggest you use an AsyncTask to prevent the app from crashing on main UI. – stebak Dec 18 '17 at 11:57
  • @KBJ the httpconnection is from AsyncTask doInBackground only i didn't pasted that because everyone knows about it right – Flash Dec 19 '17 at 03:53

1 Answers1

-2

I'm posting a working code sample, replace yours with this, then find what's the mistake here.

try {
            URL url = new URL("http://-------");
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST"); 
            httpURLConnection.setRequestProperty("Content-Type", "application/json"); 
            httpURLConnection.connect();
            DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
            wr.write(inputJson.getBytes());   //your input json in string format
            wr.flush();
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (httpURLConnection.getInputStream())));
            StringBuffer bfr = new StringBuffer();
            String output = "";
            while ((output = br.readLine()) != null) {
                bfr.append(output);
            }
            String serverPostRes = bfr.toString();
            wr.close();
            httpURLConnection.disconnect();
            bfr.delete(0,bfr.length());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serverPostRes;
    }

The inputJson in your question You can pass

    String inputJson = "{   "
            + "     \"add_fld1\": \"" + ("Test"+ i) + "\","
            + "     \"add_fld2\": \"" + ("Test"+ i+1) + "\","
            + "     \"add_fld3\": \"" + ("Test"+ i+2) + "\","
            + "     \"credated_dt\": \"" + formattedDate + "\","
            + "     \"emp_code\": \"" + eCreatedby.getText().toString() + "\","
            + "     \"location\": \"" + eLocation.getText().toString() + "\","
            + "     \"name\": \"" + eName.getText().toString() + "\","
            + "     \"phone\": \"" + ePhonenumber.getText().toString() + "\","
            + "     \"remarrks\": \"" + eRemarks.getText().toString() + "\","
            + "}";
Shambhu
  • 181
  • 6
  • 16
  • problem is not with connection..the only difference between your code and mine is you are using http post and i am using URL Connection..my URL Connection is a working code only – Flash Dec 18 '17 at 11:47
  • 1
    Both codes are using "POST" methods. This answer doesn't contain passing of values to the server side, which i believe is the main problem here. – stebak Dec 18 '17 at 11:54
  • I'm also using the same 'HttpURLConnection `. pls check once again. The problem is there to send the request and handling the response. – Shambhu Dec 18 '17 at 11:55
  • The line which is having commented part at the left side, here `inputJson` is the input value in the `json-string` format. @KBJ @flash – Shambhu Dec 18 '17 at 11:57
  • And this code is working perfectly. `serverPostRes` is the response converted into String. – Shambhu Dec 18 '17 at 11:58
  • Seen, my bad. @SNSingh – stebak Dec 18 '17 at 12:00
  • what should i give here _wr.write(inputJson.getBytes());_ – Flash Dec 18 '17 at 12:00
  • You can call your method that returns your input json there @Flash. Just create a void method for it. – stebak Dec 18 '17 at 12:02
  • well my ide is suggesting this `wr.write(Integer.parseInt(joj.toString()));` – Flash Dec 18 '17 at 12:06
  • `DataOutputStream` is not for HTTP communication as HTTP protocol knows nothing about *primitive Java data types* ... – Selvin Dec 18 '17 at 12:23
  • @Flash update: in your case the `inputJson` can be passed in this way. – Shambhu Dec 18 '17 at 13:37
  • @downvoters, let me know the reason. This code is working perfectly in my case. – Shambhu Dec 19 '17 at 01:59