Android App

RecyclerView with Firebase in Android Studio

YunSeong 2021. 11. 27. 11:53
728x90
반응형

https://youtu.be/HcPWt69d_wY

1. 라이브러리 추가

1)

https://github.com/bumptech/glide

 

GitHub - bumptech/glide: An image loading and caching library for Android focused on smooth scrolling

An image loading and caching library for Android focused on smooth scrolling - GitHub - bumptech/glide: An image loading and caching library for Android focused on smooth scrolling

github.com

위 페이지에 나와있는 설명처럼 아래 두 줄을 추가해주면서 url사진을 불러올 수 있게 해주는 라이브러리를 추가한다.

1
2
3
4
5
dependencies {
        ...
    implementation 'com.github.bumptech.glide:glide:4.12.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
}
cs

2)

Tools -> Firebase -> Realtime Database 에서 Database까지 연결해준다.


2. activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?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"
    tools:context=".MainActivity">
 
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
 
</LinearLayout>
cs

9~12 - recyclerView 위젯을 추가해주고 id를 지정해준다.


3. User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.example.firebaseliststudy;
 
public class User {
    private String profile;
    private String id;
    private int pw;
    private String userName;
 
    public User(){}
 
    ...
}
 
cs

4~7 - recyclerview에서 띄우고 싶은 정보들을 여기에 변수를 선언해준다.

9 - firebase를 사용할 때는 비어있는 생성자 또한 만들어줘야한다.

11 - 각각의 변수에 대한 Getter, Setter을 만들어준다.


4. list_item.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?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="horizontal">
    <ImageView
        android:id="@+id/iv_p"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_margin="5dp"
        android:src="@drawable/ic_launcher_foreground"/>
    <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="id"
            android:layout_margin="5dp"/>
        <TextView
            android:id="@+id/tv_pw"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="password"/>
        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="username"/>
 
    </LinearLayout>
</LinearLayout>
cs

1~35 - recyclerview의 item를 구성해준다.

7, ~ - 요소들 중에 각각의 item마다 다른 정보를 띄우고 싶은 위젯에는 id를 설정해준다.


5. CustomAdapter.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.example.firebaseliststudy;
 
import ...
 
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {
 
    private ArrayList<User> arrayList;
    private Context context;
 
    public CustomAdapter(ArrayList<User> arrayList, Context context) {
        this.arrayList = arrayList;
        this.context = context;
    }
 
    @NonNull
    @Override
    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_p);
        holder.tv_id.setText(arrayList.get(position).getId());
        holder.tv_pw.setText(String.valueOf(arrayList.get(position).getPw()));
        holder.tv_name.setText(arrayList.get(position).getUserName());
    }
 
    @Override
    public int getItemCount() {
        return (arrayList != null? arrayList.size() : 0);
    }
 
    public class CustomViewHolder extends RecyclerView.ViewHolder {
 
        ImageView iv_p;
        TextView tv_id;
        TextView tv_pw;
        TextView tv_name;
 
        public CustomViewHolder(@NonNull View itemView) {
            super(itemView);
            this.iv_p = itemView.findViewById(R.id.iv_p);
            this.tv_id = itemView.findViewById(R.id.tv_id);
            this.tv_pw = itemView.findViewById(R.id.tv_pw);
            this.tv_name = itemView.findViewById(R.id.tv_name);
        }
    }
}
 
cs

5 - 상속해주는 것이 중요하다.

10~13 - 생성자를 이용해서 매개변수로 ArrayListContext를 받아온다.

15~21

    18 - 위에서 만들었던 list_itemview에 담아준다.

    19~20 - 그 view를 이용해서 holder를 만든 후 반환해준다.

23~31 - 매개변수로 주어지는 positionarrayList를 이용해서 적절하게 holder의 위젯에 설정을 한다.

33~36 - item의 개수를 반환하는 함수를 만든다.

38~52 - holder에 담을 위젯들을 설정해준다.


6. MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.example.firebaseliststudy;
 
import ...
 
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<>();
 
        database = FirebaseDatabase.getInstance();
        databaseReference = database.getReference("User");
        databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) { //데이터베이스의 데이터를 받아오는 곳
                arrayList.clear(); //기존 배열 초기화
                for (DataSnapshot snapshot1 : snapshot.getChildren()){
                    User user = snapshot1.getValue(User.class);
                    arrayList.add(user);
                }
                adapter.notifyDataSetChanged();
            }
 
            @Override
            public void onCancelled(@NonNull DatabaseError error) {// 데이터를 받아오다 에러 발생 시
                Log.e("MainActivity", error.toException().toString());
            }
        });
        adapter = new CustomAdapter(arrayList, this);
        recyclerView.setAdapter(adapter);
 
    }
}
cs

30~37 - database의 정보에 변화가 있을 때의 이벤트로 동기화를 하기 위해 사용한다.

    33~34 - 정보들을 User.java class의 형태로 정보를 받아와서 arrayList에 넣어준다.


7. 결과

위와 같이 Realtime Database에 저장되어있는 정보를

위와 같이 recyclerview에 띄울 수 있다.

728x90
반응형