Home Blog Page 66

Android Studio bottom navigation bar android – custom navigation bar

0
custom bottom navigation bar android
custom bottom navigation bar android

Hi, Guys Welcome to Proto Coders Point, In this android studio tutorial article we will build a material component i.e custom bottom navigation bar android.

Bottom Navigation bar is a material component that help user to switch between screen or pages.

Here is how our final BottomNavigationView looks

BottomNavigationView bar
custom bottom navigation bar with fab button.

Video Tutorial on Custom Navigation Bar android

So now let’s begin Implementing the same.

Custom Bottom Navigation Bar android with Fab Button at center

Step 1: Create a new Android Project

Ofcourse you need to create a new Android Project or Open your existing Android Project where you want to add Bottom Navigation View.

In your Android Studio IDE go to, File > New > New Project ( a window will open select Empty Activity Next) > Give a name & package to your Android application & Finish (Android project will get created).

Step 2: Add Required Dependencies (build.gradle app level)

In your Android IDE Project section look for Gradle Script> build.gradle (app level) open it and add below 3 dependencies under the dependencies section if they don’t exist.

dependencies {     
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'androidx.coordinatorlayout:coordinatorlayout:1.1.0'
    implementation 'com.google.android.material:material:1.3.0-alpha03'
}

Step 3: Add google maven repository and sync project

Then, you need to add android google maven url in your project repositories in build.gradle(project level) under allprojects section.

allprojects {
    repositories {
        google()
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

Step 4: Create 5 Vector Assets Icon in Drawable Folder

Then, you need 5 Vector Assets to show in each menu item of Bottom Navigation Bar. So to create it:

right click on drawable > New > Vector Assets ( a window will open select your clip Art as per your need Next ) > finish

create vector assets in android studio

Like this create 5 vector icon assets.

Step 5: Create menu in android studio

Then, you need to create a menu in android studio under

res > menu > (right click, create a new menu resource file) bottom_nav_menu.xml

and copy paste below xml code in it

bottom_nav_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/mHome"
        android:title="Home"
        android:icon="@drawable/ic_home_24"/>

    <item android:id="@+id/mSearch"
        android:title="Search"
        android:icon="@drawable/ic_search_24"/>
    <item android:id="@+id/mplaceholder"
        android:title=""
        />

    <item android:id="@+id/mPerson"
        android:title="Profile"
        android:icon="@drawable/ic_person_24"/>

    <item android:id="@+id/mSetting"
        android:title="Setting"
        android:icon="@drawable/ic_settings_24"/>


</menu>

Step 6: create 4 fragment files

then, to create frangment files under java folder right click on package name > New > Fragment > Fragment (Blank)

This will automatically create fragment xml file for you.

Have a look at my project structure, i have created 4 fragment class and 4 fragment xml.

Step 7: activity_main.xml custom bottom navigation bar android

custom bottom navigation bar android

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainActivity">
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/framecontainer"
        >

        <androidx.coordinatorlayout.widget.CoordinatorLayout
            android:id="@+id/coordinator"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <com.google.android.material.bottomappbar.BottomAppBar
                android:id="@+id/bottomappbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom">

                <com.google.android.material.bottomnavigation.BottomNavigationView
                    android:id="@+id/bottomnavigationbar"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginRight="16dp"
                    android:background="@android:color/transparent"
                    app:menu="@menu/bottom_nav_menu" />

            </com.google.android.material.bottomappbar.BottomAppBar>

            <com.google.android.material.floatingactionbutton.FloatingActionButton
                android:id="@+id/fab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_add_24"
                app:layout_anchor="@id/bottomappbar" />
        </androidx.coordinatorlayout.widget.CoordinatorLayout>
    </FrameLayout>


</RelativeLayout>

Step 8: Giving functionality to navigation menu bar

MainActivity.java

package com.example.customnavigationbar;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.os.Bundle;
import android.view.MenuItem;

import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {

    BottomNavigationView bottomNavigationView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomnavigationbar);

        bottomNavigationView.setBackground(null);

        bottomNavigationView.getMenu().getItem(2).setEnabled(false);

        getSupportFragmentManager().beginTransaction().replace(R.id.framecontainer,new FragmentHome()).commit();

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                Fragment temp = null;

                switch (item.getItemId())
                {
                    case R.id.mHome : temp = new FragmentHome();
                                     break;
                    case R.id.mSearch : temp = new FragmentSearch();
                        break;

                    case R.id.mPerson : temp = new Fragment_Profile();
                    break;

                    case R.id.mSetting : temp = new FragmentSetting();


                }

                getSupportFragmentManager().beginTransaction().replace(R.id.framecontainer,temp).commit();
                return true;
            }
        });
    }
}

Flutter Drop Down Menu List – Drop Down In Flutter

0
drop down in flutter

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will learn How to implement drop down list in flutter.

A Dropdown in Flutter helps app user to select an item from a drop-down menu item. This widget will show the selected item on drop-down button and icon to indicate user it has a list of item to select.

