// ItemData.java
import java.util.HashMap;
import java.util.Map;
public class ItemData {
private String image; //int to String
private String title;
private String contents;
public ItemData() { } // 기본생성자
public ItemData(String image, String title, String contents) {
this.image = image; //int to String
this.title = title;
this.contents = contents;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
// 새로추가됨
public Map<String, Object> toMap(){
HashMap<String, Object> result = new HashMap<>();
result.put("image", image);
result.put("title", title);
result.put("contents", contents);
return result;
}
//새로추가됨 끝
}
build.gradle 에 추가
implementation 'com.github.bumptech.glide:glide:4.10.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
MyRecyclerAdapter.java
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.ViewHolder>{
private ArrayList<ItemData> itemData;
//생성자
public MyRecyclerAdapter(ArrayList<ItemData> itemData) {
this.itemData = itemData;
}
// 이벤트 처리 인터페이스 생성
public interface MyRecyclerViewClickListener{
void onItemClicked(int position);
void onItemLongClicked(int position);
void onTitleClicked(int position);
void onContentsClicked(int position);
void onImageViewClicked(int position);
}
private MyRecyclerViewClickListener mListener;
public void setOnClickListener(MyRecyclerViewClickListener listener){
this.mListener = listener;
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
TextView contents;
ImageView imageView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.title_text);
contents = itemView.findViewById(R.id.contents_text);
imageView = itemView.findViewById(R.id.imageView);
imageView.setBackground(new ShapeDrawable(new OvalShape()));
imageView.setClipToOutline(true);
}
}
@NonNull
@Override
public MyRecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull final MyRecyclerAdapter.ViewHolder holder, int position) {
ItemData item = itemData.get(position);
holder.title.setText(item.getTitle());
holder.contents.setText(item.getContents());
//holder.imageView.setImageResource(item.getImage());
Glide.with(holder.itemView)
.load(item.getImage())
.into(holder.imageView);
// 이벤트 처리 관련 리스너 처리
if(mListener != null){
final int pos = position;
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onItemClicked(pos);
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
mListener.onItemLongClicked(holder.getAdapterPosition());
// remove(holder.getAdapterPosition());
return true;
}
});
holder.title.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onTitleClicked(holder.getAdapterPosition());
}
});
holder.contents.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onContentsClicked(holder.getAdapterPosition());
}
});
holder.imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onImageViewClicked(pos);
}
});
}
}
@Override
public int getItemCount() {
return itemData.size();
}
public void remove(int position){
try {
itemData.remove(position);
notifyDataSetChanged();
} catch (IndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
MainActivity.java
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
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.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements MyRecyclerAdapter.MyRecyclerViewClickListener {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<ItemData> dataList;
private FirebaseDatabase database;
private DatabaseReference databaseReference;
private MyRecyclerAdapter adapter;
String IMAGE_URL="https://firebasestorage.googleapis.com/v0/b/recyclerviewex-b819d.appspot.com/o/pic_013.jpg?alt=media&token=611fca00-4b2d-497f-86df-7d9ce2a8a2be";
static int i=0;
@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);
dataList = new ArrayList<>();
database = FirebaseDatabase.getInstance(); // 파이어베이스 데이터베이스 연동
databaseReference = database.getReference("CAT"); //DB 테이블 연결
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//파이어 베이스 데이터베이스에 데이터를 받아오는곳
dataList.clear(); //기존 배열 리스트가 존재하지 않게 초기화
for(DataSnapshot snapshot : dataSnapshot.getChildren()){ //반복문으로 데이터List 추출
ItemData itemData = snapshot.getValue(ItemData.class); // 만들어둔 ItemData 객체에 데이터를 담는다.
dataList.add(itemData); // 담은 데이터를 배열리스트에 넣고 리사이클러 뷰로 보냄
}
adapter.notifyDataSetChanged(); //리스트 저장 및 새로 고침
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e("MainActivity", String.valueOf(databaseError.toException()));
}
});
adapter = new MyRecyclerAdapter(dataList);
recyclerView.setAdapter(adapter);
Button button_add = findViewById(R.id.button_add);
button_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String title = "CAT"+Integer.toString(i);
String contents = "예쁨";
if(!IsExistTITLE(title)){
postItemData(true, title, contents);
getFirebaseDatabase();
}else{
Toast.makeText(getApplicationContext(), "이미 존재하는 ID 입니다. 다른 ID로 설정해주세요.",
Toast.LENGTH_LONG).show();
}
}
});
adapter.setOnClickListener(this);
}
@Override
public void onItemClicked(int position) {
Toast.makeText(getApplicationContext(),""+position, Toast.LENGTH_SHORT).show();
}
@Override
public void onTitleClicked(int position) {
Toast.makeText(getApplicationContext(),""+dataList.get(position).getTitle(), Toast.LENGTH_SHORT).show();
}
@Override
public void onContentsClicked(int position) {
Toast.makeText(getApplicationContext(),""+dataList.get(position).getContents(), Toast.LENGTH_SHORT).show();
}
@Override
public void onImageViewClicked(int position) {
Toast.makeText(getApplicationContext(),""+dataList.get(position).getImage(),Toast.LENGTH_SHORT).show();
}
@Override
public void onItemLongClicked(int position) {
adapter.remove(position);
Toast.makeText(getApplicationContext(),
dataList.get(position).getTitle()+" is removed",Toast.LENGTH_SHORT).show();
}
public void onMenuInsert(View view) {
// final View innerView = getLayoutInflater().inflate(R.layout.list_insert,null);
final Dialog mDialog = new Dialog(this);
mDialog.setTitle("Title");
mDialog.setContentView(R.layout.list_insert);
mDialog.setCancelable(true);
// //DialogSize조절
WindowManager.LayoutParams params = mDialog.getWindow().getAttributes();
params.width = WindowManager.LayoutParams.MATCH_PARENT;
// params.height = WindowManager.LayoutParams.MATCH_PARENT;
mDialog.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
final EditText contents_edittext = mDialog.findViewById(R.id.contents_edittext);
final EditText title_edittext = mDialog.findViewById(R.id.title_edittext);
ImageView imageView_insert = mDialog.findViewById(R.id.imageView_insert);
Button button_go = mDialog.findViewById(R.id.button_go);
Button button_cancel = mDialog.findViewById(R.id.button_cancel);
button_go.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String mMenuTitle = title_edittext.getText().toString();
String mMenuContents = contents_edittext.getText().toString();
// dataList.add(new ItemData(IMAGE_URL, mMenuTitle, mMenuContents));
postItemData(true, "CAT"+mMenuTitle, mMenuContents);
getFirebaseDatabase();
mDialog.dismiss();
}
});
button_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDialog.dismiss();
}
});
i = (i+1)%35;
mDialog.show();
adapter.notifyDataSetChanged();
}
public void postItemData(boolean add, String title, String content){
databaseReference = FirebaseDatabase.getInstance().getReference();
Map<String, Object> childUpdates = new HashMap<>();
Map<String, Object> postValues = null;
IMAGE_URL = "https://firebasestorage.googleapis.com/v0/b/recyclerviewex-b819d.appspot.com/o/pic_013.jpg?alt=media&token=611fca00-4b2d-497f-86df-7d9ce2a8a2be";
// TITLE = "CAT"+Integer.toString(i);
// CONTENTS = "예쁨";
if(add){
ItemData itemData = new ItemData(IMAGE_URL, title, content);
postValues = itemData.toMap();
}
childUpdates.put("/CAT/" + title, postValues);
databaseReference.updateChildren(childUpdates);
i++;
}
public void getFirebaseDatabase(){
ValueEventListener postListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataList.clear(); //기존 배열 리스트가 존재하지 않게 초기화
for(DataSnapshot snapshot : dataSnapshot.getChildren()){ //반복문으로 데이터List 추출
ItemData itemData = snapshot.getValue(ItemData.class); // 만들어둔 ItemData 객체에 데이터를 담는다.
dataList.add(itemData); // 담은 데이터를 배열리스트에 넣고 리사이클러 뷰로 보냄
}
adapter.notifyDataSetChanged(); //리스트 저장 및 새로 고침
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w("getFirebaseDatabase","loadPost:onCancelled", databaseError.toException());
}
};
}
public boolean IsExistTITLE(String title){
boolean IsExist = dataList.contains(title);
return IsExist;
}
public String setTextLength(String text, int length){
if(text.length()<length){
int gap = length - text.length();
for (int i=0; i<gap; i++){
text = text + " ";
}
}
return text;
}
}
'PROGRAM > Android' 카테고리의 다른 글
Android Studio 4.1 Installation (0) | 2020.10.19 |
---|---|
MyMemo exam (0) | 2020.05.30 |
firebase db (0) | 2020.05.23 |
리사이클러뷰-full (0) | 2020.05.10 |
리사이클러뷰 (0) | 2020.05.10 |