앱만들기 33.(Firebase RecyclerView)

alt +insert

 

Getter and Setter 

 

 

gradle.app

이미지 로딩을 좀 더 쉽게(범용적으로쓰이는 라이브러리)

implementation 'com.github.bumptech.glide:glide:4.10.0'

annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'

(안드로이드x버전을 위해 추가함 밑에꺼는)

 

 

 

firebase

 

Realtime DB쓸거임

save어쩌고누르고

connect 해주기

 

걍 냅뒀더니 연결이 너무 안되는거임.. 그래서 프로젝트 생성을 연결된 firebase 사이트에서 눌러줬더니..됨

나 왜기다림..

 

 

firebase console사이트에들어가서 리얼타임DB눌러주기

데이터베이스 만들기 눌러줌 (테스트모드로)

 

User01컬럼에 만들어주기

 

profile 과같이 이미지를 db에 넣어주려면 storage를 활성화시켜야함.

 

시작하고, 규칙(권한)바꿔줌

 

 

파일 업로드해서 원하는 이미지 업로드해주기

사진클릭해서, 파일위치 눌러서 다운로드 경로 복사해주기

 

abc순 자동정렬, 아 근데 이거 비밀번호 1234 여야함.

여기에 넣어주깅

 

이러한 데이터베이스 연결하는 구문

 

구동전에 ! 비밀번호 혼자만 정수값이므로 스트링값으로 만들어주자.

 

 

 


코드 다짜고, 실행해보면 하나만 듬

여러개 뜨게해보자

 

 

 

수정

수정한 파일가져오기

 

올ㅋ

 

main.js

package com.example.firebaseexample;

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객체를 담을 arraylist(어댑터쪽으로)

        database = FirebaseDatabase.getInstance(); //firebase DB기능 연동

        databaseReference = database.getReference("User"); //DB테이블 연결
        databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                //파이어베이스 데이터베이스의 데이터를 받아오는 곳
                arrayList.clear(); //기존 배열리스트가 존재하지 않게 방지차원 초기화
                for (DataSnapshot snapshot: dataSnapshot.getChildren()){ //반복문으로 데이터 리스트 추출해내기
                    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()));//에러문 출력

            }
        });
        //activity oncreate 에서는 this가 context에 해당됨
        adapter = new CustomAdapter(arrayList, this);
        recyclerView.setAdapter(adapter);//리사이클러 뷰 어댑터 연결






    }
}

User.js

package com.example.firebaseexample;

public class User {
    private String profile; //이미지가 string인이유는 firebase에서 가져올때 url주소를 가져와서 이미지 로드라이브로 띄워주기때문
    private String id;
    private int pw;
    private String username;

    public User(){}

    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;
    }
}

CustomAdaptor.js

package com.example.firebaseexample;

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;
    //어댑터에서 액티비티 액션을 가져올때


    public CustomAdapter(ArrayList<User> arrayList, Context context) {
        this.arrayList = arrayList;
        this.context = context;
    }

    @NonNull
    @Override
    public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //뷰홀더를 최초로 만들어냄, listitem 이 한 컬럼을 만들어낼때 선언
        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) {
        //각 아이템들에 대한 매칭 , imageview를 서버로부터 불러옴 (편하게 로딩하는 라이브러리 써야)
        //유저 객체가 있는 어레이리스트에 담아서 여기 자바에 쏜걸 받아서 글라이드 로드하는것

        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() {
        //삼항연산자
        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);
        }
    }
}

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="촬리"
                android:layout_margin="5dp"
                />


        </LinearLayout>

    </LinearLayout>


</LinearLayout>

activity.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>

 

 

결과:

자꾸 어플 중지됨

진짜 너무 화난다..

https://code-examples.net/ko/q/2639883

 

android - 슬라이드 - 안드로이드 메뉴 버튼

 

code-examples.net

여기 참고하면서 계속 바꿔봤음

2시간넘게 안됨

개빡쳐서 포기 

다음번에 해야지..(<-- 과연)

728x90

'✍2021,2022 > app(android studio)' 카테고리의 다른 글

H &Y Calendar  (0) 2021.08.11
앱만들기.34 (ViewPager androidx ver)  (0) 2021.08.09
앱만들기.32(constraint Layout)  (0) 2021.08.04
앱만들기.32(VideoView)  (0) 2021.08.04
앱만들기 (캘린더) - 진행 中  (1) 2021.08.03