Android Volley JsonArrayRequest to Post ArrayList data to the server

Hi Everyone in this article, I am sharing how to post an ArrayList data to a server using volley. Android Volley JsonArrayRquest  Post data to the server. First of getting an array list of data to  JSONArray and using the volley network library to post the list data to the server on a button click post the Android Volley JsonArrayRequest to Post ArrayList data to the server.

So Let Start on this Topic send Android Volley JsonArrayRequest to Post ArrayList data to the server, and store data in the local recycler view list. Create a user form and use username and email and store form data to an ArrayList and send it to the server.

  Store Data in Locle recyclerView list and send to the server

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation "androidx.drawerlayout:drawerlayout:1.0.0"
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.android.volley:volley:1.1.0'
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

Main Java Clase Source Code

public class Partisipent_Invite extends AppCompatActivity{

    String EventId="";
    String Count;
    ArrayList<ExampleItem> mExampleList;
    private RecyclerView mRecyclerView;
    private Add_Invite mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    Button Invite_SubmitBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_partisipent__invite);
        EventId= getIntent().getStringExtra("id");
      
        TextView Count_Number =(TextView)findViewById(R.id.Count_Number);
        androidx.appcompat.app.ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("Invite Participant");
        loadData();
        buildRecyclerView();
        setInsertButton();
    }


    private void loadData() {
        SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
        Gson gson = new Gson();
        String json = sharedPreferences.getString("task list", null);
        Type type = new TypeToken<ArrayList<ExampleItem>>() {}.getType();
        mExampleList = gson.fromJson(json, type);

        if (mExampleList == null) {
            mExampleList = new ArrayList<>();
        }
    }

    private void buildRecyclerView() {
        mRecyclerView = findViewById(R.id.Invite_recyclerview);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mAdapter = new Add_Invite(this,mExampleList);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        Invite_SubmitBtn = findViewById(R.id.Invite_SubmitBtn);
        Invite_SubmitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mExampleList == null) {
                    mExampleList = new ArrayList<>();
                }else {
                    Share_Resource();
                }

            }
        });
    }


    private void setInsertButton() {
        Button buttonInsert = findViewById(R.id.Invite_AddBtn);
        buttonInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText name = findViewById(R.id.Invite_editName);
                EditText email = findViewById(R.id.Invite_editemail);
                String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
                String useremail = email.getText().toString().trim();
                String username = name.getText().toString().trim();
                if (username.equals("") || username.equals(null)) {
                    name.setError("Full name can't be empty");
                    return;

                } else if (useremail.equals("") || useremail.equals(null) || !useremail.matches(emailPattern)) {
                    email.setError("Email address can't be empty");
                    return;
                } else {
                    insertItem(username,useremail,"1234567890");
                    name.getText().clear();
                    email.getText().clear();
                }
            }
        });
    }

    private void insertItem(String name, String email,String Phone) {
        mExampleList.add(new ExampleItem(name, email,Phone));
        mAdapter.notifyItemInserted(mExampleList.size());
    }
public void Share_Resource(){
    final ProgressDialog loading = new ProgressDialog(this);
    loading.setMessage("Please Wait...");
    loading.setCanceledOnTouchOutside(false);
    loading.show();
    Gson gson = new Gson();
    String Data = null;
    JSONArray mJSONArray = null;
    try {
        mJSONArray = new JSONArray(gson.toJson(mExampleList));
        Data =mJSONArray.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    // Enter the correct url for your api service site
    RetryPolicy mRetryPolicy = new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    String finalData = Data;
    StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, ConfiURL.Invite_Partisipent+EventId,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("Response", String.valueOf(response));
                    loading.dismiss();
                    try {
                        JSONObject eventObject = new JSONObject(response);
                        String Error = eventObject.getString("httpStatus");
                        if (Error.equals("")||Error.equals(null)){

                        }else if(Error.equals("OK")) {
                            ContextThemeWrapper ctw = new ContextThemeWrapper(Partisipent_Invite.this, R.style.Theme_AlertDialog);
                            final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(ctw);
                            alertDialogBuilder.setTitle("Message");
                            alertDialogBuilder.setCancelable(false);
                            alertDialogBuilder.setMessage("Participant's has been invited successfully");
                            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    Intent intent = new Intent(Partisipent_Invite.this, EventDetails_Screen.class);
                                    startActivity(intent);
                                    overridePendingTransition(R.anim.right_slide, R.anim.right_slide_close_open);
                                    finish();
                                }
                            });
                            alertDialogBuilder.show();
                        }
                        // Parsing json
                    } catch (Exception e) {
                        Log.d("Tag", e.getMessage());

                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            loading.dismiss();
            VolleyLog.d("Error", "Error: " + error.getMessage());
            if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                ContextThemeWrapper ctw = new ContextThemeWrapper( Partisipent_Invite.this, R.style.Theme_AlertDialog);
                final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(ctw);
                alertDialogBuilder.setTitle("No connection");
                alertDialogBuilder.setMessage(" Connection time out error please try again ");
                alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });
                alertDialogBuilder.show();
            } else if (error instanceof AuthFailureError) {
                ContextThemeWrapper ctw = new ContextThemeWrapper( Partisipent_Invite.this, R.style.Theme_AlertDialog);
                final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(ctw);
                alertDialogBuilder.setTitle("Connection Error");
                alertDialogBuilder.setMessage(" Authentication failure connection error please try again ");
                alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });
                alertDialogBuilder.show();
                //TODO
            } else if (error instanceof ServerError) {
                ContextThemeWrapper ctw = new ContextThemeWrapper( Partisipent_Invite.this, R.style.Theme_AlertDialog);
                final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(ctw);
                alertDialogBuilder.setTitle("Connection Error");
                alertDialogBuilder.setMessage("Connection error please try again");
                alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });
                alertDialogBuilder.show();
                //TODO
            } else if (error instanceof NetworkError) {
                ContextThemeWrapper ctw = new ContextThemeWrapper( Partisipent_Invite.this, R.style.Theme_AlertDialog);
                final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(ctw);
                alertDialogBuilder.setTitle("Connection Error");
                alertDialogBuilder.setMessage("Network connection error please try again");
                alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });
                alertDialogBuilder.show();
                //TODO
            } else if (error instanceof ParseError) {
                ContextThemeWrapper ctw = new ContextThemeWrapper( Partisipent_Invite.this, R.style.Theme_AlertDialog);
                final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(ctw);
                alertDialogBuilder.setTitle("Something Went Wrong");
                alertDialogBuilder.setMessage("Parser error please try again");
                alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });
                alertDialogBuilder.show();
            }

        }
    })
    {
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            try {
                return finalData == null ? null : finalData.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", finalData, "utf-8");
                return null;
            }
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Authorization",Token);
            return headers;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    jsonObjectRequest.setRetryPolicy(mRetryPolicy);
    requestQueue.add(jsonObjectRequest);
}

 

Main XML file activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".Activitys.Partisipent_Invite">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="15dp"
        android:orientation="vertical">
        <TextView
            android:id="@+id/Count_Number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:textStyle="bold"
            android:visibility="gone"
            android:textAppearance="@style/body"
            android:gravity="center"
            android:text=""/>


        <EditText
            android:id="@+id/Invite_editName"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:singleLine="true"
            android:paddingLeft="15dp"
            android:layout_marginTop="10dp"
            android:hint="Full Name"
            android:background="@drawable/edit_text"
            android:inputType="text"
            android:textColor="@color/Black" />


        <EditText
            android:id="@+id/Invite_editemail"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:singleLine="true"
            android:paddingLeft="10dp"
            android:layout_marginTop="20dp"
            android:background="@drawable/edit_text"
            android:hint="Email Address"
            android:inputType="textEmailAddress"
            android:textColor="@color/Black" />


        <Button
            android:id="@+id/Invite_AddBtn"
            android:layout_width="150dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:layout_marginTop="10dp"
            android:layout_gravity="right"
            android:background="@drawable/button"
            android:text="Add More"
            android:textAppearance="?android:textAppearanceMedium"
            android:textStyle="bold"
            android:textColor="@color/White"/>
    </LinearLayout>


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/Invite_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

        <Button
            android:id="@+id/Invite_SubmitBtn"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:gravity="center"
            android:layout_marginTop="20dp"
            android:layout_gravity="right"
            android:background="@drawable/button_right"
            android:text="Submit"
            android:textAppearance="?android:textAppearanceMedium"
            android:textStyle="bold"
            android:textColor="@color/White"/>

</LinearLayout>

Create a Add_Invite Adupter  class for Recyclerview List

public class Add_Invite extends RecyclerView.Adapter<Add_Invite.ExampleViewHolder> {
    private ArrayList<ExampleItem> mExampleList;
    private Context context;
    public static final String KEY_UserEmail = "email";//database key
    public static final String KEY_registrationType= "registrationType";
    public static final String KEY_phoneNumber = "phoneNumber";
    public static final String KEY_Username="name";


    public void removeItem(int position) {
        if(mExampleList==null){

        }else {
            mExampleList.remove(position);
            // notify the item removed by position
            // to perform recycler view delete animations
            // NOTE: don't call notifyDataSetChanged()
            notifyItemRemoved(position);
        }
    }

    public Add_Invite(Context context,ArrayList<ExampleItem> exampleList) {
        mExampleList = exampleList;
        this.context = context;

    }

    @Override
    public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.invite_card, parent, false);
        ExampleViewHolder evh = new ExampleViewHolder(v);
        return evh;
    }

    @Override
    public void onBindViewHolder(final ExampleViewHolder holder, final int position) {
        ExampleItem currentItem = mExampleList.get(position);
        holder.CV.setTag(position);
        holder.mTextViewLine1.setText(currentItem.getLine1());
        holder.mTextViewLine2.setText(currentItem.getLine2());
        holder.Remove_User.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeItem(holder.getAdapterPosition());
                Toast.makeText(context,"Invitation remove ",Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public int getItemCount()
    {
        return mExampleList.size();
    }

    public class ExampleViewHolder extends RecyclerView.ViewHolder {
        public TextView mTextViewLine1;
        public TextView mTextViewLine2;
        public TextView textview_Id;
        CardView CV;
        ImageView Send_User,Remove_User;

        public ExampleViewHolder(View itemView) {
            super(itemView);
            CV =itemView.findViewById(R.id.Invite_Card);
            mTextViewLine1 = itemView.findViewById(R.id.textview_line1);
            mTextViewLine2 = itemView.findViewById(R.id.textview_line_2);
            textview_Id = itemView.findViewById(R.id.textview_Id);
            Remove_User = itemView.findViewById(R.id.Remove_User);
            Send_User = itemView.findViewById(R.id.Send_User);
            Remove_User.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });

            
        }
    }

You may also like...