Latihan Ppb: Koneksi Android Studio dengan Firebase

1. Buat project baru

2. Buka file ‘AndroidManifest.xml’ dan tambahkan kode berikut diatas <application

<uses-permission android:name="android.permission.INTERNET"/>

2. Pilih menu tools -> firebase -> realtime database

3. Buat project baru firebase dengan nama “firebaselatihan”

4. Tunggu lalu pilih connect

5. Pada android studio, lanjutkan ke langkah 2, klik “add the realtime database

6. Pergi ke firebase console

7. Kemudian ke -> build -> authentication -> get stasted -> anonymous -> enable ->save

8. kemudian ke -> build -> realtime database -> create database -> next ->

9. Pergi ke Rules, dan ubah kodenya seperti dibawah dan publish:

{
  "rules": {
    ".read": "true",  // 2023-1-24
    ".write": "true",  // 2023-1-24
  }
}

10. Pergi ke build -> storage -> get started -> Start in test mode -> next -> done

11. Kemudian ke -> Rules -> edit rules -> ubah menjadi seperti dibawah, dan Publish

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if
         true;
    }
  }
}

12. Pergi ke -> project setting -> see sdk instruction -> download google-service.json dan letakkan didalam folder app di project -> next

13. Buka file build.gradle(project:firebase) 

14. Tambahkan kode berikut dibawah dependencies, lalu syncronisasi.

  repositories {
    // Make sure that you have the following two repositories
    google()  // Google's Maven repository

    mavenCentral()  // Maven Central repository

  }

15. Sehingga keseluruhan kodenya menjadi seperti berikut:

buildscript {
    dependencies {
        classpath 'com.google.gms:google-services:4.3.14'
    }
    repositories {
        // Make sure that you have the following two repositories
        google()  // Google's Maven repository

        mavenCentral()  // Maven Central repository

    }
}// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.3.0' apply false
    id 'com.android.library' version '7.3.0' apply false
}

16. Kemudian buka file “build.gradle(Module:firebase)“, dan tambahkan kode dibawah kedalam dependencies, lalu syncronisasi

implementation platform('com.google.firebase:firebase-bom:31.1.1')

17. Lalu -> next -> continue to console -> selesai

Entry Data

18. Buat Package adaptor, api, class, dan model, caranya:

  • klik kanan “com.example.firebase” pada folder java
  • new
  • package

19. Buat empty activity dengan nama “EntryDataPegawai” dan isi dengan kode:

<?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=".CLASS.EntryDataPegawai">

    <TextView
        android:id="@+id/judule"
        android:text="Entry Data Pegawai"
        android:textSize="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <EditText
        android:id="@+id/nippegawai"
        android:hint="nip pegawai"
        android:layout_below="@+id/judule"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <EditText
        android:id="@+id/namapegawai"
        android:hint="nama pegawai"
        android:layout_below="@+id/nippegawai"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <EditText
        android:id="@+id/gajipegawai"
        android:hint="gaji pegawai"
        android:layout_below="@+id/namapegawai"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <LinearLayout
        android:layout_below="@id/gajipegawai"
        android:layout_width="match_parent"
        android:gravity="center"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/btnsave"
            android:text="save"
            android:layout_margin="4dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@+id/btnview"
            android:text="view"
            android:layout_margin="4dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>

</RelativeLayout>

20. Kemudian Buka EntryDataPegawai.java dan isi dengan kode:

package com.example.firebase.CLASS;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

import com.example.firebase.R;
import com.google.firebase.database.DatabaseReference;

public class EntryDataPegawai extends AppCompatActivity {
    
    EditText ednip,ednama,edgaji;
    Button tombolsimpan,tombolview;
    DatabaseReference dbr;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_entry_data_pegawai);

        ednip=findViewById(R.id.nippegawai);
        ednama=findViewById(R.id.namapegawai);
        edgaji=findViewById(R.id.gajipegawai);
    }
}

21. Buat class dengan nama “ModelPegawai” didalam package Model, dan isi dengan kode:

package com.example.firebase.MODEL;

public class ModelPegawai {
    String nip;
    String nama_peg;
    int gaji;
    String key;
}

22. Kemudian buat constructor dengan cara klik kanan -> generate -> constructor

23. Buat getter dan setter dengan cara klik kanan -> generate -> getter & setter

24. Sehingga sekarang “ModelPegawai.java” berisi kode berikut:

package com.example.firebase.MODEL;

public class ModelPegawai {
    String nip;
    String nama_peg;
    int gaji;
    String key;

    public String getNip() {
        return nip;
    }

    public void setNip(String nip) {
        this.nip = nip;
    }