A Flutter Drop Down Button is a generic type flutter widget which means you can pass any datatype as per your requirement, In flutter drop down menu list item string are been used most of the time.

Video Tutorial

Drop Down in flutter

How to implement a drop-down list in flutter?

Create a list of items to show them in Drop down spinner in flutter

Snippet Code

The Flutter DropDownButton contain several properties that you can use to create a customized dropdown list.

Here i above snippet code screenshot, i am using only 4 properties

  • value: A selected value from the drop-down will be shown in the drop-down button.
  • icon: to show a drop icon next to the button.
  • onChanged: when the user selects an option from the drop-down, the value on dropdownbutton changed.
  • items: where you need to pass your list of items that you want to show in DropDownMenuItem.

Then, I have used a map function that simply iterates to a list of items (items – Array list), so the map function in the first iteration will set item[0] to the drop-down, then in the second iteration, the second item will be set and so on up to the end of the array string.

Complete source code of Drop Down Button

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  String dropdownvalue = 'Apple';

  var items =  ['Apple','Banana','Grapes','Orange','watermelon','Pineapple'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("DropDownList Example"),
      ),
      body: Container(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              DropdownButton(
                value: dropdownvalue,

                  icon: Icon(Icons.keyboard_arrow_down),

                  items:items.map((String items) {
                       return DropdownMenuItem(
                           value: items,
                           child: Text(items)
                       );
                  }
                  ).toList(),

                onChanged: (String newValue){
                  setState(() {
                    dropdownvalue = newValue;
                  });
                },

              ),
            ],
          ),
        ),
      ),
    );
  }
}

Recommended Article

Flutter Web – Add Hover effect in flutter dropdown

flutter array array in flutter

Android Floating Action Button Animation – Expandable Fab Menu Example

0
android floating action button animation menu example
android floating action button animation menu example

Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial Article, we will learn How to Implement the Floating action button with an animation pop-up menu example.

What is Floating Action Button ?

The floating action button is a speical and different as compared to normal button. They are in circle or round button in android that will be floating above the UI. This Floating Button is known as primary action used by users to perform main task.

For Example: Using Floating Button a user can perform action like adding a new item to an existing list.

So in this article, we will learn how to implement Floating Action Button in android with menu pop-up animation example.

NOTE: we are going to implement this project using kotlin android language.

then let’s begin with the tutorial.

Steps for Creating Extended Floating Action Button with Animation

Step 1: Create new Project

Just Create a new Android Project in your android studio IDE

Step 2: check for material design dependencies

If you are using latest version of android studio IDE (4.1.1) then material design dependencies will automatically been added in your project while creating new project. To check that, open build.gradle(Module:app) under dependencies section check if material dependencies is there if not then add it.

// material design 

implementation 'com.google.android.material:material:1.3.0'

After adding any new dependencies, a button/text “Sync Now” will appear on the top right corner of your android Studio IDE just click on it.

Make user you are connected to Internet before hiting Sync Now button. It will download all the files of the depencencies into your project.

We need Material dependencies because FloatingActionButton library exist in it.

Step 3 : Create Vector Images Icon

Now In Drawable folder create some vector Icon Image, to display icons on fab buttons.

  • To create new vector images in the project  right-click on the drawable folder -> New -> Vector Asset.
  • A new pop window will be opened and choose any vector you want by clicking on the Clip Art button.
  • Please refer below images.
how to create vector image

click on clip art to select vector image icons.

Step 4: Create fab animation files

Here is How my animation xml file structure looks.

creating anim files android

So as you can see in above screenshot, you need to create 4 animation files.

firstly under res folder create Android Resource directory(anim), res(right click) > New > Android Resource Directory > a dialog open’s under resource type select anim.

Then, anim directory is been created, now under anim folder create 4 android resource files.

res > anim(right click) > New > Animation Resources File

from_bottom_anim.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true">

    <translate
        android:fromYDelta="100%"
        android:toYDelta="0%"
        android:duration="300"/>

    <scale android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="0.8"
        android:toYScale="0.8"/>

    <alpha
        android:fromAlpha="0"
        android:toAlpha="1"
        android:duration="800"/>

</set>

to_bottom_anim.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true">

    <translate
        android:fromYDelta="0%"
        android:toYDelta="100%"
        android:duration="300"/>

    <scale android:pivotX="50%"
        android:pivotY="50%"
        android:fromXScale="0.8"
        android:fromYScale="0.8"
        android:toXScale="0.8"
        android:toYScale="0.8"/>

    <alpha
        android:fromAlpha="1"
        android:toAlpha="0"
        android:duration="150"/>

</set>

rotate_open_anim.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true">

    <rotate
        android:fromDegrees="0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="360"
        android:duration="300"
        />
</set>

rotate_close_anim.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true">

    <rotate
        android:fromDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="0"
        android:duration="300" />

</set>

Step 5: Working with activity_main.xml

Kindly refer the comment in below xml code for easy understanding

