0

I am completely new to Android.

I have a list of data receiving in my 'onActivityResult'. I converted them as json array in the format [{"name":"net","price":"20"},{"name":"samsung","price":"11220"}] now I want to attach this to a url and want to send like this format

http://xyz/abc/purchasedetails=[{“name”:”Samsung”,”price”=“45”},{“name”:”Nokia”,”price”=“25”},{“name”:”Lenovo”,”price”=“115”}]

What I have done so far:

public class SendDataToServer extends Fragment {

    int publishStatusCode = 0;

    public interface SendProductDetailsToServerCallbacks {
        public void OnPostExcecuteSendMilestoneDetailsToServerAsync(int _publishStatus,
                                                                    String _responseString);
    }

    SendProductDetailsToServerAsync mSendProductDetailsToServerAsync;
    SendProductDetailsToServerCallbacks mSendProductDetailsToServerCallbacks;

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        try {
            mSendProductDetailsToServerCallbacks =
                    (SendProductDetailsToServerCallbacks) activity;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

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

        String DataToSend = "";

        public SendProductDetailsToServerAsync(String _DataToSend) {
            DataToSend = _DataToSend;

        }

        @Override
        protected String doInBackground(Void... params) {
            boolean isDoRequestAgain = false;
            String result = "";
            do {
                isDoRequestAgain = false;
               /* List<NameValuePair> nameValuePairs = new
                        ArrayList<NameValuePair>();*/


                JSONObject json = new JSONObject();
                try {



                    String totalUrl = "http://androidxyz.com/android/vendor/purchasedetails.jsp?purchasedetails=" + DataToSend;

                    HttpPost post = new HttpPost(totalUrl);
                    HttpClient client = new DefaultHttpClient();
                    HttpResponse response;

                    /*nameValuePairs.add(new BasicNameValuePair(
                            "milestonedata", json.toString()));*/

                    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    response = client.execute(post);
                    publishStatusCode = response.getStatusLine().getStatusCode();
                    HttpEntity entity = response.getEntity();

                    if (entity != null) {

                        InputStream instream = entity.getContent();
                        StringBuffer buffer = new StringBuffer();
                        byte[] b = new byte[4096];
                        for (int n; (n = instream.read(b)) != -1; ) {
                            buffer.append(new String(b, 0, n));
                        }

                        result = buffer.toString();

                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } while (isDoRequestAgain);
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            Log.v("publishStatusCode", publishStatusCode + "");
            Log.v("result", result + "");
            mSendProductDetailsToServerCallbacks.OnPostExcecuteSendMilestoneDetailsToServerAsync(publishStatusCode, result);
        }

    }

    public void startSendMilestoneDetailsToServerAsync(String _dataToSend) {
        mSendProductDetailsToServerAsync = new SendProductDetailsToServerAsync(_dataToSend);
        mSendProductDetailsToServerAsync.execute();
    }
}

What change I have to do here to make my code work?

DataToSend is [{"name":"net","price":"20"},{"name":"samsung","price":"11220"}].

8
  • What is the issue, you are facing? Commented Mar 10, 2016 at 5:16
  • i dont know how to start? I started with Asyntask..then?? Commented Mar 10, 2016 at 5:21
  • Then, you need to parse the data in the server side, after sending the data from android device. Commented Mar 10, 2016 at 5:22
  • how to send from android device?? Commented Mar 10, 2016 at 5:22
  • Basically you can use any library or you can write your custom code. Commented Mar 10, 2016 at 5:24

4 Answers 4

0

This method will post your data

public static String httpPost(HashMap<String, String> map, String url, String token) {
    Log.e("call ", "running");
    HttpRequest request;

    if(token!=null){
        request = HttpRequest.post(url).accept("application/json")
                .header("Authorization", "Token " + AppInfo.token).form(map);
    }
    else request = HttpRequest.post(url).accept("application/json").form(map);

    int responseCode = request.code();
    String text = request.body();

    Log.e("response", " "+responseCode+ " "+ text);

    if(responseCode==400){
        return "invalid_tocken";

    }
    else if(responseCode<200 || responseCode>=300) {

        return "error";
    }

    return text;
}

Hope you can convert the JSONArray to HashMap. If you instead need to post it as a JSONArray itself, then OkHttp library will help you.

Sign up to request clarification or add additional context in comments.

6 Comments

can you help me with my code in the edited question??
sure. So you need to post it as a hashmap or as a jsonarray?
here .post is showing error 'HttpRequest.post' cannot resolve method
Which one you need? I suggest you to use Okhttp library. I do is using it
i need to post as jsonarray
|
0

You have to create json array and than post it with as jasonArray.toString into param.

Following is just example that may help you to understand.

private void generateCartJsonArray() {
    JSONArray jArrayMain = null;
    // send to php
    Set<String> keys = Utility.CartDetailsList.keySet();
    for (String key : keys) {
        if (Utility.CartDetailsList.containsKey(key)) {
            //creatign json obj for send to php
            cartObj = new JSONObject();
            try {
                cartObj.put("psid", key.toString());//psid
                cartObj.put("SelectedQuantity", String.valueOf(Utility.CartDetailsList.get(key).addQuantity));//SelectedQuantity
                cartObj.put("DiscountQuantity", String.valueOf(Utility.CartDetailsList.get(key).freeQuantity));//DiscountQuantity
                cartObj.put("FinalAmount", String.valueOf(Utility.CartDetailsList.get(key).totalprice));//final amount
                jArrayMain = jsonArray.put(cartObj);
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        }
    }
    if (jArrayMain != null) {
        verifyOrder(jArrayMain); // verify before place order
    }
}

private void verifyOrder(final JSONArray cartarrayData) {

    final Dialog dialog = new Dialog(CartActivity.this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.progress_dialog);
    dialog.setCancelable(false);


    TextView text = (TextView) dialog.findViewById(R.id.tvProcessDialogTitle);
    if (Utility.language.equals(CartActivity.this.getResources().getString(R.string.Gujarati))) {
        text.setTypeface(Utility.AppsGujratiFont);
        text.setText(CartActivity.this.getResources().getString(R.string.verify_order_please_wait_guj));
    } else {
        text.setText(CartActivity.this.getResources().getString(R.string.verify_order_please_wait_eng));
    }

    dialog.show();


    StringRequest sr = new StringRequest(Request.Method.POST, Constant.VERIFY_MY_ORDER, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {


            mverifyOrderResponse = JSONUtils.verifyOrderResponse(response);
            dialog.dismiss();
            showVerifyMessage();

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            dialog.dismiss();

        }
    }) {
        @Override
        protected Map<String, String> getParams() {

            String dd = selected_Date;

            Map<String, String> params = new HashMap<String, String>();
            params.put("Customer", Utility.userId);// customer id
            params.put("DeliverySlot", selected_SlotId);
            params.put("CustomerAddress", Utility.profileResponse.data.Areaid);
            params.put("DeliveryDate", selected_Date);
            params.put("productdetails", cartarrayData.toString());

            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Content-Type", "application/x-www-form-urlencoded");
            return params;
        }
    };
    AppController.getInstance().getRequestQueue().getCache().remove(Constant.VERIFY_MY_ORDER);
    AppController.getInstance().addToRequestQueue(sr);
}

Comments

0

First create or if you already have class

class Data{
    String name;
    String price;

    getters & setters

    create constuctore with name & price 
}

Declared one list & set data

List<Data> list = new ArrayList<>();
list.add(new Data("Samsung", "10"));
list.add(new Data("Samsung", "20"));

Create map of your data & set data to it pass this map to constructor of Asynch

HashMap<String, String> parameters = new HashMap<>();
foreach(Data d : list){
   parameters.put("name", d.getName());
   parameters.put("price",d.getPrice() );
}

In Asynch Task class

 HashMap<String, String> parameters


 public SendProductDetailsToServerAsync(HashMap<String, String>  _parameters) {
            parameters = _parameters;
        }


@Override
    protected String doInBackground(Void... params) {
        Log.e("Response from url", webUrl);
        String json = null;
        URL url = null;
        try {
            try {
                url = new URL(webUrl+"?"+getQuery(parameters, sendingParametersType));
                Log.e("Response from url", webUrl+"?"+getQuery(parameters, sendingParametersType));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e2) {
            e2.printStackTrace();
        }
        HttpURLConnection urlConnection;

        try {
            assert url != null;
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");

            if (parameters != null) {
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);
                urlConnection.setConnectTimeout(2000);
               // OutputStream os = urlConnection.getOutputStream();
                //BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                      //  os, "UTF-8"));
                //writer.write(getQuery(parameters, sendingParametersType));
               /* writer.flush();
                writer.close();*/
               // os.close();
            }

            urlConnection.connect();

            try {

                if (urlConnection.getResponseCode() == 200) {
                    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                    json = readStream(in);
                }else {
                    json = "{\"result\":\"fail\"}";
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                urlConnection.disconnect();
            }

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

        return json;
    }

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

            Log.e("Response from url", result);


        }
    }

    private String readStream(InputStream is) {
        try {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            int i = is.read();
            while (i != -1) {
                bo.write(i);
                i = is.read();
            }
            return bo.toString();
        } catch (IOException e) {
            return "";
        }
    }

    private String getQuery(HashMap<String, String> params, String typeJsonOrParams)
            throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();

        if (AppContants.JSON.equalsIgnoreCase(typeJsonOrParams)) {
            result = new StringBuilder(new JSONObject(params).toString());
        } else if (AppContants.PARAMETERS.equalsIgnoreCase(typeJsonOrParams)) {

            boolean first = true;

            for (Entry<String, String> e : params.entrySet()) {
                if (first)
                    first = false;
                else
                    result.append("&");

                result.append(URLEncoder.encode(e.getKey(), "UTF-8"));
                result.append("=");
                if (e.getValue().equalsIgnoreCase("")) {
                    result.append("");
                } else {
                    result.append(URLEncoder.encode(e.getValue(), "UTF-8"));
                }
            }
        } else {

        }

        return result.toString();
    }

Comments

0

I did using OkHttp Library

Thanks Hari Krishnan for helping me to make my code work; This is what i did; In MainActivity i wrote:

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

