Friday, February 22, 2019

Membuat Realtime Chat Sederhana Menggunakan Android Studio Dengan Database Firebase

Membuat Realtime Chat Sederhana Menggunakan Android Studio Dengan Database Firebase - CodePolitan.com

Tutorial saya kali ini saya akan membuat Chat realtime sederhana dengan firebase saya asumsikan untuk coder yang sudah punya akun firebase , kalau belum tau bisa cari tahu di google , oke langsung saja mulai.
  1. Buka android studio lalu pilih File -> New Project
  2. Berinama Project RealtimeChat tanpa petik, pilih next
  3. Pilih API level 17:Android 4.2 ( Jelly Bean ) ,next
  4. Pilih Empty Activity, next
  5. Nama activity dan class Biarkan saja default -> Finish
  6. Buka browser dan masukan alamat https://console.firebase.google.com/
  7. Pilih Create New Project, isikan Project name Sesuai dengan yang tadi kita
    buat dan pilih juga negaranya yang pasti INDONESIA hehe
  8. Setelah Create New Projek lalu akan di alihakan he halaman seperti berikut, Lalu
    pilih yang di tengah Add Firebase to your android app

  9. Isi Form sesuai Name Package yang ada di projek , Untuk SHA 1 optional
    jika di isi ini caranya :


    1. Refresh Gradlenya
    2. Pilih RealtimeChat -> RealtimeChat (root) -> Tasks ->
      android -> double klik pada signing report
    3. Setelah beberapa saat akan muncul dialog yang berada di bawah, lalu copy SHA 1
      pada Form tadi
  10. Setelah langkah pertama selesai maka akan secara otomatis akan mendownload
    file json, setelah terdwonload copy file json tersebut di folder app

  11. Yang terakhir kita harus menambahkan beberapa baris code pada Gradle
    build
    dan Gradle app level

    Gradle build
    Gradle level app
  12. Buka browser lagi untuk mengubah Permision pada database , Pilih Databse
    -> Rules - > ubah "auth != null" jadi true -> Publish

Source Code

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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.darsiwan.fireapp.MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_above="@+id/etNeme_room">
    </ListView>

    <EditText

        android:layout_width="226dp"
        android:layout_height="wrap_content"
        android:id="@+id/etNeme_room"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:layout_toStartOf="@+id/btnAdd_room" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Room"
        android:id="@+id/btnAdd_room"
        android:layout_gravity="right" style="?android:attr/borderlessButtonStyle"
        android:drawableLeft="@drawable/ic_add_black_24dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

MainActivity.java

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.firebase.client.Firebase;
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.ValueEventListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    private  Button add_room;
    private  EditText room_name;
    private ListView listView;
    private String name;
    private DatabaseReference root = FirebaseDatabase.getInstance().getReference().getRoot();

    private ArrayAdapter<String> arrayAdapter;
    private ArrayList<String> list_of_rooms = new ArrayList();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        add_room = (Button)findViewById(R.id.btnAdd_room);
        room_name = (EditText)findViewById(R.id.etNeme_room);
        listView = (ListView)findViewById(R.id.listView);

        arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list_of_rooms);
        listView.setAdapter(arrayAdapter);

        request_user_name();
        add_room.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Map<String,Object> map = new HashMap<String,Object>();
                map.put(room_name.getText().toString(),"");
                root.updateChildren(map);

            }
        });
        root.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Set<String> set = new HashSet<String>();
                Iterator i = dataSnapshot.getChildren().iterator();
                while ( i.hasNext())
                {
                    set.add(((DataSnapshot)i.next()).getKey());
                }
                list_of_rooms.clear();
                list_of_rooms.addAll(set);

                arrayAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Intent I = new Intent(getApplicationContext(),chatroom.class);
                I.putExtra("room_name",((TextView)view).getText().toString());
                I.putExtra("user_name",name);
                startActivity(I);
            }
        });

    }

    private void request_user_name() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Enter Name");
        final EditText input_field = new EditText(this);
        builder.setView(input_field);
        builder.setPositiveButton("OK ", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                name = input_field.getText().toString();
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
                request_user_name();
            }
        });
        builder.show();
    }
}

Buat Empty Activity dengan nama activity_chatroom.xml dan chatroom.java

  1. activity_chatroom.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.darsiwan.fireapp.chatroom"
    android:weightSum="1">

    <ScrollView
        android:layout_width="378dp"
        android:layout_height="157dp"
        android:id="@+id/scrollView"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_weight="1.04">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:id="@+id/textView" />
    </ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="1">
        <EditText
            android:layout_width="59dp"
            android:layout_height="wrap_content"
            android:id="@+id/editText"
            android:layout_alignTop="@+id/button"
            android:layout_alignParentStart="true"
            android:layout_toStartOf="@+id/button"
            android:layout_weight="1.02" />

        <Button
            android:layout_width="52dp"
            android:layout_height="wrap_content"

            android:id="@+id/button" style="?android:attr/borderlessButtonStyle"
            android:drawableLeft="@drawable/ic_send_black_24dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentEnd="true" />

    </LinearLayout>

</LinearLayout>
  1. chatroom.java
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.firebase.database.ChildEventListener;
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 java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class chatroom extends AppCompatActivity {

    private Button btn_send_msg;
    private EditText input_msg;
    private TextView chat_conversation;
    private String user_name ,room_name;
    private DatabaseReference root;
    private String temp_key;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chatroom);
        btn_send_msg = (Button)findViewById(R.id.button);
        input_msg = (EditText)findViewById(R.id.editText);
        chat_conversation = (TextView)findViewById(R.id.textView);
        user_name = getIntent().getExtras().get("user_name").toString();
        room_name = getIntent().getExtras().get("room_name").toString();
        setTitle("Room - "+room_name);

        root = FirebaseDatabase.getInstance().getReference().child(room_name);

        btn_send_msg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Map<String,Object> map = new HashMap<String, Object>();
                temp_key = root.push().getKey();
                root.updateChildren(map);

                DatabaseReference message_root = root.child(temp_key);
                Map<String,Object> map2 = new HashMap<String, Object>();
                map2.put("name",user_name);
                map2.put("msg",input_msg.getText().toString());

                message_root.updateChildren(map2);

            }
        });

        root.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {

                append_chat_conversatin(dataSnapshot);

            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                append_chat_conversatin(dataSnapshot);
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }
private String chat_msg, chat_user_name;

    private void append_chat_conversatin(DataSnapshot dataSnapshot) {
        Iterator i = dataSnapshot.getChildren().iterator();
        while (i.hasNext())
        {
            chat_msg = (String) ((DataSnapshot)i.next()).getValue();
            chat_user_name = (String) ((DataSnapshot)i.next()).getValue();

            chat_conversation.append(chat_user_name + " : "+chat_msg +"\n");

        }
    }
}

Edit androidmanifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.darsiwan.fireapp">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".chatroom"></activity>
    </application>

</manifest>

Jalankan aplikasinya

Penutup

Demikian tutorial saya kali ini kalau ada yang kurang jelas mohon tanyakan pada kolom komentar , Terima Kasih , Semoga bermanfaat !
Unduh aplikasi jadi di sini


SUMBER

No comments:

Post a Comment

Rekomendasi Aplikasi Penghasil Cuan :D Dirumah saja tetap Dapet Duit !!!

Hallo Bosskyuuh semua. Perkenalkan aku Patrick Ananta berasal dari Jawa Tengah. Aku sudah lama sekali dirumahkan dikarenakan covid19 sehingg...