2swan

Retrofit 예제 본문

Programming/Android Example

Retrofit 예제

2swan 2023. 8. 9. 17:01

AndroidManifest.xml, Gradle Scripts 파일에 추가

 

main.xml

<?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"
    android:orientation="vertical"
    tools:context=".MainActivity">

<Button
    android:id="@+id/btnPhoto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Photo Button"/>

    <Button
        android:id="@+id/btnPost"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Post Button"/>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>


</LinearLayout>

 

item_list.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"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:padding="10dp"/>

    <TextView
        android:id="@+id/txId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textSize="20sp"/>

    <TextView
        android:id="@+id/txTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textSize="20sp"/>

    <TextView
        android:id="@+id/txUrl"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textSize="20sp"/>


</LinearLayout>

main.activity

public class MainActivity extends AppCompatActivity {
            private  PhotoInterface photoInterface;

            private  PhotoInterface postInterface;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnPhoto = findViewById(R.id.btnPhoto);
        Button btnPost = findViewById(R.id.btnPost);

        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,false);

        recyclerView.setLayoutManager(linearLayoutManager);




        btnPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ArrayList<Photo>photolist = new ArrayList<>();
                PhotoAdapter photoAdapter = new PhotoAdapter(photolist);
                recyclerView.setAdapter(photoAdapter);

                photoInterface = PhotoClient.getClient().create(PhotoInterface.class);
               Call<List<Photo>> call = photoInterface.doGetPhotos();
               call.enqueue(new Callback<List<Photo>>() {
                   @Override
                   public void onResponse(Call<List<Photo>> call, Response<List<Photo>> response) {
                       List<Photo> resource  = response.body();
                       Log.d(">>>photoAdapter size : ", resource.size()+ " " );
                       for(Photo photo : resource){
                           photolist.add(photo);
                       }
                       photoAdapter.notifyDataSetChanged();
                   }

                   @Override
                   public void onFailure(Call<List<Photo>> call, Throwable t) {

                   }
               });
            }
        });

        btnPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ArrayList<Post>postlist = new ArrayList<>();
                PostAdapter postAdapter = new PostAdapter(postlist);
                recyclerView.setAdapter(postAdapter);
                postInterface = PhotoClient.getClient().create(PhotoInterface.class);

                    Call<List<Post>>call = postInterface.doGetPosts();
                    call.enqueue(new Callback<List<Post>>() {
                        @Override
                        public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
                            List<Post> resource = response.body();
                            for(Post post : resource){
                                postlist.add(post);
                            }
                            postAdapter.notifyDataSetChanged();
                        }

                        @Override
                        public void onFailure(Call<List<Post>> call, Throwable t) {

                        }
                    });
            }
        });


    }
}

 

Photo.java

public class Photo {
    private  int albumId;
    private  int id;
    private  String title;

    private  String url;
    private  String thumbnailUrl;

    public Photo(int albumId, int id, String title, String url, String thumbnailUrl) {
        this.albumId = albumId;
        this.id = id;
        this.title = title;
        this.url = url;
        this.thumbnailUrl = thumbnailUrl;
    }

    public int getAlbumId() {
        return albumId;
    }

    public void setAlbumId(int albumId) {
        this.albumId = albumId;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getThumbnailUrl() {
        return thumbnailUrl;
    }

    public void setThumbnailUrl(String thumbnailUrl) {
        this.thumbnailUrl = thumbnailUrl;
    }
}

 

PhotoAdapter.java

public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.PhotoViewHolder> {

    private ArrayList<Photo> photoList;

    public PhotoAdapter(ArrayList<Photo> photoList) {
        this.photoList = photoList;
    }

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

    @Override
    public void onBindViewHolder(@NonNull PhotoViewHolder holder, int position) {
                Photo photo = photoList.get(position);
//             holder.imageView.setImageResource(R.drawable.ic_launcher_background);
                Glide.with(holder.itemView)
                                .load(photo.getThumbnailUrl())
                                        .into(holder.imageView);
                holder.txId.setText(Integer.toString(photo.getId()));
//             holder.txId.setText(photo.getId()+"");      <- 이 방식도 가능하다 (문자열을 넣어서)
                holder.txTitle.setText(photo.getTitle());
                holder.txUrl.setText(photo.getUrl());
    }

    @Override
    public int getItemCount() {
        return photoList == null ? 0 : photoList.size();
    }

    class  PhotoViewHolder extends  RecyclerView.ViewHolder{
        TextView txId, txTitle, txUrl;
        ImageView imageView;
        View itemView;
        public PhotoViewHolder(@NonNull View itemView) {
            super(itemView);
            this.itemView = itemView;
            this.txId = itemView.findViewById(R.id.txId);
            this.txTitle = itemView.findViewById(R.id.txTitle);
            this.txUrl = itemView.findViewById(R.id.txUrl);
            this.imageView = itemView.findViewById(R.id.imageView);
        }
    }
}

 

PhotoClient.java

public class PhotoClient {
    private  static Retrofit retrofit;
    static  Retrofit getClient(){
        retrofit = new Retrofit.Builder()
                .baseUrl("https://jsonplaceholder.typicode.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        return  retrofit;
    }
}

 

PhotoInterface.java

public interface PhotoInterface {
    @GET("photos/")
    Call<List<Photo>> doGetPhotos();

    @GET("posts/")
    Call<List<Post>> doGetPosts();
}

결과 값

'Programming > Android Example' 카테고리의 다른 글

Progressbar  (0) 2023.08.09
음악 듣기 예제  (0) 2023.08.09
Tab 예제  (0) 2023.08.09
슬라이드 예제 2  (0) 2023.08.09
가로(세로) 슬라이드  (0) 2023.08.09