        String DataToSend;

        public SendProductDetailsToServerAsync(String _DataToSend) {
            DataToSend = _DataToSend;

        }

        @Override
        protected String doInBackground(Void... voids) {
          //  JSONObject jsonObject= null;
            JSONArray jsonArr = null;
            JSONObject jsonObject = new JSONObject();
            try {
             //   jsonObject = new JSONObject(DataToSend);

                jsonArr = new JSONArray(DataToSend);
                jsonObject.put("", jsonArr);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return Http.httpPost(jsonArr, "http://../android/vendor/purchasedetails.jsp", null);


        }

Then created a Http class

public class Http {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static String httpPost(JSONArray map,String url, String token) {
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(10, TimeUnit.SECONDS);
        client.setReadTimeout(10, TimeUnit.SECONDS);
        String text="";
        Request request;
        int responseCode=1234;
        try {
            JSONArray jsonArray = map;

            String json = jsonArray.toString();
            Log.e("json", json);
            RequestBody body = RequestBody.create(JSON, json);
            Log.v("body",""+body);
            if (token!=null){
                request = new Request.Builder().url(url).header("Authorization", "Token " + token).
                        header("Connection", "close").
                        post(body).
                        build();

            Log.v("request",""+request);}
            else {
                request = new Request.Builder().url(url).
                        header("Connection", "close").
                        post(body).build();
                Log.v("requestnotoken",""+request);
            }
            Response response = client.newCall(request).execute();
            text=response.body().string();
            responseCode=response.code();
            Log.e("responseode",String.valueOf(responseCode));
            Log.e("text",text);

            if(!response.isSuccessful()) {
                Log.e("HttpPostResponse", String.valueOf(responseCode));
                return "error";
            }
        }


        catch (Exception e) {
            e.printStackTrace();
            return "error_network";
        }
        return text;
    }

}

Comments

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.