    public String getNama_peg() {
        return nama_peg;
    }

    public void setNama_peg(String nama_peg) {
        this.nama_peg = nama_peg;
    }

    public int getGaji() {
        return gaji;
    }

    public void setGaji(int gaji) {
        this.gaji = gaji;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }
}

25. Buka EntryDataPegawai.java dan tambahkan kode:

ModelPegawai modelPegawai;

dibawah kode:

    EditText ednip,ednama,edgaji;
    Button tombolsimpan,tombolview;
    DatabaseReference dbr;

Tambahkan kode berikut:

        tombolsimpan=findViewById(R.id.btnsave);
        tombolview=findViewById(R.id.btnview);
        tombolsimpan.setOnClickListener(this);
        tombolview.setOnClickListener(this);
        modelPegawai=new ModelPegawai();
        dbr= FirebaseDatabase.getInstance().getReference().child("Pegawai");
    }

    @Override
    public void onClick(View view) {
        if(view.getId()==R.id.btnsave)
        {
            modelPegawai.setNip(ednip.getText().toString());
            modelPegawai.setNama_peg(ednama.getText().toString());
            modelPegawai.setGaji(Integer.parseInt(edgaji.getText().toString()));
            dbr.push().setValue(modelPegawai);

        }
        else
        {
            Intent intent=new Intent(view.getContext(),MainActivity.class);
            view.getContext().startActivity(intent);        }
    }

Dibawah kode:

ednip=findViewById(R.id.nippegawai);
ednama=findViewById(R.id.namapegawai);
edgaji=findViewById(R.id.gajipegawai);

26. Coba Input data dan lihat di realtime database firebase datanya sudah ada atau belum, jika sudah bearti sudah berhasil.

Tampilkan Data

27. Taruh MainActivity.java kedalam package class

28. Kemudian buat layout resource file dengan nama format_pegawai dan isi dengan kode:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:padding="5dp"
    android:layout_height="wrap_content">

    <androidx.cardview.widget.CardView
    android:id="@+id/cardview_pagawai"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:layout_width="match_parent"
            android:background="@color/purple_200"
            android:layout_height="wrap_content">
            <TextView
                android:id="@+id/nippegawai"
                android:hint="nip pegawai"
                android:textColor="@color/white"
                android:textAppearance="@style/TextAppearance.AppCompat"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

            <TextView
                android:id="@+id/namapegawai"
                android:hint="nip pegawai"
                android:textColor="@color/white"
                android:textAppearance="@style/TextAppearance.AppCompat"
                android:layout_below="@id/nippegawai"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

            <TextView
                android:id="@+id/gajipegawai"
                android:hint="nip pegawai"
                android:textColor="@color/white"
                android:textAppearance="@style/TextAppearance.AppCompat"
                android:layout_below="@id/namapegawai"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
            <ImageView
                android:id="@+id/hapuspegawai"
                android:src="@android:drawable/ic_menu_delete"
                android:layout_centerVertical="true"
                android:layout_alignParentRight="true"
                android:layout_width="40dp"
                android:layout_height="40dp"/>

        </RelativeLayout>
    </androidx.cardview.widget.CardView>

</LinearLayout>

29. Lalu buka file activity_main dan isi dengan kode:

<?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=".CLASS.MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView_peg"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:listitem="@layout/format_pegawai"/>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/floatinginput"
        android:layout_alignParentBottom="true"
        android:src="@android:drawable/ic_input_add"
        app:maxImageSize="35dp"
        android:layout_alignParentRight="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>

30. Membuat “AdaptorPegawai” didalam package Adaptor.

package com.example.firebase.ADAPTOR;

import androidx.recyclerview.widget.RecyclerView;

public class AdaptorPegawai extends RecyclerView.Adapter<AdaptorPegawai.myviewholder> {
}

Nantinya kodenya akan berwarna merah, tinggal klik lampu yang berwarna merah, nanti kodenya akan menjadi seperti dibawah ini:

package com.example.firebase.ADAPTOR;

import android.view.View;
import android.view.ViewGroup;

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

public class AdaptorPegawai extends RecyclerView.Adapter<AdaptorPegawai.myviewholder> {
    @NonNull
    @Override
    public AdaptorPegawai.myviewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull AdaptorPegawai.myviewholder holder, int position) {

    }

    @Override
    public int getItemCount() {
        return 0;
    }

    public class myviewholder extends RecyclerView.ViewHolder {
        public myviewholder(@NonNull View itemView) {
            super(itemView);
        }
    }
}

31. Kemudian tambahkan kode berikut:

