Menampilkan Data Menggunakan RecyclerView (Retrofit) Part 1


Hello Sobat, Hari ini saya akan memberikan tutorial untuk menampilkan data menggunakan RecylerView dengan  HTTP REQUEST menggunakan library Retrofit untuk lebih jelasnya mengenai library ini sobat bisa kunjungi situs resminya disini, Tanpa berpikir panjang karna saya sudah kehabisan kata-kata saya akan memberikan langkah-langkah untuk membuat aplikasinya perhatikan iya.

Membuat Databases
Sobat copy code databases dibawah ke mysql



/* Navicat MySQL Data Transfer Source Server : tanwir Source Server Version : 50624 Source Host : localhost:3306 Source Database : db_blogspot Target Server Type : MYSQL Target Server Version : 50624 File Encoding : 65001 Date: 2017-07-03 09:16:54 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for siswa -- ---------------------------- DROP TABLE IF EXISTS `siswa`; CREATE TABLE `siswa` ( `nis` int(11) NOT NULL, `nama` varchar(255) DEFAULT NULL, PRIMARY KEY (`nis`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- ---------------------------- -- Records of siswa -- ---------------------------- INSERT INTO `siswa` VALUES ('1111', 'CodeTR'); INSERT INTO `siswa` VALUES ('2222', 'Randi'); INSERT INTO `siswa` VALUES ('3333', 'Tanwir'); INSERT INTO `siswa` VALUES ('5555', 'Hama'); INSERT INTO `siswa` VALUES ('6666', 'Cinta'); INSERT INTO `siswa` VALUES ('7777', 'Naruto'); INSERT INTO `siswa` VALUES ('8888', 'Budi'); INSERT INTO `siswa` VALUES ('9999', 'Tutu'); INSERT INTO `siswa` VALUES ('67676', 'hgfh');

Membuat API menggunakan PHP
Sesuaikan dengan nama yang diberikan
  • koneksi.php
PHP

<?php
// deklarasi variable untuk koneksi ke MySQL
$hostname = "localhost";
$username = "root";
$password = "";
$database = "db_blogspot";

// membuat koneksi ke MySQL
$status = mysqli_connect($hostname, $username, $password, $database);
if (!$status){
die("Koneksi ke MySQL gagal dilakukan!<br>");
}
?>
  • siswa.php
PHP

<?php if($_SERVER['REQUEST_METHOD']=='GET'){ require_once('koneksi.php'); $sql = "SELECT * FROM siswa"; $result = mysqli_query($status,$sql); $total_results = mysqli_num_rows($result); $res = array(); if ($total_results == 0){ array_push($res, array("pesan"=>"Data tidak ada..!!!", $total_results)); }else{ while($row = mysqli_fetch_array($result)){ array_push($res, array("nis"=>$row['nis'],"nama"=>$row['nama'],"jmhdata"=>$total_results)); } } echo json_encode($res); mysqli_close($status); } ?>

Android Studio
Selanjutnya masuk ke tools android studio buat project baru 
  • Membuat desian layout denga struktur sebagai berikut

  • Masukan source code xml dibagian content_main.xml


<?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" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/content_main" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:context="com.codetr.tanwir.codetr.MainActivity" 
    tools:showIn="@layout/activity_main"> 
 
    <android.support.v7.widget.RecyclerView 
        android:id="@+id/ryView" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent" 
        android:scrollbars="none" /> 
 
</RelativeLayout> 
  • Membuat item dengan nama item_siswa.xml dan masukan source code berikut


<?xml version="1.0" encoding="utf-8"?><!-- 
  ~ Copyright (c) 2016. Tanwir. All Rights Reserver. 
  ~ <p> 
  ~ Save to the extent permitted by law, you may not use,copy,modify, 
  ~ distribute or create derivative works of this material or any part 
  ~ of it without the prior written consent of Tanwir. 
  ~ <p> 
  ~ The above copyright notice and this permission notice shall be included in 
  ~ all copies or substantial portions of the Software. 
  --> 
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 
 
    <RelativeLayout 
        android:layout_width="match_parent" 
        android:layout_height="80dp"> 
 
        <ImageView 
            android:id="@+id/tvPhoto" 
            android:layout_width="60dp" 
            android:layout_height="60dp" 
            android:layout_margin="8dp" 
            android:scaleType="centerCrop" 
            android:src="@mipmap/ic_launcher" /> 
 
        <LinearLayout 
            android:layout_width="match_parent" 
            android:layout_height="wrap_content" 
            android:layout_alignParentBottom="true" 
            android:layout_alignParentEnd="true" 
            android:layout_alignParentRight="true" 
            android:layout_alignParentTop="true" 
            android:layout_marginLeft="80dp" 
            android:gravity="center_vertical" 
            android:orientation="horizontal"> 
 
 
            <LinearLayout 
                android:layout_width="wrap_content" 
                android:layout_height="match_parent" 
                android:gravity="center_vertical" 
                android:orientation="vertical"> 
 
                <TextView 
                    android:layout_width="wrap_content" 
                    android:layout_height="wrap_content" 
                    android:ellipsize="end" 
                    android:maxLines="1" 
                    android:paddingRight="16dp" 
                    android:text="Nis" /> 
 
                <TextView 
                    android:layout_width="wrap_content" 
                    android:layout_height="wrap_content" 
                    android:layout_marginTop="10dp" 
                    android:paddingRight="16dp" 
                    android:text="Nama " /> 
 
            </LinearLayout> 
 
            <LinearLayout 
                android:layout_width="wrap_content" 
                android:layout_height="match_parent" 
                android:layout_weight="1" 
                android:gravity="center_vertical" 
                android:orientation="vertical"> 
 
                <TextView 
                    android:id="@+id/tvNis" 
                    android:layout_width="match_parent" 
                    android:layout_height="wrap_content" 
                    android:ellipsize="end" 
                    android:maxLines="1" 
                    android:paddingRight="16dp" /> 
 
                <TextView 
                    android:id="@+id/tvNama" 
                    android:layout_marginTop="10dp" 
                    android:layout_width="match_parent" 
                    android:layout_height="wrap_content" 
                    android:paddingRight="16dp" /> 
 
            </LinearLayout> 
        </LinearLayout> 
 
    </RelativeLayout> 
    <View 
        android:layout_width="match_parent" 
        android:background="@android:color/darker_gray" 
        android:layout_height="1dp"/> 
</LinearLayout>
  • Jika sudah selesai melakukan design pada tampilan layout selanjutnya melakukan penambahan uses permission pada Manifest


<uses-permission android:name="android.permission.INTERNET" />
  • Menambahkan library di bagian gridle


compile 'com.android.support:recyclerview-v7:25.3.1'compile 'com.squareup.retrofit2:retrofit:2.1.0'compile 'com.squareup.retrofit2:converter-gson:2.1.0'

  • Perhatikan struktur folder code java
  • Tambahkan di folder adapter dengan nama SAdapter.java dan masukan source code


/* * Copyright (c) 2016. Tanwir. All Rights Reserver. * <p> * Save to the extent permitted by law, you may not use,copy,modify, * distribute or create derivative works of this material or any part * of it without the prior written consent of Tanwir. * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. */
package com.codetr.tanwir.codetr.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.codetr.tanwir.codetr.R;
import com.codetr.tanwir.codetr.model.Siswa;
import java.util.ArrayList;
import java.util.List;


