Android Retrofit Restful API ve GSON Kullanımı

Projenizin build.gradle (Module: app) içerisindeki dependencies scope'u içerisine aşağıdakileri ekleyin;

implementation 'com.google.code.gson:gson:2.6.2'
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.github.bumptech.glide:glide:4.8.0'
implementation 'com.android.support:cardview-v7:27.1.1'

listview_row.xml layout dosyası üretiniz ve içerisine;

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/ivBlogPhoto"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_alignParentStart="true"
                android:layout_centerVertical="true"
                android:layout_marginStart="16dp"
                app:srcCompat="@drawable/ic_launcher_background" />

            <TextView
                android:id="@+id/tvBlogTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignTop="@+id/ivBlogPhoto"
                android:layout_alignParentStart="true"
                android:layout_marginStart="136dp"
                android:text="TextView"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignStart="@+id/tvBlogTitle"
                android:layout_alignParentBottom="true"
                android:layout_marginStart="-1dp"
                android:layout_marginBottom="54dp"
                android:text="Paylaşım Tarihi" />

            <TextView
                android:id="@+id/tvShareTime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignParentBottom="true"
                android:layout_marginEnd="60dp"
                android:layout_marginBottom="51dp"
                android:text="TextView" />

            <TextView
                android:id="@+id/textView4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignStart="@+id/tvBlogTitle"
                android:layout_alignBottom="@+id/ivBlogPhoto"
                android:layout_marginStart="-1dp"
                android:layout_marginBottom="1dp"
                android:text="Okunma Sayısı" />

            <TextView
                android:id="@+id/tvViewCount"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignTop="@+id/textView4"
                android:layout_alignParentEnd="true"
                android:layout_marginTop="1dp"
                android:layout_marginEnd="60dp"
                android:text="TextView" />
        </RelativeLayout>
    </android.support.v7.widget.CardView>
</RelativeLayout>

activity_main.xml dosyası için;

<RelativeLayout 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=".Activity.MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true" />
</RelativeLayout>

Model paketi oluşturunuz, içerisine BlogResponse ve Blog sınıfları üretiniz.

Blog.java için;

import com.google.gson.annotations.SerializedName;

public class Blog {
    @SerializedName("id")
    private String id;
    @SerializedName("sharetime")
    private String sharetime;
    @SerializedName("updatetime")
    private String updatetime;
    @SerializedName("blog_do_viewcount")
    private String blog_do_viewcount;
    @SerializedName("url")
    private String url;
    @SerializedName("image")
    private String image;
    @SerializedName("blog_seo_title")
    private String blog_seo_title;


    public Blog() {
    }

    public Blog(String id, String sharetime, String updatetime, String blog_do_viewcount, String url, String image, String blog_seo_title) {
        this.id = id;
        this.sharetime = sharetime;
        this.updatetime = updatetime;
        this.blog_do_viewcount = blog_do_viewcount;
        this.url = url;
        this.image = image;
        this.blog_seo_title = blog_seo_title;
    }

    public String getId() {
        return id;
    }

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

    public String getSharetime() {
        return sharetime;
    }

    public void setSharetime(String sharetime) {
        this.sharetime = sharetime;
    }

    public String getUpdatetime() {
        return updatetime;
    }

    public void setUpdatetime(String updatetime) {
        this.updatetime = updatetime;
    }

    public String getBlog_do_viewcount() {
        return blog_do_viewcount;
    }

    public void setBlog_do_viewcount(String blog_do_viewcount) {
        this.blog_do_viewcount = blog_do_viewcount;
    }

    public String getUrl() {
        return url;
    }

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

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getBlog_seo_title() {
        return blog_seo_title;
    }

    public void setBlog_seo_title(String blog_seo_title) {
        this.blog_seo_title = blog_seo_title;
    }
}

BlogResponse.java için;

import com.google.gson.annotations.SerializedName;

import java.util.List;

public class BlogResponse {
    @SerializedName("blogs")
    public List<Blog> getBlogs;

    public List<Blog> getGetBlogs() {
        return getBlogs;
    }

    public void setGetBlogs(List<Blog> getBlogs) {
        this.getBlogs = getBlogs;
    }
}

Interface paketi üretiniz ve içerisine ApiInterface.java dosyası içeriniz. Dosya içeriği olarak aşağıdakileri yazınız;

import com.serifgungor.bloglarilisteleretrofit.Model.BlogResponse;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface ApiInterface {

    @GET("content/api/post/blogs.php")
    Call<BlogResponse> getBloglar(@Query("api_key") String apiKey);
}

Helper paketi üretip, ApiClient.java oluşturun ve içerisine;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    public static final String BASE_URL = "https://serifgungor.com/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient(){
        if(retrofit==null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

        }
        return retrofit;
    }

}

Adapter paketi üretip içerisine, ListViewAdapter.java üretiniz;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.serifgungor.bloglarilisteleretrofit.Model.Blog;
import com.serifgungor.bloglarilisteleretrofit.R;

import java.util.List;

public class ListViewAdapter extends BaseAdapter {

    List<Blog> blogs;
    Context context;
    LayoutInflater layoutInflater;

    public ListViewAdapter(){}

    public ListViewAdapter(Context context, List<Blog> bloglar){
        this.blogs = bloglar;
        this.context = context;
        this.layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return blogs.size();
    }

    @Override
    public Object getItem(int position) {
        return blogs.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = layoutInflater.inflate(R.layout.listview_row,null);

        ImageView ivPhoto = v.findViewById(R.id.ivBlogPhoto);
        TextView tvTitle = v.findViewById(R.id.tvBlogTitle);
        TextView tvShareTime = v.findViewById(R.id.tvShareTime);
        TextView tvViewCount = v.findViewById(R.id.tvViewCount);

        tvTitle.setText(blogs.get(position).getBlog_seo_title());
        tvViewCount.setText(blogs.get(position).getBlog_do_viewcount());
        tvShareTime.setText(blogs.get(position).getSharetime());
        Glide.with(v.getContext()).load("https://serifgungor.com/"+blogs.get(position).getImage()).into(ivPhoto);

        return v;
    }
}

Activity paketi altında MainActivity.java içerisine;


import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

import com.serifgungor.bloglarilisteleretrofit.Adapter.ListViewAdapter;
import com.serifgungor.bloglarilisteleretrofit.Helper.ApiClient;
import com.serifgungor.bloglarilisteleretrofit.Interface.ApiInterface;
import com.serifgungor.bloglarilisteleretrofit.Model.Blog;
import com.serifgungor.bloglarilisteleretrofit.Model.BlogResponse;
import com.serifgungor.bloglarilisteleretrofit.R;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    ListView listView;
    ListViewAdapter adapter;

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

        listView = findViewById(R.id.listView);

        ApiInterface apiService =ApiClient.getClient().create(ApiInterface.class);

        Call<BlogResponse> call = apiService.getBloglar("");
        call.enqueue(new Callback<BlogResponse>() {
            @Override
            public void onResponse(Call<BlogResponse> call, Response<BlogResponse> response) {
                List<Blog> bloglar = response.body().getGetBlogs();

                adapter = new ListViewAdapter(getApplicationContext(),bloglar);
                listView.setAdapter(adapter);

            }

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

            }
        });

    }
}

Bu makaleyi paylaşın:

3 Comments

Bir yorum bırakın