activity with floating action button
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

    <!--This is a parent Floating Action Button-->
    <!-- When this FAB Button is been pressed/clicked the following two button will get pop-up with animation -->
    <!-- the Functionality is been done in MainActivity.java file -->
    <!-- The other two FAB button is been set to InVisible so when user click on this button those 2 will get visible-->

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/add_f"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginBottom="24dp"
        android:clickable="true"
        android:focusable="true"
        android:tint="@android:color/white"
        android:backgroundTint="#0038FF"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:srcCompat="@drawable/ic_android"
        tools:ignore="VectorDrawableCompat" />

    <!--This act a child Floating Action Button-->
    <!-- The visibility is been set to INVISIBLE -->
 
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/edit_f"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:clickable="true"
        android:visibility="invisible"
        android:focusable="true"
        android:tint="@color/white"
        app:layout_constraintBottom_toTopOf="@+id/add_f"
        app:layout_constraintEnd_toEndOf="@+id/add_f"
        app:srcCompat="@drawable/ic_edit_24" />

    <!--This act a child Floating Action Button-->
    <!-- The visibility is been set to INVISIBLE -->

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/setting_f"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:clickable="true"
        android:focusable="true"
        android:visibility="invisible"
        android:tint="@color/white"
        app:layout_constraintBottom_toTopOf="@+id/edit_f"
        app:layout_constraintEnd_toEndOf="@+id/edit_f"
        app:srcCompat="@drawable/ic_settings_24" />
</androidx.constraintlayout.widget.ConstraintLayout>

In you want to change floating action button color then you can user

android:backgroundTint="@color/white"

and you easily change floating action button icon size then use 

app:maxImageSize="45dp"

Step 6: Handling Floating Action Button Animation in MainActivity.java

package com.example.expandablefloatingactionbutton

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.Toast
import com.example.expandablefloatingactionbutton.R
import com.google.android.material.floatingactionbutton.FloatingActionButton
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

     // creating variable that handles Animations loading
    // and initializing it with animation files that we have created
    private  val rotateOpen : Animation by lazy { AnimationUtils.loadAnimation(this,R.anim.rotate_open_anim) }
    private  val rotateClose : Animation by lazy { AnimationUtils.loadAnimation(this,R.anim.rotate_close_anim) }
    private  val fromBottom: Animation by lazy { AnimationUtils.loadAnimation(this,R.anim.from_bottom_anim) }
    private  val toBottom : Animation by lazy { AnimationUtils.loadAnimation(this,R.anim.to_bottom_anim) }

   //used to check if fab menu are opened or closed
    private var closed = false


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //add fab button
        add_f.setOnClickListener {

            OnAddButtonClick()
        }
         
         //edit fab button on click
        edit_f.setOnClickListener {
            Toast.makeText(this,"Edit",Toast.LENGTH_SHORT).show();
        }

        //setting fab button on click
        setting_f.setOnClickListener {
            Toast.makeText(this,"Search",Toast.LENGTH_SHORT).show();
        }


    }

    private fun OnAddButtonClick() {

         setVisibility(closed)
         setAnimation(closed)

        closed = !closed;

    }

   // A Function used to set the Animation effect
    private fun setAnimation(closed:Boolean) {

        if(!closed){
            edit_f.startAnimation(fromBottom)
            setting_f.startAnimation(fromBottom)
            add_f.startAnimation(rotateOpen)
        }else{
            edit_f.startAnimation(toBottom)
            setting_f.startAnimation(toBottom)
            add_f.startAnimation(rotateClose)
        }
    }

    // used to set visibility to VISIBLE / INVISIBLE
    private fun setVisibility(closed:Boolean) {

        if(!closed)
        {
            edit_f.visibility = View.VISIBLE
            setting_f.visibility = View.VISIBLE
        }else{
            edit_f.visibility = View.INVISIBLE
            setting_f.visibility = View.INVISIBLE
        }

    }
}

5 Best Flutter Packages /Plugins

0
best flutter package
best flutter package

Hi Guys, Welcome to Proto Coders Point.

So you are here to know the best flutter package/plugins, That means you might be having a great and awesome cross-platform project idea in your mind using flutter? am I right? then you are in the right place to make research on the best plugins for a flutter app development.

Bro, Don’t miss this is simple yet easy-to-use and awesome flutter packages to include in your project that makes app development much faster and easier.

5 Best flutter packages/plugin

  1. GetX.
  2. Equatable.
  3. Flutter Secure Storage.
  4. path Provider.
  5. fluter share.

1. GetX Flutter

flutter getx

The GetX package in flutter is a very extra lightweight plugin & a powerful package that will help flutter developers to build apps much faster.

Using GetX we can easily switch between screens, show snackbar, show dialog and bottomsheet that too without passing any context.

Then, it combimes high performance state management, intelligent dependency injection & route management that to quickly.

Feature provided in Flutter GetX library

  1. Getx State Management
  2. GetX Route Management
  3. Dependency Management
  4. Validation & much more.
  5. GetX Storage

Snippet GetX Code

//Easy Navigation to Flutter Pages
Get.to(Page2());

// Display Snackbar messages
Get.snackbar("Hi", "message");

//Easy to display a dialog pop 
Get.defaultDialog(title: "THIS IS DIALOG BOX USING FLUTTER GET X ",middleText: "GET x made Easy");

And much more Event is easily possible using Flutter GetX.

2. Flutter Equatable

Using Equatable you can compare between objects, and thus save lots of time in writing boiler plate codes.

Equatable easily override == & hashcode with flutter equatable there is no need to generate code, you can keep your focus of writing amazing flutter application.
To learn more visit official sire here

Snippet Code Flutter Equatable Example

import 'package:equatable/equatable.dart';
class Fruits extends Equatable{

 final String FruitName;

 Fruits(this.FruitName);

  @override
  // TODO: implement props
  List<Object> get props => throw UnimplementedError();
  
}

// inside main or class
Fruits fruits1 = Fruits("Apple");
Fruits fruits2 = Fruits("Banana");
print(fruit1 == fruit2); //return false

Fruits fruits3=Fruits("Banana");

print(fruit1 == fruit2); //return true

3. Flutter Secure Storage

This Flutter storage package will work the same as SHARED PREFERENCES but in a secured form, This flutter storage plugin will store data in a secured way with AES Encryption.

A Flutter plugin to store data in secure storage:

  • Keychain is used for iOS
  • AES encryption is used for Android. AES secret key is encrypted with RSA and RSA key is stored in KeyStore.

Note : This package library will work only on Android 4.3 (API level 18) and above.

Snippet code how to use flutter secure storage

import 'package:flutter_secure_storage/flutter_secure_storage.dart';

// Create storage
final storage = new FlutterSecureStorage();

// Read value 
String value = await storage.read(key: key);

// Read all values
Map<String, String> allValues = await storage.readAll();

// Delete value 
await storage.delete(key: key);

// Delete all 
await storage.deleteAll();

// Write value 
await storage.write(key: key, value: value);

4. Flutter Path Provider

A Plugin in flutter that help you in finding most commonly used directory lication on a mobile file system.

Very useful package library to read any kind of document in device path such as TemporaryDirectory or any document.

Snippet code example on how to use flutter path provider

Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;

Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;

5. Flutter Share Plugin

flutter share plugin with example
flutter share plugin with example

So, Once your flutter project is ready to be distributed publicly, then it’s time to add-on an awesome functionality, such as share, where your app user can easily share flutter app URL with his friends & family to download your awesome flutter application.

What is Flutter Share plugin?

The flutter share plugin is very useful when the user wants to share contents from the flutter app with any of his friends via the platform share dialog box.

This plugin is wraped with ACTION_VIEW INTENT as in android and UIActivityViewController as on iOS devices.

whenever the flutter app user wants to share any contents he can just click on the share button which simply pop-up a share dialog using which he/she can easily share contents.

snippet code flutter share

//on share button pressed 
onPressed: () {
                Share.share(
                    'check out my website https://protocoderspoint.com/');
},

Here is an article flutter share plugin with example

Send user entered recyclerview edittext Array list data to database (phpmyadmin)

1
recyclerview send list of data to database

Hi Guys, Welcome to Proto Coders Point, So i my previous android tutorial blog post i have covered Android RecyclerView with EditText Example + Expense sum calculation

You can check the GIF Video below

Recycler View with calculating user entered expenses.

Sending Recyclerview Entered data/ array list to Database (phpmyadmin)

So Title itself says then in this part we gonna send our recyclerview entered data to our database i.e. phpmyadmin database.

I have also created a video tutorial on my youtube channel proto coders point on how to send arraylist to database. (Watch it now)

Recyclerview user entered – array list send to database

Ok So let’s begin,

Database Setup

My database is hosted with my website hosting protocoderspoint.com, so in my hosting i have created a new database special for this tutorial.

Create a new table in your phpmyadmin database

How a look at database, it has a table by name :
‘ExpenseTable’ which has 3 column

  • id : type int auto Increment.
  • ExpenseName : type varchar(50).
  • ExpenseAmt : type varchar(50).

command to create table in your database

