5

I've an app where i am trying to send data to a webservice using a http post. The user data is a mixture of strings int and doubles. In the app all are represented as Strings as when i use AsyncTask to run the network call, (so that it's not on the main thread), the params array is of type String.

The problem i have is that the server expects an int sometimes. eg compID is an int that the server expects. When using the http post, i use NameValuePair. This will only accept strings. How can i pass an int or a double to the http post?

In my activity.

String[] params = new String[]{tagCompany, tagId, tagPerson, OUT,
                                null, null,null, null, null, null}; 
                        AsyncPostData apd = new AsyncPostData();
                        apd.execute(params);





private class AsyncPostData extends AsyncTask<String, Void, Void> {

        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute()
        {
            progressDialog= ProgressDialog.show(NfcscannerActivity.this, 
                    "Connecting to Server"," Posting data...", true);            
        };  


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

            nfcscannerapplication.loginWebservice.postData(params[0], params[1], params[2], params[3], params[4],
                    params[5], params[6], params[7], params[8], params[9]);
            return null;
        }

         @Override
            protected void onPostExecute(Void result)
            {
             super.onPostExecute(result);
                if(progressDialog != null)
                progressDialog.dismiss();

            }
    }//end of AsyncPostData 

.

My post method

public void postData( String compID, String tagID, String clientID, String carerID, 
            String phoneScanned, String phoneSent, String TXType, String phoneType, String latitude, String longitude) {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://cfweb.yourofficeanywhere.co.uk:88/roadrunner.asmx/PostTransaction");


        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("CompanyID", compID));
            nameValuePairs.add(new BasicNameValuePair("TagID", tagID));
            nameValuePairs.add(new BasicNameValuePair("ClientID", clientID));
            nameValuePairs.add(new BasicNameValuePair("CarerID", carerID));
            nameValuePairs.add(new BasicNameValuePair("PhoneScanned", "2010-10-16 16:30 000"));
            nameValuePairs.add(new BasicNameValuePair("PhoneSent", "2010-10-16 16:32 000"));
            nameValuePairs.add(new BasicNameValuePair("TXType", "2"));
            nameValuePairs.add(new BasicNameValuePair("PhoneType", "2"));
            nameValuePairs.add(new BasicNameValuePair("Latitude", latitude));
            nameValuePairs.add(new BasicNameValuePair("Longitude", longitude));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            Log.e(TAG, "response of post = " + response.toString());



        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    } 

In my post method some of the values are set to null for now. What i would like to know is how to make compID an int in the NameValuePair. compID comes over from the activity as a String but the server expects an int.

3 Answers 3

11

You can do something like this:

nameValuePairs.add(new BasicNameValuePair("TXType",Integer.toString (2)));

TxType is the key and 2 is the value

3
  • Hi The variable compID is a String. NameValuePair will only accept <String,String> not <String, int>, but the server expects <String, int>
    – turtleboy
    Oct 17, 2012 at 10:29
  • you can change the datatype in the server, if it is possible. I guess that will be less tedious.
    – kittu88
    Oct 17, 2012 at 10:31
  • I've had a chat with director and he says we might be able to change what the server expects. like you say might be easier:)
    – turtleboy
    Oct 17, 2012 at 10:34
0

Just parse your String to Integer like this

int result = Integer.parseInt(compID);

But you have to be sure that your compID can be parsed to Integer. If it contains symbols that are not numbers, this operation will fail. To make sure that compID is parsable you can use this

if(compID.matches("(\\d+)"){
    result = Integer.parseInt(compId); }
6
  • Hi, this is the problem i have. if i go nameValuePairs.add(new BasicNameValuePair("CompanyID", Integer.parseInt(compID))); Eclipse complains that String, int is undefined for NameValuePair
    – turtleboy
    Oct 17, 2012 at 9:52
  • Try nameValuePairs.add(new BasicNameValuePair("CompanyID", ((int)Integer.parseInt(compID))));
    – Agata
    Oct 17, 2012 at 9:53
  • 1
    The constructor of BasicNameValuePair is (String, String), so it won't work.
    – Astrorvald
    Oct 17, 2012 at 10:00
  • So... your problem is that server accepts only int, but from application you can only send String?
    – Agata
    Oct 17, 2012 at 10:02
  • yes Astrorvald has got it right. The constructor is String String. I need to send String, int to server. So is there another data structure other than NameValePair that can handle this?
    – turtleboy
    Oct 17, 2012 at 10:32
0

it has been a long time since this question asked but I want to help those landing on this page. As in the argument above you cant use doubles or longs or ints in namevaluepair but you can use JSONObject , it can handle those primitives succesfully whereas You have A Bad Request Response with namevaluepair ,I wrote a sample below .

 JSONObject juo = new JSONObject();
    juo.put("City", txtCity.getText().toString().trim().toString());
    juo.put("ClassNumber",
            Long.parseLong(txtClassNumber.getText().toString()
                    .trim()));
    juo.put("EmailAddress", txtEmail.getText().toString().trim()
            .toString());
    juo.put("ID", Long.parseLong(userid));
    juo.put("RealName", txtRealName.getText().toString().trim());
    juo.put("RealSurname", txtRealSurname.getText().toString()
            .trim());
    juo.put("School", txtSchool.getText().toString().trim());
    juo.put("UserId", Long.parseLong(userid));
    juo.put("UserName", username);
    juo.put("UserProfileImage", profileImageUrl);

    StringEntity entityForPost = new StringEntity(juo.toString());
    hpost.setHeader("content-type", "application/json");
    // hpost.setEntity(new UrlEncodedFormEntity(UpdateParams));
    hpost.setEntity(entityForPost);

    HttpResponse hres = hclient.execute(hpost);

    StatusLine status = hres.getStatusLine(); 

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.