private Context context; // 선택한 액티비티에 대한 context를 가져올 때 필요
implementation 'com.github.bumptech.glide:glide:4.10.0' // 이미지 로딩을 더 원활하게 해 줄 수 있는 라이브러리
MainActivity.java
1. 상단 Tools 탭 클릭
2. Firebase 클릭 > Realtime Database에 Sava and retrieve data 클릭
3. connect to Firebase
4. Add the Realtime Database to your app 클릭
5. Accept Changes
파이어 베이스 콘솔
1. 파이어 베이스 콘솔 검색
2. 좌측 개발 탭에서 Realtime Database 클릭
3. 데이터 베이스 만들기 클릭
4. 테스트 모드에서 시작 클릭 > 사용 설정 클릭
5. 생성된 코드에서 + 클릭
6. 이름 탭에서 User 입력 후, + 클릭
7. 생성된 탭에 이름 User_01 입력 후, + 클릭
8. 생성된 탭에 이름 id 값은 khon 입력 후, User_01 탭에 + 클릭
9. 두번째 생성된 탭에 이름 pw 값은 1234 입력 후, User_01 탭에 + 클릭
10. 세번째 생성된 탭에 이름 userName 값은 khon 입력 후, 추가 버튼 클릭
데이터 베이스 안에 이미지 주소 넣기
1. 파이어 베이스 콘솔 사이트 좌측에 Storage 클릭
2. 시작하기 > 다음 > 완료
3. Rulse 클릭
4.
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if true;
}
}
}
5. 게시 클릭
6. FIles 클릭 > 파일 업로드(이미지 파일 선택 후 업로드) > 업로드된 파일 클릭 > 액세스 토큰 URL 클릭
7. Realtime Database 클릭 > User_01 탭에 + 클릭 > 생성된 탭에 이름 profile 값에 복사된 URL 붙여넣기 > 추가 클릭
결과 값 추가
1. Realtime Database에 우측 상단 점 세개 클릭 후, JSON 내보내기 클릭
2. JSON 파일 메모장으로 실행 후
{
"User" : {
"User_01" : {
"id" : "khon",
"profile" : "https://firebasestorage.googleapis.com----",
"pw" : 1234,
"userName" : "khon"
}
}
}
위 코드들을
{
"User" : {
"User_01" : {
"id" : "khon",
"profile" : "https://firebasestorage.googleapis.com----",
"pw" : 1234,
"userName" : "khon"
},
"User" : {
"User_02" : {
"id" : "khon",
"profile" : "https://firebasestorage.googleapis.com----",
"pw" : 1234,
"userName" : "khon"
},
"User" : {
"User_03" : {
"id" : "khon",
"profile" : "https://firebasestorage.googleapis.com----",
"pw" : 1234,
"userName" : "khon"
},
"User" : {
"User_04" : {
"id" : "khon",
"profile" : "https://firebasestorage.googleapis.com----",
"pw" : 1234,
"userName" : "khon"
}
}
}
위 코드 처럼 복사, 붙여 넣기 후 저장
3. Realtime Database 우측 상단 점 세개 클릭 후, JSON 가져오기 클릭
4. 찾아보기 > 저장 한 파일 선택 > 가져오기 클릭
--------------------------------
activity_main.xml
<?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"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
--------------------------------
--------------------------------
MainActivity.java
package com.example.firebaselist;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
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;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<User> arrayList;
private FirebaseDatabase database;
private DatabaseReference databaseReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerview); // 아이디 연결
recyclerView.setHasFixedSize(true); // 리사이클러뷰 기존성능 강화
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
arrayList = new ArrayList<>(); // User 객체를 담을 Array 리스트 (어댑터 쪽으로)
database = FirebaseDatabase.getInstance(); // Firebase Database 연동
databaseReference = database.getReference("User"); // DB 테이블 연결결
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// Firebase Database의 데이터를 받아오는 곳
arrayList.clear(); // 기존 배열 리스트가 존재하지 않게 초기화
for (DataSnapshot snapshot : dataSnapshot.getChildren()) { // 반복문으로 데이터 List를 추출
User user = snapshot.getValue(User.class); // 만들어졌던 User 객체에 데이터를 담는다
arrayList.add(user); // 담은 데이터들을 배열 리스트에 넣고 리사이클러뷰로 보낼 준비
}
adapter.notifyDataSetChanged(); // 리스트 저장 및 새로고침
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
// 디비를 가져오던 중 에러 발생 시
Log.e("MainActivity", String.valueOf(databaseError.toException())); // 에러문 출력
}
});
adapter = new CustomAdapter(arrayList, this);
recyclerView.setAdapter(adapter); // 리사이클러뷰에 어댑터 연결
}
}
--------------------------------
xml 파일 생성
--------------------------------
list_item.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="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/iv_profile"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_margin="5dp"
android:src="@drawable/ic_launcher_background"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:orientation="vertical">
<TextView
android:id="@+id/tv_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="아이디"
android:layout_margin="5dp"/>
<TextView
android:id="@+id/tv_pw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="비밀번호"
android:layout_margin="5dp"/>
<TextView
android:id="@+id/tv_userName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="khon"
android:layout_margin="5dp"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
--------------------------------
java 파일 생성
--------------------------------
package com.example.firebaselist;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {
private ArrayList<User> arrayList;
private Context context; // 선택한 액티비티에 대한 context를 가져올때 필요
// Alt + Ins 키 누르고 Instructor
public CustomAdapter(ArrayList<User> arrayList, Context context) {
this.arrayList = arrayList;
this.context = context;
}
@NonNull
@Override
// list View가 Adapter에 연결 돼었을때 뷰 홀더를 만들어 냄
public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false); // 뷰 연결 완료
CustomViewHolder holder = new CustomViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
Glide.with(holder.itemView)
.load(arrayList.get(position).getProfile())
.into(holder.iv_profile);
holder.tv_id.setText(arrayList.get(position).getId());
holder.tv_pw.setText(String.valueOf(arrayList.get(position).getPw()));
holder.tv_userName.setText(arrayList.get(position).getUserName());
}
@Override
public int getItemCount() {
// 삼향 연산자 (if문과 비슷)
return (arrayList != null ? arrayList.size() : 0);
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView iv_profile;
TextView tv_id;
TextView tv_pw;
TextView tv_userName;
public CustomViewHolder(@NonNull View itemView) {
super(itemView);
this.iv_profile = itemView.findViewById(R.id.iv_profile);
this.tv_id = itemView.findViewById(R.id.tv_id);
this.tv_pw = itemView.findViewById(R.id.tv_pw);
this.tv_userName = itemView.findViewById(R.id.tv_userName);
}
}
}
--------------------------------
java 파일 생성
--------------------------------
User.java
package com.example.firebaselist;
public class User {
private String profile;
private String id;
private int pw;
private String userName;
public User(){}
// Alt + Ins 키 누르고 Getter and Setter 선택, Shift키 누른 상태로 맨 밑에 코드 클릭
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getPw() {
return pw;
}
public void setPw(int pw) {
this.pw = pw;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
--------------------------------
--------------------------------
build.gradle (:app)
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 30
buildToolsVersion "30.0.1"
defaultConfig {
applicationId "com.example.firebaselist"
minSdkVersion 28
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'com.github.bumptech.glide:glide:4.10.0' // 이미지 로딩을 더 원활하게 해줄수 있는 라이브러리
implementation 'com.google.firebase:firebase-database:19.3.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}