CREATE TABLE `ExpenseTable` (
  `id` int(11) NOT NULL,
  `ExpenseName` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `ExpenseAmt` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

So now we are done with create the database table now let’s go with php code that helps us in getting connected with database and store the array list data into the table.

Php code – connect database – storing array list to data table

Here are 2 php files/code

  • connect.php: Help us in getting connected with our database.
  • save_expense.php: Helps us in storing/inserting data into our database.

connect.php

<?php

$conn = mysqli_connect("localhost", "Login username", "Login User password", "database Name");

if($conn)
{
  //echo "Connection Success";
}
else
{
//  echo "Connection Failed";

}

?>

The connect.php is a common php code that help in getting connected with our database, I have created connect.php file separate so that in my other php code i can simply include connect.php code that’s it, whenever i hit or call other php code where connet.php is included it automatically get connected to out database.

save_expense.php

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

include 'connect.php';

$expname = $_POST["expname"];
$expname = json_decode($expname,TRUE);

$amount = $_POST["expamt"];
$amount = json_decode($amount,TRUE);


for($i = 0; $i < count($expname); $i++){

      $sql = "INSERT INTO ExpenseTable (ExpenseName, ExpenseAmt) VALUES ('$expname[$i]','$amount[$i]')";

        mysqli_query($conn, $sql);
}

echo "DONE"

?>

Then, in above save_expense.php code i m sending list of jsonArray string from our android app using POST method.

Snippet code Explaination

$expname = $_POST[“expname”];
$expname = json_decode($expname,TRUE);

Here the PHP code is receiving ArrayList in the form of JSON ARRAY, that is been decoded using the json_decode function.

After that we are using for loop to iterate the total number of data present in the array list using count($expname) this will return a number, for example, suppose your array is [‘0’, ‘1’, ‘2’, ‘3’] then count will return 4, so the for loop will run for 4 times.
Then in for loop, we have a SQL query then will insert the data into our database using mysqli_query.

Ok so now we are done with our php script that will insert data into our database, now let’s go to android coding.

Android Coding –

Recyclerview EditText Entered data store in an array and send to database

android project structure

Have a look at my android project structure for easy understanding of the android tutorial on Recyclerview with editText Field.

android recyclerview

Check out this tutorial article “Android RecyclerView with EditText Example + Expense sum calculation” to know the UI and the calculation part and how i store user entered data in arraylist.

Android Volley library is been used to send data from android to php

build.gradle (module: app) 
under dependencies section add the volley library.
implementation 'com.android.volley:volley:1.1.0'

itemdatamodel.java

Our DataModel class holder 2 kinds of datatype i.e integer and a string.
integer to hold Expense Id and String that holds ExpenseName.

package com.example.recyclerview_image_pick.datamodel;

public class ItemDatamodel {

    int ExpenseId;
    String ExpenseName;

    public ItemDatamodel(int expenseId, String expenseName) {
        ExpenseId = expenseId;
        ExpenseName = expenseName;
    }

    public int getExpenseId() {
        return ExpenseId;
    }

    public String getExpenseName() {
        return ExpenseName;
    }
}

MainActivity.java

Here i have created static data, and sending it to our Adapter to display the data in our android recyclerview.

package com.example.recyclerview_image_pick;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;

import com.example.recyclerview_image_pick.Adapter.Adapter;
import com.example.recyclerview_image_pick.datamodel.ItemDatamodel;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static ArrayList<ItemDatamodel> data;
    ItemDatamodel itemDatamodel;
    // list of Expensesname
    String[] Expensesname = {"Rent","Coffee","Lunch","Dinner","Transport","Other"};

    private static RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    private static RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view_expenses);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        data = new ArrayList<>();

        // generate ArrayList and store in data model
        for(int i =0;i<Expensesname.length;i++){
            itemDatamodel = new ItemDatamodel(
                    i,
                    Expensesname[i]
            );
            data.add(itemDatamodel);
        }

       // call Adapter class by passing ArrayList data
        adapter = new Adapter(data);
        // set adapter to recyclerview
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
}

activity_main.xml

android recyclerview with edittext
<?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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_weight="0.9"
        android:id="@+id/my_recycler_view_expenses"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical" />
    
    <LinearLayout
        android:background="#A7B4FF"
        android:padding="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Total Expenses ₹ 0.00 "
                android:textSize="20sp"
                android:textStyle="italic"
                android:id="@+id/totalExpense"
                android:layout_gravity="center"/>

            <Button
                android:id="@+id/saveexpenses"
                android:paddingLeft="60dp"
                android:paddingRight="60dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Save"/>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Adapter.java

I recommend to watch the video tutorial to understand what is going on in below android Adapter.java class.

