Firebase_RealtimeDatabase 사용 해보기.
2021. 12. 1. 17:03ㆍAndroid Development
google play service out of date 오류날때
-sdk manager 에서 google-play-service 삭제후 재설치.
-안드로이드 애뮬을 삭제후 재설치.
-build-gradle.zip install error >> 안드로이드 스튜디오 재설치.
google-service.json 갱신
consle페이지에서 realtime database만들기
테스트모드- region은 미국으로
어제 만들던 프로젝트에 이어서 작성
realTimeDB패키지 생성
package com.example.fcmtest.realTimeDB;
public class UserInfo {
private String userpwd;
private String username;
private String emailaddr;
public String getUserpwd() {
return userpwd;
}
public void setUserpwd(String userpwd) {
this.userpwd = userpwd;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmailaddr() {
return emailaddr;
}
public void setEmailaddr(String emailaddr) {
this.emailaddr = emailaddr;
}
}
userInfo.java
package com.example.fcmtest.realTimeDB;
public class MemoItem {
private String user;
private String memotitle;
private String memocontents;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getMemotitle() {
return memotitle;
}
public void setMemotitle(String memotitle) {
this.memotitle = memotitle;
}
public String getMemocontents() {
return memocontents;
}
public void setMemocontents(String memocontents) {
this.memocontents = memocontents;
}
}
MemoItem.java
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<TextView
android:id="@+id/memotitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/memocontents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/memotitle" />
</androidx.constraintlayout.widget.ConstraintLayout>
memo_item_list.xml
package com.example.fcmtest.realTimeDB;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.fcmtest.R;
import java.util.ArrayList;
public class MemoAdapter extends RecyclerView.Adapter<MemoAdapter.ViewHolder> {
private Context context = null;
private ArrayList<MemoItem> memoItems = null;
private MemoViewListener memoViewListener = null;
public MemoAdapter(Context context, ArrayList<MemoItem> memoItems, MemoViewListener memoViewListener) {
this.context = context;
this.memoItems = memoItems;
this.memoViewListener = memoViewListener;
}
@NonNull
@Override
public MemoAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.memo_item_list, parent, false);
ViewHolder holder = new ViewHolder(v);
return holder;
}
@Override
public void onBindViewHolder(@NonNull MemoAdapter.ViewHolder holder, int position) {
holder.titleView.setText(memoItems.get(position).getMemotitle());
holder.contentsView.setText(memoItems.get(position).getMemocontents());
}
@Override
public int getItemCount() {
return memoItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView titleView = null;
public TextView contentsView = null;
public ViewHolder(@NonNull View itemView) {
super(itemView);
titleView = itemView.findViewById(R.id.memotitle);
contentsView = itemView.findViewById(R.id.memocontents);
}
@Override
public void onClick(View v) {
memoViewListener.onItemClick(getAdapterPosition(), v);
}
}
}
MemoAdapter.java
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".realTimeDB.MemoActivity">
<EditText
android:id="@+id/memotitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="메모 타이틀" />
<EditText
android:id="@+id/memocontents"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="메모 내용" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/memobtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="메모 등록" />
<Button
android:id="@+id/reguser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="사용자 등록" />
</LinearLayout>
<TextView
android:id="@+id/memolisttitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="메모 리스트" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/memolist"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
activity_memo.xml
package com.example.fcmtest.realTimeDB;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.fcmtest.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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 com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Random;
public class MemoActivity extends AppCompatActivity
implements View.OnClickListener, MemoViewListener {
private ArrayList<MemoItem> memoItems = null;
private MemoAdapter memoAdapter = null;
private String username = null;
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = firebaseDatabase.getReference();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memo);
Log.d("jaeho", databaseReference.toString());
init();
initView();
}
@Override
protected void onStart() {
super.onStart();
addChildEvent();
addValueEventListener();
}
private void addValueEventListener() {
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
//Log.d("jaeho", "Value = " +snapshot.getValue().toString());
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void addChildEvent() {
databaseReference.child("memo").addChildEventListener(new
ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot snapshot
, @Nullable String previousChildName) {
Log.d("jaeho", "addChildEvent in");
MemoItem item = snapshot.getValue(MemoItem.class);
memoItems.add(item);
memoAdapter.notifyDataSetChanged();
}
@Override
public void onChildChanged(@NonNull DataSnapshot snapshot
, @Nullable String previousChildName) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot snapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot snapshot
, @Nullable String previousChildName) {
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void initView() {
Button regbtn = findViewById(R.id.memobtn);
regbtn.setOnClickListener(this);
Button userbtn = findViewById(R.id.reguser);
userbtn.setOnClickListener(this);
RecyclerView.LayoutManager layoutManager = new
LinearLayoutManager(this);
RecyclerView recyclerView = findViewById(R.id.memolist);
memoAdapter = new MemoAdapter(this, memoItems, this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(memoAdapter);
}
private void init() {
memoItems = new ArrayList<>();
username = "user_" + new Random().nextInt(1000);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.memobtn:
regMemo();
break;
case R.id.reguser:
writeNewUser();
break;
}
}
private void writeNewUser() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is signed in
String name = user.getDisplayName();
String email = user.getEmail();
String uid = user.getUid();
Log.d("jaeho", "name = " + name);
Log.d("jaeho", "email = " + email);
Log.d("jaeho", "uid = " + uid);
UserInfo userInfo = new UserInfo();
userInfo.setUserpwd("1234");
userInfo.setUsername(name);
userInfo.setEmailaddr(email);
databaseReference.child("users").child(uid).setValue(userInfo);
} else {
// No user is signed in
Log.d("jaeho", "user null");
}
}
private void regMemo() {
EditText titleedit = findViewById(R.id.memotitle);
EditText contentsedit = findViewById(R.id.memocontents);
if (titleedit.getText().toString().length() == 0 ||
contentsedit.getText().toString().length() == 0) {
Toast.makeText(this,
"메모 제목 또는 메모 내용이 입력되지 않았습니다. 입력 후 다시 시작해주세요.",
Toast.LENGTH_LONG).show();
return;
}
MemoItem item = new MemoItem();
item.setUser(this.username);
item.setMemotitle(titleedit.getText().toString());
item.setMemocontents(contentsedit.getText().toString());
databaseReference.child("memo").push().setValue(item);
}
@Override
public void onItemClick(int position, View view) {
}
}
MemoActivity.java
실행 후 app 내에서 메모 작성시 실시간 DB에 반영.
'Android Development' 카테고리의 다른 글
Friebase 사용해서 push message 보내기 (0) | 2021.12.02 |
---|---|
Firebase로 로그인 처리하기 (0) | 2021.12.01 |
Google Firebase 환경설정. (0) | 2021.11.29 |
Android semiProject (0) | 2021.11.24 |
Android Studio 13일차 (0) | 2021.11.17 |