/** * * Created by tanwir on 01/07/2017. */ public class SAdapter extends RecyclerView.Adapter<SAdapter.Holder> {
    private final SiswaClickListener nListener;
    private List<Siswa> lSiswa;


    public SAdapter(SiswaClickListener listener) {
        lSiswa = new ArrayList<>();
        nListener = listener;
    }

    @Override
    public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
        View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.items_siswa, parent, false);
        return new Holder(row);
    }

    @Override
    public void onBindViewHolder(Holder holder, int position) {
        Siswa setSiswa = lSiswa.get(position);

//        Picasso.with(holder.itemView.getContext()).load(setSiswa.getPhoto()).error(R.drawable.ic_error_outline_black_48dp).resize(100,100).into(holder.mPhoto);        holder.tvNis.setText(setSiswa.getNis());
        holder.tvNama.setText(setSiswa.getNama());
    }

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

    public void addSiswa(Siswa siswa) {
        lSiswa.add(siswa);
        notifyDataSetChanged();
    }


    /**     * @return     */
    public Siswa getSiswa(int position) {
        return lSiswa.get(position);
    }

    public class Holder extends RecyclerView.ViewHolder{

        private ImageView mPhoto;
        private TextView tvNis, tvNama, tvJk;

        public Holder(View itemView) {
            super(itemView);
            mPhoto = (ImageView) itemView.findViewById(R.id.tvPhoto);
            tvNis = (TextView) itemView.findViewById(R.id.tvNis);
            tvNama = (TextView) itemView.findViewById(R.id.tvNama);
        }
    }
}
  • Tambahkan di folder model dengan nama Siswa.java dan masukan sourcode


/* * Copyright (c) 2016. Tanwir. All Rights Reserver. * <p> * Save to the extent permitted by law, you may not use,copy,modify, * distribute or create derivative works of this material or any part * of it without the prior written consent of Tanwir. * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. */
package com.codetr.tanwir.codetr.model;