package com.example.recyclerview_image_pick.Adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.recyclerview_image_pick.R;
import com.example.recyclerview_image_pick.datamodel.ItemDatamodel;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {

    View rootView;
    Context context;
    private ArrayList<ItemDatamodel> dataSet;
    ArrayList<String> ExpNameArray = new ArrayList<String>();
    ArrayList<String> ExpAmtArray = new ArrayList<String>();
    boolean isOnTextChanged = false;
    int ExpenseFinalTotal = 0;
    TextView textviewTotalExpense;
    Button saveExpense;
    String SubmitExpenseURL ="https://protocoderspoint.com/php/save_expense.php";
    //constructor with dataSet passed from MainActivity when Adapter is called
    public Adapter(ArrayList<ItemDatamodel> dataSet) {
        this.dataSet = dataSet;
    }

    //Recyclerview ViewHolder
    public static class MyViewHolder extends RecyclerView.ViewHolder {
        TextView expensesName;
        EditText expHeld;
        Button imageButton;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            // finding view by view id.
            expensesName = (TextView) itemView.findViewById(R.id.textViewExpName);
            expHeld = (EditText) itemView.findViewById(R.id.ExpHeld);
            imageButton = (Button) itemView.findViewById(R.id.ExpBimageSelect);
        }
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        // Initialize view for recyclerview
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_prod_list, parent, false);

        context = parent.getContext();
        rootView = ((Activity) context).getWindow().getDecorView().findViewById(android.R.id.content);

        textviewTotalExpense = (TextView) rootView.findViewById(R.id.totalExpense);
        saveExpense =(Button)rootView.findViewById(R.id.saveexpenses);
        //attach view to MyViewHolder
        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

        //initialize the view with a view holder
        TextView expensesName = holder.expensesName;
        EditText expHeld = holder.expHeld;
        Button imageButton = holder.imageButton;
        int id = dataSet.get(position).getExpenseId();

        expensesName.setText(dataSet.get(position).getExpenseName());

        expHeld.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                isOnTextChanged = true;
            }

            @Override
            public void afterTextChanged(Editable editable) {

                if(isOnTextChanged){
                    isOnTextChanged = false;

                    try{

                        ExpenseFinalTotal = 0;

                        for (int i = 0;i<=id;i++){
                            if(i!=id){
                                ExpNameArray.add("0");
                                ExpAmtArray.add("0");
                            }else{
                                ExpAmtArray.add("0");
                                ExpNameArray.add("0");
                                ExpNameArray.set(id,dataSet.get(id).getExpenseName());
                                ExpAmtArray.set(id,editable.toString());
                            }
                        }
                        Log.d("ExpAmt",ExpAmtArray.toString());
                        Log.d("ExpName",ExpNameArray.toString());

                        for(int i = 0;i<=ExpAmtArray.size()-1;i++){
                            int tempTotalExpense = Integer.parseInt(ExpAmtArray.get(i));
                            ExpenseFinalTotal = ExpenseFinalTotal +tempTotalExpense;
                        }

                        textviewTotalExpense.setText("Total Expense : " +String.valueOf(ExpenseFinalTotal));
                    }catch (NumberFormatException e)
                    {
                        // catch is used because, when used enter value in editText and remove the value it
                        // it will trigger NumberFormatException, so to prevent it and remove data value from array ExpAmtArray
                        //then
                        // re-perform loop total expense calculation and display the total.

                        ExpenseFinalTotal = 0;
                        for (int i = 0; i <= id; i++) {
                            Log.d("TimesRemoved", " : " + i);

                            if (i == id) {
                                ExpNameArray.set(id,"0");
                                ExpAmtArray.set(id,"0");

                            }

                        }
                        Log.d("ExpAmt",ExpAmtArray.toString());
                        Log.d("ExpName",ExpNameArray.toString());

                        for(int i = 0;i<=ExpAmtArray.size()-1;i++){
                            int tempTotalExpense = Integer.parseInt(ExpAmtArray.get(i));
                            ExpenseFinalTotal = ExpenseFinalTotal +tempTotalExpense;
                        }

                        textviewTotalExpense.setText("Total Expense : " +String.valueOf(ExpenseFinalTotal));

                    }
                }

            }
        });


        saveExpense.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ArrayList<String> FExpenseAmtArray = new ArrayList<>();
                ArrayList<String> FExpenseNameArray = new ArrayList<>();

                if(!ExpAmtArray.isEmpty()){
                    for(int i =0 ; i<ExpAmtArray.size();i++){
                        if(!ExpAmtArray.get(i).equals("0") && !ExpAmtArray.get(i).equals("")){
                            FExpenseAmtArray.add(ExpAmtArray.get(i));
                            FExpenseNameArray.add(ExpNameArray.get(i));
                        }
                    }

                }

                Log.d("ArrayExpName",FExpenseNameArray.toString());
                Log.d("ArrayExpAmt",FExpenseAmtArray.toString());

                JSONArray jsonArrayName = new JSONArray();
                for(String Expname : FExpenseNameArray){
                    jsonArrayName.put(Expname);
                }

                JSONArray jsonArrayExpAmt = new JSONArray();
                for(String ExpAmt : FExpenseAmtArray){
                    jsonArrayExpAmt.put(ExpAmt);
                }

                SubmitExpenseData(jsonArrayName.toString(),jsonArrayExpAmt.toString());
            }
        });


    }

    private void SubmitExpenseData(String ExpName, String ExpAmt)
    {
        StringRequest stringRequest = new StringRequest(Request.Method.POST,SubmitExpenseURL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //we get the successful in String response
                        Log.e("response", response);


                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("sellresponseerror", ""+error.toString());


            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();

                params.put("expname", ExpName);
                params.put("expamt", ExpAmt);

                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest);
    }



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

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }


}

card_prod_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:tag="cards main container">

    <androidx.cardview.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        card_view:cardBackgroundColor="#ffffff"
        card_view:cardUseCompatPadding="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="horizontal"
            android:weightSum="2">

            <TextView
                android:id="@+id/textViewExpName"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center"
                android:layout_weight="1"
                android:paddingLeft="5dp"
                android:text="Product"
                android:textStyle="italic|bold"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textColor="#000000"
                android:textSize="16sp" />

            <EditText
                android:id="@+id/ExpHeld"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:backgroundTint="#000000"
                android:gravity="center"
                android:hint="Value"
                android:inputType="number"
                android:textColor="#000000"
                android:textColorHint="#989898"
                android:textSize="14sp" />


            <Button
                android:id="@+id/ExpBimageSelect"
                android:layout_width="0dp"
                android:visibility="gone"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Select Image"
                android:textSize="6dp" />

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>

Network Security Config

So as we are making internet call to send data to our database, we need to specify which domain or IP we are using to send/receive data, so for that, you need to create a networksecurityconfig.xml file in res>xml>

create a directory “XML” inside res then create an XML resource file networksecurityconfig.xml under that directory and copy-paste the below code.

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">protocoderspoint.com</domain>  // Here replace with your domain/IP

    </domain-config>
</network-security-config>

Then go to your AndroidManifest.xml and add the network SecurityConfig file under <application> tag

 <application
        android:networkSecurityConfig="@xml/network_conf"
        android:usesCleartextTraffic="true"

/>

Android RecyclerView with EditText Example + Expense sum calculation

2
RecyclerView with EditText Example
RecyclerView with EditText Example

Hi Guys, Welcome to Proto Coders Point, In this tutorial we will build a app that has a recyclerview with a list of view items and each list item in adapter has a Expense name (TextView) and a EditText field where user can enter the expense he spent for that expense.
Check out below screenshot

android recyclerview with expenses

Android Recyclerview with edittext example

OUTPUT

Have a look at my android project structure for easy understanding of the android tutorial on Recyclerview with editText Field.

Android Project Structure

So as you can see in above project structure, i have created 2 folder one for Recyclerview Adapter and a Data model that hold our dataSet that will be displayed in androidx Recyclerview.

Java Class

  • Adapter.java: That will help to inflate view in recyclerview.
  • ItemDatamodel.java: That holded list of data’s.

XML Layout

  • activity_main.xml : Where list of data will be displayed.
  • card_prod_list.xml : Eiew that will be shown to display particular list of items.

Recyclerview android example with edittext (source code)

UI XML Source Code below

card_prod_list.xml

Cardview that get generated when list of passed from activity to recyclerview adapter
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:tag="cards main container">

    <androidx.cardview.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        card_view:cardBackgroundColor="#ffffff"
        card_view:cardUseCompatPadding="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="horizontal"
            android:weightSum="2">

            <TextView
                android:id="@+id/textViewExpName"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center"
                android:layout_weight="1"
                android:paddingLeft="5dp"
                android:text="Product"
                android:textStyle="italic|bold"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textColor="#000000"
                android:textSize="16sp" />

            <EditText
                android:id="@+id/ExpHeld"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:backgroundTint="#000000"
                android:gravity="center"
                android:hint="Value"
                android:inputType="number"
                android:textColor="#000000"
                android:textColorHint="#989898"
                android:textSize="14sp" />


            <Button
                android:id="@+id/ExpBimageSelect"
                android:layout_width="0dp"
                android:visibility="gone"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Select Image"
                android:textSize="6dp" />
        </LinearLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>

activity_main.xml

This XML design simple has a recyclerview widget where all the generated list of data will get displayed.

recycler view acitivity main
<?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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_weight="0.9"
        android:id="@+id/my_recycler_view_expenses"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical" />



    <LinearLayout
        android:background="#A7B4FF"
        android:padding="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Total Expenses ₹ 0.00 "
                android:textSize="20sp"
                android:textStyle="italic"
                android:id="@+id/totalExpense"
                android:layout_gravity="center"/>

            <Button
                android:id="@+id/submitexpenses"
                android:paddingLeft="60dp"
                android:paddingRight="60dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Save"/>
        </LinearLayout>

    </LinearLayout>

</LinearLayout>

that all in xml layout you need to add. now let’s jump to java source : android recyclerview adapter and datamodel.

Java source : android recyclerview adapter and datamodel.

ItemDatamodel.java

Our DataModel class holder 2 kinds of datatype i.e integer and a string.
interger to hold Expense Id and String that holds ExpenseName.

package com.example.recyclerview_image_pick.datamodel;

public class ItemDatamodel {

    int ExpenseId;
    String ExpenseName;

    public ItemDatamodel(int expenseId, String expenseName) {
        ExpenseId = expenseId;
        ExpenseName = expenseName;
    }

    public int getExpenseId() {
        return ExpenseId;
    }

    public String getExpenseName() {
        return ExpenseName;
    }
}

Adapter.java

Check out the comment in code to under the Android Recyclerview Adapter code.

package com.example.recyclerview_image_pick.Adapter;

import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.recyclerview_image_pick.R;
import com.example.recyclerview_image_pick.datamodel.ItemDatamodel;

import java.util.ArrayList;

