Passing String array to POST URL java android

Viewed 39

I am creating an app with multi-selections. on button click the choices ticked should be send to the server and inserted each in a row.How can I pass the selections to my server? screenshot1 screenshot2 screenshot2

private void add_scouting
            (final String pest,final String chem,final String remarks) {
        // Tag used to cancel the request
        String tag_string_collect = "Add_scouting";

        pDialog.setMessage("Add Scouting ...");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_ADDPLANTING, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Scouting Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    if (!error) {

                        Toast.makeText(planting.this, "Scouting Added successfully.", Toast.LENGTH_LONG).show();


                    } else {

                        // Error occurred in registration. Get the error
                        // message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(planting.this,
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "AddPlanting Error: " + error.getMessage());
//                Toast.makeText(getContext(),
//                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                Map<String, String> params = new HashMap<String, String>();

                params.put("bcode",pest);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_collect);
    }
    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
1 Answers

1) Implement this dependencies in app's build.gradle

implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'

2) Create APIClient.java class and put this code into that class:

import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class APIClient {
    private static Retrofit retrofit = null;

    public static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .readTimeout(180, TimeUnit.SECONDS)
            .writeTimeout(180,TimeUnit.SECONDS)
            .connectTimeout(180, TimeUnit.SECONDS)
            .build();

    public static Retrofit getClient() {
        return new Retrofit.Builder()
                .baseUrl("http://BASE_URL_HERE/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();
    }
}

BASE URL is your server host name. For example you have apis. All apis start with http://localhost:8080/api/. This will be BASE URL. Because all api's starts with that url.

3) Create ApiInterface.java interface file and insert this code into that file:

import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;

public interface ApiInterface {
    @POST("insert-multiple-selection")
    Call<YOUR_RESPONSE_CLASS> acceptOrder(@Body ArrayList<String> selections);
}

4) Add this code to your button onclick method:

ApiInterface apiInterface= APIClient.getClient().create(ApiInterface.class);
        ArrayList<String> selections=new ArrayList<>();
        // To add value
        selections.add("YOUR_VALUE_1");
        selections.add("YOUR_VALUE_2");
        selections.add("YOUR_VALUE_3");
        // To remove value
        selections.remove("YOUR_VALUE_1");
        Call<YOUR_RESPONSE_CLASS> call=apiInterface.sendSelections(selections);
        call.enqueue(new Callback<YOUR_RESPONSE_CLASS>() {
            @Override
            public void onResponse(Call<YOUR_RESPONSE_CLASS> call, Response<YOUR_RESPONSE_CLASS> response) {
         

               if(response.isSuccessful()){
                   Toast.makeText(context, "Successfully sent!", Toast.LENGTH_SHORT).show();
                } else {
                   Toast.makeText(context, "Error code: "+response.code(), Toast.LENGTH_SHORT).show();
               }
                
            }

            @Override
            public void onFailure(Call<YOUR_RESPONSE_CLASS> call, Throwable t) {
              Toast.makeText(context, t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
Related