Android Custom ListView with ImageView EditText and Button Part 2

Android Custom ListView with ImageView EditText and Button Part 2

In our previous article and part 1 of this article, we learned about How to create a ListView with ImageView, EditText, TextView and two ImageButton. We also learned about how to handle ListView item clicks. In our demo app, we have a PlaceOrder button. In this article, we are going to focus on the Place Order button. Before starting below is the demo of what we are going to achieve, in this article.

Ok, For this article we are going to use the following code as a base code. If you didn't download it yet download it first.

FileDownload
ListViewEditTextButton.zipLogin to Download

Before moving ahead, we are assuming you read the first article. It is recommended to read the first article for better understanding.
In our MainActivity.java file, we have an on click listener on our Place Order Button. We are called "placeOrder()" in our button click listener. Following is the existing code for placeOrder() function.

Code

private void placeOrder()
    {
        productOrders.clear();
        for(int i=0;i<listAdapter.listProducts.size();i++)
        {
            if(listAdapter.listProducts.get(i).CartQuantity > 0)
            {
                Product products = new Product(
                        listAdapter.listProducts.get(i).ProductName
                        ,listAdapter.listProducts.get(i).ProductPrice
                        ,listAdapter.listProducts.get(i).ProductImage
                );
                products.CartQuantity = listAdapter.listProducts.get(i).CartQuantity;
                productOrders.add(products);
            }
        }
    }

Now we are going to add another simple function to display toast message. Following is the code for showMessage. Add it to MainActivity.java file. Import required class.

Code

public void showMessage(String message)
{
    Toast.makeText(this,message,Toast.LENGTH_LONG).show();
}

Finally, we are going to display the number of Products selected by the end user. Following is the updated code for placeOrder() function.

Code

private void placeOrder()
{
    productOrders.clear();
    for(int i=0;i<listAdapter.listProducts.size();i++)
    {
        if(listAdapter.listProducts.get(i).CartQuantity > 0)
        {
            Product products = new Product(
                    listAdapter.listProducts.get(i).ProductName
                    ,listAdapter.listProducts.get(i).ProductPrice
                    ,listAdapter.listProducts.get(i).ProductImage
            );
            products.CartQuantity = listAdapter.listProducts.get(i).CartQuantity;
            productOrders.add(products);
        }
    }
    showMessage("Total Item: "+productOrders.size());
}

Run your app and select quantity of 2 products. Click on Place Order button.
Now we are able to see the following toast message.

Ok, so we have products selected by the end user. What is next?
Now we can share this data with another activity or we can send this data to the server so we can place user data.
Scenario 1: How to share data with other activity? Let's assume we need to share the placeOrder data with a summary activity. In our summary activity, we are going to display all the products selected by the user with selected quantity. Ok. For achieving this scenario, we need to first create a Summary activity.  In our summary activity, we are displaying, a list of the product selected by the user. Again in another ListView. In the last, we are going to display total amount need to pay for current selection. In our summary activity, we have a constraint layout as a container and ListView, and a TextView to display the total.
Following is the code for activity_summary.xml file. 

Code

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="com.vlemonn.vlog.listviewedittextbutton.Summary">

    <ListView
        android:id="@+id/lvSummary"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toTopOf="@+id/tvTotal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </ListView>

    <TextView
        android:id="@+id/tvTotal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:textSize="30sp"
        android:text="Total"
        android:gravity="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</android.support.constraint.ConstraintLayout>

Now we need to open this activity when a user clicks on the Place Order Button. Following is the function to open summary activity.

Code

public void openSummary()
{
    Intent summaryIntent = new Intent(this,Summary.class);
    startActivity(summaryIntent);
}

Now for sharing data, between our Main Activity and Summary Activity we are going to use Put Extra. For sharing data, we are going to first convert our PlaceOrder array into a string. And we are going to pass the string to our summary activity. For converting our Product Array into a String we are going to perform the following operations.
1. First, we are going to convert each product store in productOrder ArrayList into JSON object. For this step, we need to modify our Product class.
2. Next, we are going to convert each product JSON Object into a string and store it in a String ArrayList.
3. Then we are going to convert String ArrayList into a JSON Array.
4. Finally, we need to convert JSON Array into a string.
5. Now we can share this string with other activity.

For performing steps mentioned above, we need to modify our Product class and placeOrder() function. Following is the final code for Product class and placeOrder() function with openSummary() call.

Product.java Class

Code

package com.vlemonn.vlog.listviewedittextbutton;

import org.json.JSONObject;

/**
 * Created by Mayank Sanghvi on 29-11-2017.
 */

public class Product {