public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {


    View rootView;

    Context context;

    private ArrayList<ItemDatamodel> dataSet;

    // Usered Entered Expense amt will be stored in ExpAmtArray
    ArrayList<String> ExpAmtArray = new ArrayList<String>();

    boolean isOnTextChanged = false;
    int ExpenseFinalTotal = 0;
    TextView textviewTotalExpense;

    //constructor with dataSet passed from MainActivity when Adapter is called
    public Adapter(ArrayList<ItemDatamodel> dataSet) {
        this.dataSet = dataSet;
    }

    //Recyclerview ViewHolder
    public static class MyViewHolder extends RecyclerView.ViewHolder {
        TextView expensesName;
        EditText expHeld;
        Button imageButton;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            // finding view by view id.
            expensesName = (TextView) itemView.findViewById(R.id.textViewExpName);
            expHeld = (EditText) itemView.findViewById(R.id.ExpHeld);
            imageButton = (Button) itemView.findViewById(R.id.ExpBimageSelect);
        }
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        // Initialize view for recyclerview
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_prod_list, parent, false);

        context = parent.getContext();
        rootView = ((Activity) context).getWindow().getDecorView().findViewById(android.R.id.content);

        textviewTotalExpense = (TextView) rootView.findViewById(R.id.totalExpense);
        //attach view to MyViewHolder
        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

        //initialize the view with view holder
        TextView expensesName = holder.expensesName;
        EditText expHeld = holder.expHeld;
        Button imageButton = holder.imageButton;

        expensesName.setText(dataSet.get(position).getExpenseName());

        // EditText with TextWatcher Listens each time when user enter value in edittext in recyclerview
        expHeld.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //using this boolean because sometime when user enter value in edittxt
                //afterTextchanged runs twice to prevent this, i m making use of this variable.
                isOnTextChanged = true;
            }

            @Override
            public void afterTextChanged(Editable editable) {
                //so this will trigger each time user enter value in editText box
                ExpenseFinalTotal = 0;
                if (isOnTextChanged) {
                    isOnTextChanged = false;

                    try {
                        ExpenseFinalTotal = 0;


                        for (int i = 0; i <= position; i++) {

                            int inposition1 = position;
                            if (i != position) {
                                //store 0  where user select position in not equal/
                                ExpAmtArray.add("0");

                            }else {

                                // store user entered value to Array list (ExpAmtArray) at particular position
                                ExpAmtArray.add("0");
                                ExpAmtArray.set(inposition1,editable.toString());

                                break;
                            }

                        }

                        // for statement to loop to the array, to calculate the Expense total.
                        for (int i = 0; i <= ExpAmtArray.size() - 1; i++) {

                            int tempTotalExpenase = Integer.parseInt(ExpAmtArray.get(i));
                            ExpenseFinalTotal  = ExpenseFinalTotal + tempTotalExpenase;

                        }

                      textviewTotalExpense.setText("Total Expenses: ₹ "+String.valueOf(ExpenseFinalTotal));
                    }catch (NumberFormatException e)
                    {
                        // catch is used because, when used enter value in editText and remove the value it
                        // it will trigger NumberFormatException, so to prevent it and remove data value from array ExpAmtArray
                        //then
                        // re-perform loop total expense calculation and display the total.

                        ExpenseFinalTotal = 0;
                        for (int i = 0; i <= position; i++) {
                            Log.d("TimesRemoved", " : " + i);
                            int newposition = position;
                            if (i == newposition) {
                                ExpAmtArray.set(newposition,"0");

                            }

                        }
                        for (int i = 0; i <= ExpAmtArray.size() - 1; i++) {

                            int tempTotalExpenase = Integer.parseInt(ExpAmtArray.get(i));
                            ExpenseFinalTotal  = ExpenseFinalTotal + tempTotalExpenase;

                        }
                       textviewTotalExpense.setText("Total Expenses: ₹ "+String.valueOf(ExpenseFinalTotal));
                    }

                }
            }
        });
    }

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

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }


}

MainActivity.java

package com.example.recyclerview_image_pick;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;

import com.example.recyclerview_image_pick.Adapter.Adapter;
import com.example.recyclerview_image_pick.datamodel.ItemDatamodel;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static ArrayList<ItemDatamodel> data;
    ItemDatamodel itemDatamodel;
    // list of Expensesname
    String[] Expensesname = {"Rent","Coffee","Lunch","Dinner","Transport","Other"};

    private static RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    private static RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view_expenses);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        
        data = new ArrayList<>();
        
        // generate ArrayList and store in data model
        for(int i =0;i<Expensesname.length;i++){
            itemDatamodel = new ItemDatamodel(
                    i,
                    Expensesname[i]
            );
            data.add(itemDatamodel);
        }

       // call Adapter class by passing ArrayList data
        adapter = new Adapter(data);
        // set adapter to recyclerview
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
}

#video Tutorial will be uploaded soon on my youtube channel.

Similar Tutorial

How to add search filter to recyclerview adapter.

Firebase UI RecyclerView Adapter

How to show grid view in recyclerview android