/** * * Created by tanwir on 01/07/2017. */public class Siswa {
    public String nis;
    public String nama;
    public String photo;

    public String getNis() {
        return nis;
    }

    public void setNis(String nis) {
        this.nis = nis;
    }

    public String getNama() {
        return nama;
    }

    public void setNama(String nama) {
        this.nama = nama;
    }

    public String getPhoto() {
        return photo;
    }

    public void setPhoto(String photo) {
        this.photo = photo;
    }
}
  • Tambahkan di folder network tiga file java dengan nama Config.java, DataProvider.java dan DataService.java dan masukan sourecode
Config.java


/* * Copyright (c) 2016. Tanwir. All Rights Reserver. * <p> * Save to the extent permitted by law, you may not use,copy,modify, * distribute or create derivative works of this material or any part * of it without the prior written consent of Tanwir. * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. */
package com.codetr.tanwir.codetr.network;

/** * * Created by tanwir on 01/07/2017. */public class Config {
    public static final String BASE_URL = "https://blogspot-wtanwir.c9users.io/";
}

DataProvider.java


/* * Copyright (c) 2016. Tanwir. All Rights Reserver. * <p> * Save to the extent permitted by law, you may not use,copy,modify, * distribute or create derivative works of this material or any part * of it without the prior written consent of Tanwir. * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. */
package com.codetr.tanwir.codetr.network;

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

/** * * Created by tanwir on 01/07/2017. */public class DataProvider {
    private DataService nService;
    private Retrofit mRetrofitClient;

    /**     * config Retrofit in initialization     */    public DataProvider() {

        OkHttpClient httpClient = new OkHttpClient();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Config.BASE_URL)
                .client(httpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        nService = retrofit.create(DataService.class);
    }


    public DataService getTService() {
        return nService;
    }

    public Retrofit getRetrofitClient() {
        return mRetrofitClient;
    }
}

DataService.java


/* * Copyright (c) 2016. Tanwir. All Rights Reserver. * <p> * Save to the extent permitted by law, you may not use,copy,modify, * distribute or create derivative works of this material or any part * of it without the prior written consent of Tanwir. * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. */
package com.codetr.tanwir.codetr.network;

import com.codetr.tanwir.codetr.model.Siswa;

import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;

/** * * Created by tanwir on 01/07/2017. */public interface DataService {
    @GET("siswa.php")
    Call<List<Siswa>> getSiswa();
}
  • Dibagian Mainactivity.java tambahkan source code


package com.codetr.tanwir.codetr;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.MenuItemCompat;
import android.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.Toast;

import com.codetr.tanwir.codetr.adapter.DialogAdapter;
import com.codetr.tanwir.codetr.adapter.SAdapter;
import com.codetr.tanwir.codetr.model.Siswa;
import com.codetr.tanwir.codetr.network.DataProvider;
import com.codetr.tanwir.codetr.network.DataService;

import java.util.ArrayList;
import java.util.List;

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

public class MainActivity extends AppCompatActivity{

    public static MainActivity activity;
    public static DataService nService;
    private RecyclerView mRecycleView;
    private SAdapter siswaAdapter;
    private List<Siswa> siswaList;
    private Siswa siswa;

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("Data Siswa");
        toolbar.setLogo(R.mipmap.ic_launcher);
        setSupportActionBar(toolbar);

        mRecycleView = (RecyclerView) findViewById(R.id.ryView);
        DataProvider provider = new DataProvider();
        nService = provider.getTService();

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                
            }
        });

        ShowSiswa();

    }

    public void ShowSiswa() {
        configViews();
        Call<List<Siswa>> call = nService.getSiswa();
        call.enqueue(new Callback<List<Siswa>>() {
                         @Override
                         public void onResponse(Call<List<Siswa>> call, Response<List<Siswa>> response) {
                             if (response.isSuccessful()) {
                                 siswaList = response.body();
                                 for (int i = 0; i < siswaList.size(); i++) {
                                     siswa = siswaList.get(i);
                                     siswaAdapter.addSiswa(siswa);
                                 }
                             }
                         }

                         @Override
                         public void onFailure(Call<List<Siswa>> call, Throwable t) {
                             Toast.makeText(MainActivity.this, "Tidak ada koneksi", Toast.LENGTH_SHORT).show();
                         }
                     }
        );
    }

    private void configViews() {
        mRecycleView.setHasFixedSize(true);
        mRecycleView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        mRecycleView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        siswaAdapter = new SAdapter(this);
        mRecycleView.setAdapter(siswaAdapter);
    }
    @Override public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_refresh) {
            ShowSiswa();
            Toast.makeText(this, "Refresh", Toast.LENGTH_SHORT).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Hasil Output



Untuk lebih jelasnya lihat vidio dibawah 



Sekian artikel dari saya semoga bermanfaat, jika ada yang ditanyakan comment saja di bawah.

Comments

Popular posts from this blog

PRIVACY POLICY - APLICATION BELMANDIYSAH

PRIVACY POLICY BELMANDIYSAH