How to create batch (transaction) storage in Android Firebase Database

In this android programming source code example, we are going to create batch (transaction) storage in Android Firebase Database.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to create batch (transaction) storage in Android Firebase Database.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="15dp"
    android:background="#CACACA">

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/titleinput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp">
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/title"
            android:inputType="textNoSuggestions"
            android:maxLines="1"
            android:singleLine="true" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/bodyinput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/titleinput">
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/body"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/body"
            android:inputType="textNoSuggestions"
            android:maxLines="1"
            android:singleLine="true" />
    </com.google.android.material.textfield.TextInputLayout>


    <Button
        android:id="@+id/edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:layout_below="@id/bodyinput"
        android:textColor="#ffffff"
        android:text="Edit"/>

</RelativeLayout>

MainActivity.java

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

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

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.MutableData;
import com.google.firebase.database.Query;
import com.google.firebase.database.Transaction;
import com.google.firebase.database.ValueEventListener;

public class FirebaseActivity18 extends AppCompatActivity {
    private TextInputEditText title;
    private TextInputEditText body;
    private DatabaseReference mDatabase;
    private Button edit;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firebase18);
        title = (TextInputEditText)findViewById(R.id.title);
        body = (TextInputEditText)findViewById(R.id.body);
        edit = (Button)findViewById(R.id.edit);
        mDatabase = FirebaseDatabase.getInstance().getReference().child("AndroidView");

        edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String enteredtitle = title.getText().toString();
                String enteredbody = body.getText().toString();
                editData(enteredtitle, enteredbody);
            }
        });
    }

    private void editData(final String strTitle, final String strBody){
        Query editQuery = mDatabase.orderByChild("title").equalTo(strTitle);
        editQuery.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot edtData: dataSnapshot.getChildren()){
                    final DatabaseReference databaseReference = mDatabase.child(edtData.getKey());
                    databaseReference.runTransaction(new Transaction.Handler() {
                        @NonNull
                        @Override
                        public Transaction.Result doTransaction(@NonNull MutableData mutableData) {
                            Data data = mutableData.getValue(Data.class);
                            if(data == null){
                                return Transaction.success(mutableData);
                            }
                            data.content = strBody;
                            mutableData.setValue(data);
                            return Transaction.success(mutableData);
                        }

                        @Override
                        public void onComplete(@Nullable DatabaseError databaseError, boolean b, @Nullable DataSnapshot dataSnapshot) {
                            
                        }
                    });
                }
                Toast.makeText(FirebaseActivity18.this,"Data Edited",Toast.LENGTH_LONG).show();
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(FirebaseActivity18.this,databaseError.getMessage(),Toast.LENGTH_LONG).show();
            }
        });
    }
}

Data.java

public class Data {
    public String title, content;

    public Data(){

    }

    public Data(String title, String content) {
        this.title = title;
        this.content = content;
    }

    public String getTitle() {
        return title;
    }

    public String getContent() {
        return content;
    }
}

app/build.gradle

implementation 'com.google.firebase:firebase-core:16.0.9'
implementation 'com.google.firebase:firebase-database:17.0.0'

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.