상세 컨텐츠

본문 제목

Android - 친구 포스팅 가져오기

Android

by yjh0922 2022. 7. 26. 18:03

본문

FollowPostingAdapter 파일

package com.ygh547.posting.adapter;

import android.content.Context;
import android.content.Intent;
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.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.ygh547.posting.PostingListActivity;
import com.ygh547.posting.R;
import com.ygh547.posting.config.Config;
import com.ygh547.posting.model.Posting;

import java.util.List;

public class FollowPostingAdapter extends RecyclerView.Adapter<FollowPostingAdapter.ViewHolder> {

    Context context;
    List<Posting> postingList;

    public FollowPostingAdapter(Context context, List<Posting> postingList) {
        this.context = context;
        this.postingList = postingList;
    }

    @NonNull
    @Override
    public FollowPostingAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.posting_row, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull FollowPostingAdapter.ViewHolder holder, int position) {
        Posting posting = postingList.get(position);
        holder.txtContent.setText(posting.getContent());
        holder.txtUserName.setText(posting.getUsername());
        holder.txtCreatedAt.setText(posting.getCreatedAt());
        holder.txtLikeCnt.setText(""+posting.getLikeCnt());

        if(posting.getIsLike() == 1){
            holder.imgLike.setImageResource(R.drawable.ic_thumb);
        }else{
            holder.imgLike.setImageResource(R.drawable.ic_thumb_off);
        }

        Glide.with(context).load(Config.IMAGE_URL+posting.getImgURL() )
                .placeholder(R.drawable.ic_default_photo)
                .into(  holder.imgPhoto  );

    }

    @Override
    public int getItemCount() {
        return postingList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        CardView cardView;
        TextView txtContent;
        TextView txtUserName;
        TextView txtCreatedAt;
        TextView txtLikeCnt;
        ImageView imgPhoto;
        ImageView imgLike;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            cardView = itemView.findViewById(R.id.cardView);
            txtContent = itemView.findViewById(R.id.txtContent);
            txtUserName = itemView.findViewById(R.id.txtUserName);
            txtCreatedAt = itemView.findViewById(R.id.txtCreatedAt);
            txtLikeCnt = itemView.findViewById(R.id.txtLikeCnt);
            imgPhoto = itemView.findViewById(R.id.imgPhoto);
            imgLike = itemView.findViewById(R.id.imgLike);

            imgLike.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // 메인액티비에 함수 만들어놓고 그 함수 호출하자.
                    int index = getAdapterPosition();
                    ((PostingListActivity)context).setLike(index);
                }
            });
        }
    }
}

 

MainActivity 파일

public class MainActivity extends AppCompatActivity {

    Button btnAdd;
    RecyclerView recyclerView;
    MyPostingAdapter adapter;
    ArrayList<Posting> postingList = new ArrayList<>();
    ProgressBar progressBar;

    private ProgressDialog dialog;

    // 페이징 처리를 위한 멤버변수
    int count = 0;
    int offset = 0;
    int limit = 10;
    
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            SharedPreferences sp = getApplication().getSharedPreferences(Config.PREFERENCES_NAME, MODE_PRIVATE);
            String accessToken = sp.getString("accessToken", "");

            if(accessToken.isEmpty()){

                Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
                startActivity(intent);

                finish();
                return;
            }

            btnAdd = findViewById(R.id.btnAdd);
            recyclerView = findViewById(R.id.recyclerView);
            recyclerView.setHasFixedSize(true);
            recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
            progressBar = findViewById(R.id.progressBar);

            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                    @Override
                    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                        super.onScrolled(recyclerView, dx, dy);

                        int lastPosition = ((LinearLayoutManager)recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
                        int totalCount = recyclerView.getAdapter().getItemCount();

                        if( lastPosition + 1 == totalCount){
                            if(limit == count){
                                // 네트워크 통해서 남아있는 데이터 추가로 가져와라.
                                addNetworkData();
                            }
                        }

                    }
                });

            btnAdd.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(MainActivity.this, AddActivity.class);
                        startActivity(intent);
                    }
                });

            }

            private void addNetworkData() {


                progressBar.setVisibility(View.VISIBLE);

                Retrofit retrofit = NetworkClient.getRetrofitClient(MainActivity.this);
                PostingApi api = retrofit.create(PostingApi.class);

                SharedPreferences sp = getApplication().getSharedPreferences(Config.PREFERENCES_NAME, MODE_PRIVATE);
                String accessToken = sp.getString("accessToken", "");

                Call<PostingList> call = api.getMyPosting("Bearer "+accessToken,
                        offset,
                        limit);
                call.enqueue(new Callback<PostingList>() {
                    @Override
                    public void onResponse(Call<PostingList> call, Response<PostingList> response) {
                        progressBar.setVisibility(View.GONE);
                        if(response.isSuccessful()){

                            count = response.body().getCount();

                            postingList.addAll( response.body().getItems() );

                            offset = offset + count;

                            adapter.notifyDataSetChanged();

                        }else{

                        }
                    }

                    @Override
                    public void onFailure(Call<PostingList> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                    }
                });

            }

            @Override
            protected void onResume() {
                super.onResume();
                getNetworkData();
            }

            // 처음으로 데이터 가져올때
            void getNetworkData(){

                postingList.clear();
                count = 0;
                offset = 0;

                progressBar.setVisibility(View.VISIBLE);

                Retrofit retrofit = NetworkClient.getRetrofitClient(MainActivity.this);
                PostingApi api = retrofit.create(PostingApi.class);

                SharedPreferences sp = getApplication().getSharedPreferences(Config.PREFERENCES_NAME, MODE_PRIVATE);
                String accessToken = sp.getString("accessToken", "");

                Call<PostingList> call = api.getMyPosting("Bearer "+accessToken,
                        offset,
                        limit);
                call.enqueue(new Callback<PostingList>() {
                    @Override
                    public void onResponse(Call<PostingList> call, Response<PostingList> response) {
                        progressBar.setVisibility(View.GONE);
                        if(response.isSuccessful()){

                            count = response.body().getCount();

                            postingList.addAll( response.body().getItems() );

                            offset = offset + count;

                            adapter = new MyPostingAdapter(MainActivity.this, postingList);

                            recyclerView.setAdapter(adapter);

                        }else{

                        }
                    }

                    @Override
                    public void onFailure(Call<PostingList> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                    }
                });
            }
}

 

 

해당 액티비티 디자인 화면

관련글 더보기