Activity activity;
ArrayList<ModelPegawai> modelPegawaiArrayList;

Dibawah kode:

public class AdaptorPegawai extends RecyclerView.Adapter<AdaptorPegawai.myviewholder> {

32. Kemudian dibawah kode:

ArrayList<ModelPegawai> modelPegawaiArrayList;

Klik kanan -> generate -> constructor.

Sehingga hasilnya:

public class AdaptorPegawai extends RecyclerView.Adapter<AdaptorPegawai.myviewholder> {
    Activity activity;
    ArrayList<ModelPegawai> modelPegawaiArrayList;

    public AdaptorPegawai(Activity activity, ArrayList<ModelPegawai> modelPegawaiArrayList) {
        this.activity = activity;
        this.modelPegawaiArrayList = modelPegawaiArrayList;
    }

33. Buka “Adaptor Pegawai”, kemudian tambahkan kode berikut:

cnip=itemView.findViewById(R.id.nippegawai);
cnama=itemView.findViewById(R.id.namapegawai);
cgaji=itemView.findViewById(R.id.gajipegawai);

deletepegawai=itemView.findViewById(R.id.hapuspegawai);
card01=itemView.findViewById(R.id.cardview_pagawai);

dibawah kode:

        public myviewHolder(@NonNull View itemView) {
            super(itemView);

Sehingga hasilnya:

    public class myviewholder extends RecyclerView.ViewHolder {
        TextView cnip, cnama, cgaji;
        ImageView deletepegawai;
        CardView card01;
        public myviewholder(@NonNull View itemView) {
            super(itemView);
            cnip=itemView.findViewById(R.id.nippegawai);
            cnama=itemView.findViewById(R.id.namapegawai);
            cgaji=itemView.findViewById(R.id.gajipegawai);

            deletepegawai=itemView.findViewById(R.id.hapuspegawai);
            card01=itemView.findViewById(R.id.cardview_pagawai);
        }
    }

34. Kemudian tambahkan kode berikut didalam getItemCount:

        return modelPegawaiArrayList.size();

Sehingga hasilnya:

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

35. Kemudian pada onBinViewHolder tambahkan kode berikut:

        holder.cnip.setText(modelPegawaiArrayList.get(position).getNip());
        holder.cnama.setText(modelPegawaiArrayList.get(position).getNama_peg());
        holder.cgaji.setText(String.valueOf(modelPegawaiArrayList.get(position).getGaji()));

Sehingga menjadi:

    @Override
    public void onBindViewHolder(@NonNull AdaptorPegawai.myviewholder holder, int position) {
        holder.cnip.setText(modelPegawaiArrayList.get(position).getNip());
        holder.cnama.setText(modelPegawaiArrayList.get(position).getNama_peg());
        holder.cgaji.setText(modelPegawaiArrayList.get(position).getGaji());
    }

36. Pada onCreateViewHolder tambahkan kode:

        LayoutInflater inflater=LayoutInflater.from(activity);
        View view=inflater.inflate(R.layout.format_pegawai,parent,false);
        return new AdaptorPegawai.myviewholder(view);

Sehingga menjadi:

    @Override
    public AdaptorPegawai.myviewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater=LayoutInflater.from(activity);
        View view=inflater.inflate(R.layout.format_pegawai,parent,false);
        return new AdaptorPegawai.myviewholder(view);
    }

37. Buka file MainActivity.java kemudian tambahkan kode berikut:

    RecyclerView recyclerView_pegawai;
    DatabaseReference dbr;
    ArrayList<ModelPegawai> modelPegawaiArrayList=new ArrayList<>();
    ModelPegawai modelPegawai;

Dibawah kode:

public class MainActivity extends AppCompatActivity {

38. Kemudian tambahkan kode berikut:

        recyclerView_pegawai=findViewById(R.id.recyclerView_peg);

        dbr = FirebaseDatabase.getInstance().getReference();
        recyclerView_pegawai.setLayoutManager(new LinearLayoutManager(this));
        tampilkan_pegawai();

        FloatingActionButton tmblinput;
        tmblinput=findViewById(R.id.floatinginput);
        tmblinput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(view.getContext(),EntryDataPegawai.class);
                view.getContext().startActivity(intent);
            }
        });

 

Didalam kode:

protected void onCreate(Bundle savedInstanceState) {

Sehingga menjadi:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView_pegawai=findViewById(R.id.recyclerView_peg);

        dbr = FirebaseDatabase.getInstance().getReference();
        recyclerView_pegawai.setLayoutManager(new LinearLayoutManager(this));
        tampilkan_pegawai();

        FloatingActionButton tmblinput;
        tmblinput=findViewById(R.id.floatinginput);
        tmblinput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(view.getContext(),EntryDataPegawai.class);
                view.getContext().startActivity(intent);
            }
        });
    }

