แนะนำการใช้งาน Firebase และสร้างแอป Android ติดต่อ Firebase Database

ไปที่ firebase.google.com คลิกที่ปุ่ม ไปที่คอนโซล

Create Firebase Project

select Android

เลือกที่เมนู Database เลือก Tab กฎ และเปลี่ยนสิทธิ์ให้ไม่ต้องมีการตรวจสอบผู้ใช้

 

Use Postman Test send json to Firebase

Design UI

activity_main.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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name : " />

        <EditText
            android:id="@+id/edName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Group : " />

        <Spinner
            android:id="@+id/spinGroup"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:entries="@array/group" />

        <Button
            android:id="@+id/btnAdd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Add" />

    </LinearLayout>

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

strings.xml

<resources>
    <string name="app_name">FirebaseCRUD</string>

    <array name="group">
        <item>Admin</item>
        <item>User</item>
        <item>Guest</item>
    </array>
</resources>

Create UserDao.java

public class UserDao {
    private String id;
    private String name;
    private String group;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGroup() {
        return group;
    }

    public void setGroup(String group) {
        this.group = group;
    }
}

 

Probably needs an update of Google Play Services and Google Repository.

In Android Studio SDK Manager:

  • Select SDK Tools tab
  • Select and install Google Play Services and Google Repository
  • Sync and Build

Add the dependency for Firebase Realtime Database to your app-level build.gradle file:

compile 'com.google.firebase:firebase-database:11.0.1'

MainActivity.java

Firbase Instatnce

  private void initFirebase() {
        databaseReference = FirebaseDatabase.getInstance().getReference();
    }

init Instatnces

   private void initInstances() {
        edName = (EditText) findViewById(R.id.edName);
        spinGroup = (Spinner) findViewById(R.id.spinGroup);
        btnAdd = (Button) findViewById(R.id.btnAdd);
        btnAdd.setOnClickListener(this);
        listView = (ListView) findViewById(R.id.listView);

        users = new ArrayList<>();

    }

 

set value to Firebase

   private void addUser() {
        String name = edName.getText().toString();
        String group = spinGroup.getSelectedItem().toString();

        //checking if the value is provided
        if (!TextUtils.isEmpty(name)) {
            String id = firebaseReference.child("users").push().getKey();

            UserDao user = new UserDao();
            user.setId(id);
            user.setName(name);
            user.setGroup(group);

            firebaseReference.child("users").child(id).setValue(user);

            Toast.makeText(this, "Artist added", Toast.LENGTH_LONG).show();
            edName.setText("");
        } else {
            //if the value is not given displaying a toast
            Toast.makeText(this, "Please enter a name", Toast.LENGTH_LONG).show();
        }
    }

MainActivity.java

   public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private DatabaseReference firebaseReference;
    private EditText edName;
    private Spinner spinGroup;
    private Button btnAdd;
    private ListView listView;
    private List<UserDao> users;

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

        initInstances();
        initFirebase();
    }

    private void initFirebase() {
        firebaseReference = FirebaseDatabase.getInstance().getReference();
    }

    private void initInstances() {
        edName = (EditText) findViewById(R.id.edName);
        spinGroup = (Spinner) findViewById(R.id.spinGroup);
        btnAdd = (Button) findViewById(R.id.btnAdd);
        btnAdd.setOnClickListener(this);
        listView = (ListView) findViewById(R.id.listView);

        users = new ArrayList<>();

    }

    @Override
    public void onClick(View view) {
        if (view==btnAdd){
            addUser();
        }
    }

    private void addUser() {
        String name = edName.getText().toString();
        String group = spinGroup.getSelectedItem().toString();

        //checking if the value is provided
        if (!TextUtils.isEmpty(name)) {
            String id = firebaseReference.child("users").push().getKey();

            UserDao user = new UserDao();
            user.setId(id);
            user.setName(name);
            user.setGroup(group);

            firebaseReference.child("users").child(id).setValue(user);

            Toast.makeText(this, "Artist added", Toast.LENGTH_LONG).show();
            edName.setText("");
        } else {
            //if the value is not given displaying a toast
            Toast.makeText(this, "Please enter a name", Toast.LENGTH_LONG).show();
        }
    }
}

run app

Test Add User

Check Firebase Database

 

Custom ListView

Design List Item

Create user_list_item.xml

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

    <TextView
        android:text="Name"
        android:textSize="24sp"
        android:id="@+id/tvName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:text="Group"
        android:id="@+id/tvGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
</LinearLayout>

 

Create UserListItem.java

public class UserListItem extends BaseCustomViewGroup {

    private TextView tvName;
    private TextView tvGroup;

    public UserListItem(Context context) {
        super(context);
        initInflate();
        initInstances();
    }

    public UserListItem(Context context, AttributeSet attrs) {
        super(context, attrs);
        initInflate();
        initInstances();
        initWithAttrs(attrs, 0, 0);
    }