    String ProductName;
    Double ProductPrice;
    int    ProductImage;
    int    CartQuantity=0;

    public Product(String productName, Double productPrice, int productImage) {
        ProductName = productName;
        ProductPrice = productPrice;
        ProductImage = productImage;
    }

    public String getJsonObject() {
        JSONObject cartItems = new JSONObject();
        try
        {
            cartItems.put("ProductName", ProductName);
            cartItems.put("ProductPrice", ProductPrice);
            cartItems.put("ProductImage",ProductImage);
            cartItems.put("CartQuantity",CartQuantity);
        }
        catch (Exception e) {}
        return cartItems.toString();
    }


}

ManActivity.java class placeOrder() function. In this, we have used a new string ArrayList. Don’t forget to declare it.

Code

private void placeOrder()
{
    /* Clear Product Orders for any existing data */
    productOrders.clear();
    lOrderItems.clear();

    /* Loop through each product. If user added any 
    *  Quantity then add product in Product Order
    * */
    for(int i=0;i<listAdapter.listProducts.size();i++)
    {
        if(listAdapter.listProducts.get(i).CartQuantity > 0)
        {
            Product products = new Product(
                    listAdapter.listProducts.get(i).ProductName
                    ,listAdapter.listProducts.get(i).ProductPrice
                    ,listAdapter.listProducts.get(i).ProductImage
            );
            products.CartQuantity = listAdapter.listProducts.get(i).CartQuantity;
            productOrders.add(products);
            /* Create a JSON Object and store it in String ArrayList */
            lOrderItems.add(products.getJsonObject().toString());
        }
    }

    /* Convert String ArrayList into JSON Array */
    JSONArray jsonArray = new JSONArray(lOrderItems);
    /* Open Summary with JSONArray String */
    openSummary(jsonArray.toString());
}

To send data to Summary Activity, we will use putExtra. The final version of the Open Summary function is

Code

public void openSummary(String orderItems)
{
    Intent summaryIntent = new Intent(this,Summary.class);
    summaryIntent.putExtra("orderItems",orderItems);
    startActivity(summaryIntent);
}

In Summary Activity, let us convert the order item string into a JSON Array. Then we need to convert the JSON Array into the product ArrayList. Finally, we will use the product ArrayList in the Summary Activity ListView. Following is the code for Summary.java class

package com.vlemonn.vlog.listviewedittextbutton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

public class Summary extends AppCompatActivity {

    ListView lvSummary;
    TextView tvTotal;
    Double Total=0d;
    ArrayList<Product> productOrders = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_summary);
        lvSummary = findViewById(R.id.lvSummary);
        tvTotal = findViewById(R.id.tvTotal);
        getOrderItemData();
    }

    private void getOrderItemData() {
        Bundle extras = getIntent().getExtras();
        if(extras !=null )
        {
            String orderItems = extras.getString("orderItems",null);
            if(orderItems!=null && orderItems.length()>0)
            {
                try{
                    JSONArray jsonOrderItems = new JSONArray(orderItems);
                    for(int i=0;i<jsonOrderItems.length();i++)
                    {
                        JSONObject jsonObject = new JSONObject(jsonOrderItems.getString(i));
                        Product product = new Product(
                                jsonObject.getString("ProductName")
                                ,jsonObject.getDouble("ProductPrice")
                                ,jsonObject.getInt("ProductImage")
                        );
                        product.CartQuantity = jsonObject.getInt("CartQuantity");
                        /* Calculate Total */
                        Total = Total + (product.CartQuantity * product.ProductPrice);
                        productOrders.add(product);
                    }
                    
                    if(productOrders.size() > 0)
                    {
                        ListAdapter listAdapter = new ListAdapter(this,productOrders);
                        lvSummary.setAdapter(listAdapter);
                        tvTotal.setText("Order Total: "+Total);
                    }
                    else
                    {
                        showMessage("Empty");
                    }
                }
                catch (Exception e)
                {
                    showMessage(e.toString());
                }
            }

        }
    }

    public void showMessage(String message)
    {
        Toast.makeText(this,message,Toast.LENGTH_LONG).show();
    }
}

Finally, It’s time to execute our app. Following are the different app screens.

Note: We used the same item template for Product list view and summary list view. You may select a different template for the summary list view. 
Scenario 2: Send Data to a server. We are going to cover this scenario in the next article.

The source code is available for this article. Click on below link to download it.

FileDownload
ListViewEditTextButton Part 2.zipLogin to Download
0 Comments
Leave A Comment

Please login to post your valuable comments.

Join the newsletter

Get the latest vLemonn news first

share