39. lalu tambahkan kode berikut diatas kurung kurawal tutup terakhir:

    private void tampilkan_pegawai(){
        dbr.child("Pegawai").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for(DataSnapshot dataSnapshot:snapshot.getChildren()){
                    ModelPegawai modelPegawai=dataSnapshot.getValue(ModelPegawai.class);
                    modelPegawaiArrayList.add(modelPegawai);
                }
                AdaptorPegawai afp=new AdaptorPegawai(MainActivity.this, modelPegawaiArrayList);
                recyclerView_pegawai.setAdapter(afp);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }

Hapus Data

40. Pergi ke AdaptorPegawai kemudian buat kode:

        holder.deletepegawai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                
            }
        });

Dibawah kode:

        holder.cnip.setText(modelPegawaiArrayList.get(position).getNip());
        holder.cnama.setText(modelPegawaiArrayList.get(position).getNama_peg());
        holder.cgaji.setText(String.valueOf(modelPegawaiArrayList.get(position).getGaji()));

41. Tambahkan Kode berikut:

        holder.deletepegawai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder=new AlertDialog.Builder(activity);
                builder.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //   Toast.makeText(activity, "Cari Error"+modelPegawaiArrayList.get(position).getKey(), Toast.LENGTH_SHORT).show();
                        dbr= FirebaseDatabase.getInstance().getReference();
                        dbr.child("Pegawai").child(modelPegawaiArrayList
                                        .get(position)
                                        .getKey())
                                .removeValue()
                                .addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void unused) {
                                        Toast.makeText(activity, "Hapus Berhasil", Toast.LENGTH_SHORT).show();
                                        Intent intent=new Intent(activity, MainActivity.class);
                                        activity.startActivity(intent);
                                    }
                                });
                    }
                }).setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).setMessage("Apakah Data "+modelPegawaiArrayList.get(position).getNama_peg()+" Akan Dihapus ?");
                builder.show();
            }
        });

Dibawah:

        holder.cnip.setText(modelPegawaiArrayList.get(position).getNip());
        holder.cnama.setText(modelPegawaiArrayList.get(position).getNama_peg());
        holder.cgaji.setText(String.valueOf(modelPegawaiArrayList.get(position).getGaji()));

42. Lalu Buka MainActivity.java dan tambahkan kode:

modelPegawai.setKey(dataSnapshot.getKey());

Diatas kode:

modelPegawaiArrayList.add(modelPegawai);

Update Data

43. Buat EmptyActivity dengan nama “UpdateDataPegawai” didalam package class

44. Buka activity_update_data_pegawai , buat kode:

<?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=".CLASS.EntryDataPegawai">

    <TextView
        android:id="@+id/judule"
        android:text="Update Data Pegawai"
        android:textSize="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <EditText
        android:id="@+id/nipupdate"
        android:hint="nip pegawai"
        android:layout_below="@+id/judule"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <EditText
        android:id="@+id/namaupdate"
        android:hint="nama pegawai"
        android:layout_below="@+id/nipupdate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <EditText
        android:id="@+id/gajiupdate"
        android:hint="gaji pegawai"
        android:layout_below="@+id/namaupdate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <LinearLayout
        android:layout_below="@id/gajiupdate"
        android:layout_width="match_parent"
        android:gravity="center"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/btnupdate"
            android:text="save"
            android:layout_margin="4dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@+id/btnview"
            android:text="view"
            android:layout_margin="4dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>

</RelativeLayout>

45. Buka UpdateDataPegawai.java, tambahkan kode:

    EditText Enip,Enama,Egaji;
    Button tombolupdate;
    DatabaseReference dbr;
    ModelPegawai modelPegawai;

Dibawah kode: 

public class UpdateDataPegawai extends AppCompatActivity {

 46.  Tambahkan kode:

        enip=findViewById(R.id.nipupdate);
        enama=findViewById(R.id.namaupdate);
        egaji=findViewById(R.id.gajiupdate);
        
        tombolupdate=findViewById(R.id.btnupdate);

Dibawah kode:

        setContentView(R.layout.activity_update_data_pegawai);

47. Kemudian Buka AdaptorPegawai, dan tambahkan kode:

 

Share your love
Arataside
Arataside

Hi semua, saya adalah admin di arataside.com

Articles: 29

Leave a Reply

Alamat email Anda tidak akan dipublikasikan. Ruas yang wajib ditandai *