0

I'm new to android and learning it now. I'm working on an application where I was able to get response form a get request successfully. Now I want to execute a POST request with a single parameter this is what I've came up with so far:

public class BGTask extends AsyncTask<String, String, String > {

    @Override
    protected String doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        String color = "null";

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            //I want to pass the id parameter
            connection.connect();
            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();
            String line ="";
            while ((line = reader.readLine()) != null){
                buffer.append(line);
            }

            String finalJson = buffer.toString();

            JSONObject parentObject = new JSONObject(finalJson);
            int status = parentObject.getInt("status");


            if(status == 1) {
                color = parentObject.getString("bgcolor");
            }

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

            if(connection != null) {
                    connection.disconnect();
                }
                try {
                    if(reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        return color;
    }
}

The variable color is in hex code i.e #FF0089

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Mursal Khan
  • 35
  • 1
  • 9
  • use loopj or any other Network Call lib instead of AsynchTask : http://loopj.com/android-async-http/ – Bhavesh Rangani Aug 09 '17 at 12:29
  • please have a look at retrofit libraries for android : http://square.github.io/retrofit/ it does pretty much any call the a API and it's really easy to use. – JCDecary Aug 09 '17 at 12:37

1 Answers1

2

** Use volley library for GET , POST and network calls it's very simple and efficient **

First create AppController.java

public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
    public ImageLoader getImageLoader() {
        getRequestQueue();
        if (mImageLoader == null) {
            mImageLoader = new ImageLoader(this.mRequestQueue,
                    new LruBitmapCache());
        }
        return this.mImageLoader;
    }

    public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
        ConnectivityReceiver.connectivityReceiverListener = listener;
    }
} 

Second make POST request

public void Send() {
        final String First = "";
        final String Second = "";


        StringRequest stringRequest = new StringRequest(Request.Method.POST, CREATEORDER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("RESPONSE", response);

                        JSONObject jObj = null;
                        try {
                            jObj = new JSONObject(response);
                            String success = jObj.getString("success");
                            String errorMessage = jObj.getString("message");

                            if (success.equals("")) {

                                Intent intent = new Intent(SendGiftActivity.this, PayScreenActivity.class);
                                startActivity(intent);
                                finish();
                            } else {
                                Toast.makeText(SendGiftActivity.this, errorMessage, Toast.LENGTH_LONG).show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        //  Toast.makeText(SignUpActivity.this, response, Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(SendGiftActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_FIRST_PARAMETERS, First);
                params.put(KEY_SECOND_PARAMETER, Second);


                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

Include volley library

 compile 'com.android.volley:volley:1.0.0'

Don't forget to add android:name=".AppController" in application tag of manifest file