DEV Community

SHREEHITH REDDY
SHREEHITH REDDY

Posted on

expense tracker with tab layout (java & XML)

main.xml

Main (XML)

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="fill" />

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/tabLayout"/>

    <FrameLayout
        android:id="@+id/fragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Enter fullscreen mode Exit fullscreen mode

main.java

Main.java

package com.example.expensetracker;

import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;

public class MainActivity extends AppCompatActivity {

    private ViewPager viewPager;
    private TabLayout tabLayout;

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

        viewPager = findViewById(R.id.viewPager);
        tabLayout = findViewById(R.id.tabLayout);

        TabAdapter adapter = new TabAdapter(getSupportFragmentManager());
        adapter.addFragment(new IncomeFragment(), "Income");
        adapter.addFragment(new ExpenseAdapter(), "Expenses");

        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
    }
}
Enter fullscreen mode Exit fullscreen mode

tabactivity.java

TabActivity.java

package com.example.expensetracker;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;

public class TabAdapter extends FragmentPagerAdapter {

    private final List<Fragment> fragmentList = new ArrayList<>();
    private final List<String> fragmentTitleList = new ArrayList<>();

    public TabAdapter(FragmentManager fm) {
        super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
    }

    public void addFragment(Fragment fragment, String title) {
        fragmentList.add(fragment);
        fragmentTitleList.add(title);
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

    @Override
    public int getCount() {
        return fragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return fragmentTitleList.get(position);
    }
}
Enter fullscreen mode Exit fullscreen mode

incomefragment.java

IncomeFragment.java

ckage com.example.expensetracker;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

public class IncomeFragment extends Fragment {
    private EditText incomeInput;
    private Button submitButton;
    private int totalIncome = 0;
    private int totalExpenses = 0;  // To store expenses received from ExpensesFragment

    public IncomeFragment() {
        super(R.layout.activity_income_fragment);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        incomeInput = view.findViewById(R.id.incomeInput);
        submitButton = view.findViewById(R.id.submitButton);

        // Receiving expenses from ExpensesFragment
        if (getArguments() != null) {
            totalExpenses = getArguments().getInt("totalExpenses", 0);
        }

        submitButton.setOnClickListener(v -> {
            String incomeText = incomeInput.getText().toString();
            if (!incomeText.isEmpty()) {
                totalIncome = Integer.parseInt(incomeText);
                Toast.makeText(getContext(), "Income: ₹" + totalIncome, Toast.LENGTH_SHORT).show();

                // Sending data to SummaryActivity
                Intent intent = new Intent(getActivity(), SummaryActivity.class);
                intent.putExtra("totalIncome", totalIncome);
                intent.putExtra("totalExpenses", totalExpenses);
                startActivity(intent);
            } else {
                Toast.makeText(getContext(), "Please enter a valid income!", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

incomefragment.xml

IncomeFragment (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="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    android:gravity="center"
    >

    <EditText
        android:id="@+id/incomeInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Income"
        android:inputType="number"/>

    <Button
        android:id="@+id/submitButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Submit"/>
</LinearLayout>
Enter fullscreen mode Exit fullscreen mode

expenseadapter.java

ExpenseAdapter.java

package com.example.expensetracker;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

public class ExpenseAdapter extends Fragment {
    private EditText rentInput, groceriesInput, billsInput, transportInput;
    private Button calculateButton;
    private int totalExpenses = 0;

    public ExpenseAdapter() {
        super(R.layout.activity_expense_adapter);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        rentInput = view.findViewById(R.id.rent);
        groceriesInput = view.findViewById(R.id.groceries);
        billsInput = view.findViewById(R.id.bills);
        transportInput = view.findViewById(R.id.transport);
        calculateButton = view.findViewById(R.id.calculateButton);

        calculateButton.setOnClickListener(v -> {
            int rent = getInputValue(rentInput);
            int groceries = getInputValue(groceriesInput);
            int bills = getInputValue(billsInput);
            int transport = getInputValue(transportInput);

            totalExpenses = rent + groceries + bills + transport;
            Toast.makeText(getContext(), "Total Expenses: ₹" + totalExpenses, Toast.LENGTH_SHORT).show();

            // Sending expenses to IncomeFragment
            Bundle bundle = new Bundle();
            bundle.putInt("totalExpenses", totalExpenses);
            IncomeFragment incomeFragment = new IncomeFragment();
            incomeFragment.setArguments(bundle);

            requireActivity().getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragmentContainer, incomeFragment)
                    .commit();
        });
    }

    private int getInputValue(EditText editText) {
        String text = editText.getText().toString();
        return text.isEmpty() ? 0 : Integer.parseInt(text);
    }
}
Enter fullscreen mode Exit fullscreen mode

expenseadapter.xml

ExpenseAdapter (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="match_parent"
    android:orientation="vertical"
    android:padding="20dp">

    <EditText
        android:id="@+id/rent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Rent"
        android:inputType="number" />

    <EditText
        android:id="@+id/groceries"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Groceries Expense"
        android:inputType="number" />

    <EditText
        android:id="@+id/bills"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Bills Expense"
        android:inputType="number" />

    <EditText
        android:id="@+id/transport"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Transport Expense"
        android:inputType="number" />

    <Button
        android:id="@+id/calculateButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Calculate Expenses"
        android:backgroundTint="@color/black"
        android:textColor="@android:color/white"
        android:layout_marginTop="20dp"/>
</LinearLayout>
Enter fullscreen mode Exit fullscreen mode

summary.java

Summary.java

package com.example.expensetracker;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class SummaryActivity extends AppCompatActivity {
    private TextView summaryText;
    private int totalIncome, totalExpenses;

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

        summaryText = findViewById(R.id.summaryText);

        // Receiving data from IncomeFragment
        Intent intent = getIntent();
        if (intent != null) {
            totalIncome = intent.getIntExtra("totalIncome", 0);
            totalExpenses = intent.getIntExtra("totalExpenses", 0);

        }



        int difference = totalIncome - totalExpenses;
        Toast.makeText(this, "Remaining Balance: ₹" + difference, Toast.LENGTH_LONG).show();

        summaryText.setText("Income: ₹" + totalIncome + "\nExpenses: ₹" + totalExpenses+"\nBalance: "+difference);
    }
}
Enter fullscreen mode Exit fullscreen mode

summary.xml

Summary (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="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:id="@+id/summaryText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Summary"
        android:textSize="18sp"
        android:textStyle="bold"/>
</LinearLayout>
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay