abc

Share This blog with your friends, so that we can improve more & more . our aim is to easy & simple way of learning.

12/22/2021

How to insert and view Firebase database in android?

Firebase gives real-time database which as lightweight, fast access. multiple devices can communicate with using same database for example eCommerce database.

Let's take an example of adding employee details and view it as list.
for this we have taken three edit-text and two button which design as follows,

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/idEdtEmployeeName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_margin="10dp"
        android:hint="Enter Employee Name"
        android:importantForAutofill="no"
        android:inputType="textPersonName" />
    <EditText
        android:id="@+id/idEdtEmployeePhoneNumber"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idEdtEmployeeName"
        android:layout_margin="10dp"
        android:hint="Enter employee phone number"
        android:importantForAutofill="no"
        android:inputType="phone" />
    <EditText
        android:id="@+id/idEdtEmployeeAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idEdtEmployeePhoneNumber"
        android:layout_margin="10dp"
        android:hint="Enter employee address"
        android:inputType="textPostalAddress" />

    <Button
        android:id="@+id/idBtnSendData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idEdtEmployeeAddress"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="10dp"
        android:layout_marginBottom="10dp"
        android:text="Add employee details"
        android:textAllCaps="false" />

    <Button
        android:id="@+id/BtnviewData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idBtnSendData"
        android:layout_marginStart="10dp"
        android:layout_marginTop="72dp"
        android:layout_marginEnd="10dp"
        android:layout_marginBottom="10dp"
        android:text="View employee details"
        android:textAllCaps="false" />

    <ListView
        android:id ="@+id/listviewalldata"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/BtnviewData"
        android:layout_marginStart="10dp"
        android:layout_marginTop="72dp"
        android:layout_marginEnd="10dp"
        android:layout_marginBottom="10dp"
        />


</RelativeLayout>


then write class for employee information,

public class EmployeeInfo {

    private String employeeName;
    private String employeeContactNumber;
    private String employeeAddress;
    // Firebase Realtime Database.
    public EmployeeInfo() {

    }
    // for all our variables.
    public String getEmployeeName() {
        return employeeName;
    }
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
    public String getEmployeeContactNumber() {
        return employeeContactNumber;
    }
    public void setEmployeeContactNumber(String employeeContactNumber) {
        this.employeeContactNumber = employeeContactNumber;
    }
    public String getEmployeeAddress() {
        return employeeAddress;
    }
    public void setEmployeeAddress(String employeeAddress) {
        this.employeeAddress = employeeAddress;
    }
}

-- after writing above class go to mainactivity and declare variables and design items

private EditText employeeNameEdt, employeePhoneEdt, employeeAddressEdt;
    private Button sendDatabtn,viewdatabutn;
    FirebaseDatabase firebaseDatabase;  // Firebase Database
    DatabaseReference databaseReference;  // Reference for Firebase.
    EmployeeInfo employeeInfo;    // our object class
    private ListView employeelistview;
    ArrayList<String> employeeArrayList;
employeeNameEdt = findViewById(R.id.idEdtEmployeeName);
employeePhoneEdt = findViewById(R.id.idEdtEmployeePhoneNumber);
employeeAddressEdt = findViewById(R.id.idEdtEmployeeAddress);
firebaseDatabase = FirebaseDatabase.getInstance();// instance of our FIrebase database.
databaseReference = firebaseDatabase.getReference("EmployeeInfo");
employeeInfo = new EmployeeInfo();        // class variable.
sendDatabtn = findViewById(R.id.idBtnSendData);
viewdatabutn = findViewById(R.id.BtnviewData);

employeelistview = findViewById(R.id.listviewalldata);


and use onclicklistner for both button .

in above database can be initialised as , 

 firebaseDatabase = FirebaseDatabase.getInstance();// instance of our FIrebase database.
 databaseReference = firebaseDatabase.getReference("EmployeeInfo");

now before writing final code of mainactivity.xml do the following for connection with firebase.
step1) open firebase console, download google-services.json file from project setting and copy to android-studio--project--app folder
step2) from menu -- tools--firebase-- find realtime database.
step3) click on add dependcies, and then click on connect to firebase, it will start building, it may shows error while connecting, for this come to mainactivity.java file and paste following final code.

public class MainActivity extends AppCompatActivity {
    private EditText employeeNameEdt, employeePhoneEdt, employeeAddressEdt;
    private Button sendDatabtn,viewdatabutn;
    FirebaseDatabase firebaseDatabase;  // Firebase Database
    DatabaseReference databaseReference;  // Reference for Firebase.
    EmployeeInfo employeeInfo;    // our object class
    private ListView employeelistview;
    ArrayList<String> employeeArrayList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        employeeNameEdt = findViewById(R.id.idEdtEmployeeName);
        employeePhoneEdt = findViewById(R.id.idEdtEmployeePhoneNumber);
        employeeAddressEdt = findViewById(R.id.idEdtEmployeeAddress);
        firebaseDatabase = FirebaseDatabase.getInstance();// instance of our FIrebase database.
        databaseReference = firebaseDatabase.getReference("EmployeeInfo");
        employeeInfo = new EmployeeInfo();        // class variable.
        sendDatabtn = findViewById(R.id.idBtnSendData);
        viewdatabutn = findViewById(R.id.BtnviewData);

        employeelistview = findViewById(R.id.listviewalldata);
        try {
            employeeArrayList = new ArrayList<>();
            initializeListView();
        }
        catch (Exception e)
        {
            Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_SHORT).show();
        }
        sendDatabtn.setOnClickListener(v -> {
            String name = employeeNameEdt.getText().toString();
            String phone = employeePhoneEdt.getText().toString();
            String address = employeeAddressEdt.getText().toString();
            if (TextUtils.isEmpty(name) && TextUtils.isEmpty(phone) && TextUtils.isEmpty(address)) {
                Toast.makeText(MainActivity.this, "Please add some data.", Toast.LENGTH_SHORT).show();
            }
            else {
                // else call the method to add
                addDatatoFirebase(name, phone, address);
            }
        });
        viewdatabutn.setOnClickListener(v ->
                initializeListView()
        );


    }

    private void initializeListView() {
        String[] emptylist = new String[] {};
        final List<String> fruits_list = new ArrayList<>(Arrays.asList(emptylist));
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>
                (this, android.R.layout.simple_list_item_1, fruits_list);

        ValueEventListener eventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    String address = ds.child("employeeAddress").getValue(String.class);
                    String name = ds.child("employeeName").getValue(String.class);
                    fruits_list.add(address + " / " + name);
                    arrayAdapter.notifyDataSetChanged();
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {}
        };
        databaseReference.addListenerForSingleValueEvent(eventListener);
        employeelistview.setAdapter(arrayAdapter);
    }



    private void addDatatoFirebase(String name, String phone, String address) {
        try {
            employeeInfo.setEmployeeName(name);
            employeeInfo.setEmployeeContactNumber(phone);
            employeeInfo.setEmployeeAddress(address);
            databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
                String userId = databaseReference.push().getKey();
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    // in case database so much , uncomment below line, shortcut way to delete all data
                    //databaseReference.getRef().removeValue();
                    databaseReference.child(userId).setValue(employeeInfo);
                    Toast.makeText(MainActivity.this, "data added", Toast.LENGTH_SHORT).show();
                    initializeListView();
                }
                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                    Toast.makeText(MainActivity.this, "Fail to add data " + error, Toast.LENGTH_SHORT).show();
                }
            });
        }
        catch(Exception e)
        {
            Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_SHORT).show();
        }
    }
}

and also add dependencies of internet access to manifest file.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Now come again and click on Firebase connect from assistant box of android studio.
it will connect successfully,

Finally it's time to test in real device.

Test on your device and if you success in output please type "perfect" word in comment box.

An Introduction to the Laravel Framework: What It Is and Why You Should Use It

  If you're a PHP developer looking for a modern, efficient, and powerful framework to build web applications, look no further than Lara...