    public UserListItem(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initInflate();
        initInstances();
        initWithAttrs(attrs, defStyleAttr, 0);
    }

    @TargetApi(21)
    public UserListItem(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initInflate();
        initInstances();
        initWithAttrs(attrs, defStyleAttr, defStyleRes);
    }

    private void initInflate() {
        inflate(getContext(), R.layout.user_list_item, this);
    }

    private void initInstances() {
        tvName = (TextView) findViewById(R.id.tvName);
        tvGroup = (TextView) findViewById(R.id.tvGroup);
    }

    private void initWithAttrs(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        /*
        TypedArray a = getContext().getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.StyleableName,
                defStyleAttr, defStyleRes);

        try {

        } finally {
            a.recycle();
        }
        */
    }

    @Override
    protected Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();

        BundleSavedState savedState = new BundleSavedState(superState);
        // Save Instance State(s) here to the 'savedState.getBundle()'
        // for example,
        // savedState.getBundle().putString("key", value);

        return savedState;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        BundleSavedState ss = (BundleSavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());

        Bundle bundle = ss.getBundle();
        // Restore State from bundle here
    }

    public void setTvName(String text) {
        tvName.setText(text);
    }    
    public void setTvGroup(String text) {
        tvGroup.setText(text);
    }    

}

 

Create UserAdapter

public class UserAdapter extends BaseAdapter {

    List<UserDao> users;

    public UserAdapter(List<UserDao> users) {
        this.users = users;
    }

    @Override
    public int getCount() {
        if (users == null)
            return 0;
        return users.size();
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        UserListItem item;
        if (view != null)
            item = (UserListItem) view;
        else
            item = new UserListItem(viewGroup.getContext());

        UserDao dao = users.get(position);

        item.setTvName(dao.getName());
        item.setTvGroup(dao.getGroup());

        return item;
    }
}

MainActivity.java

Show data on ListView

 private void showData() {
        Query query = firebaseReference.child("users");
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                users.clear();
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                    UserDao dao = postSnapshot.getValue(UserDao.class);
                    users.add(dao);
                }
                adapter = new UserAdapter(users);
                listView.setAdapter(adapter);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

Run app

Test Add User

Check Firebase Console

Update + Delete User

set Long Click on List View

Design User Dialog

user_dialog.xml

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

    <EditText
        android:id="@+id/edName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter name" />

    <Spinner
        android:id="@+id/spinnerGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:entries="@array/group"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnUpdate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Update" />

        <Button
            android:id="@+id/btnDelete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Delete" />

    </LinearLayout>

</LinearLayout>

MainActivity.java

Update User

  private boolean updateUser(String id, String name, String group) {
        //updating
        UserDao dao = new UserDao();
        dao.setId(id);
        dao.setName(name);
        dao.setGroup(group);

        firebaseReference.child("users").child(id).setValue(dao);
        Toast.makeText(this, "User Updated", Toast.LENGTH_LONG).show();
        return true;
    }

Delete User

   private boolean deleteUser(String id) {
        //removing
        firebaseReference.child("users").child(id).removeValue();

        Toast.makeText(this, "User Deleted", Toast.LENGTH_LONG).show();

        return true;
    }

Show Dialog

 private int getIndex(Spinner spinner, String myString) {
        int index = 0;

        for (int i = 0; i < spinner.getCount(); i++) {
            if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(myString)) {
                index = i;
                break;
            }
        }
        return index;
    }

    private void showDialog(final UserDao dao) {

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        LayoutInflater inflater = this.getLayoutInflater();
        final View dialogView = inflater.inflate(R.layout.user_dialog, null);
        dialogBuilder.setView(dialogView);

        final EditText edName = (EditText) dialogView.findViewById(R.id.edName);
        final Spinner spinnerGroup = (Spinner) dialogView.findViewById(R.id.spinnerGroup);
        final Button btnUpdate = (Button) dialogView.findViewById(R.id.btnUpdate);
        final Button btnDelete = (Button) dialogView.findViewById(R.id.btnDelete);

        dialogBuilder.setTitle(dao.getName());
        edName.setText(dao.getName());
        spinnerGroup.setSelection(getIndex(spinnerGroup, dao.getGroup()));
        final AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.show();

        btnUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = edName.getText().toString().trim();
                String genre = spinnerGroup.getSelectedItem().toString();
                if (!TextUtils.isEmpty(name)) {
                    updateUser(dao.getId(), name, genre);
                    alertDialog.dismiss();
                }
            }
        });

        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteUser(dao.getId());
                alertDialog.dismiss();
            }
        });

    }

       listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                UserDao dao = users.get(i);
                showDialog(dao);
                return false;
            }
        });

Run App

Long click ListView

 

github: https://github.com/thana19/FirebaseCRUD

(Visited 125 times, 1 visits today)
Spread the love