Menampilkan Data Menggunakan RecyclerView (Volley) Part 1


Hello sobat, hari ini saya akan berbagi tutorial mengenai library volley, apa itu volley merupakan library yang digunakan untuk memudahkan pertukaran data tanpa harus menulis code begitu panjang dan membuat code berulang-ulang, volley juga menggunakan metode singkronisasi atau asynctask jadi jika menggunakan volley tidak perlu membuat method class asycntask secara manual lagi. Mungkin itu sekilas penjelasan mengenai library volley, baik untuk langkah selanjutnya kita akan membuat aplikasi.

Database
Membuat databases, sesuaikan dengan nama supaya tidak terjadi error saat aplikasi dijalankan

  • connection.php
<?php 
 define('HOSTNAME', 'localhost');
 define('USERNAME', 'root');
 define('PASSWORD', '');
 define('DB_SELECT', 'db_blogspot');

 $koneksi = new mysqli(HOSTNAME,USERNAME,PASSWORD,DB_SELECT) or die (mysqli_errno());

 if(!$koneksi){
  die("Koneksi ke MySQL gagal dilakukan!<br>");
 }
 ?>
  • create_data.php
<?php 
 include_once('connection.php'); 

 $nis =$_POST['nis'];
 $nama=$_POST['nama'];

 $insert = "INSERT INTO siswa (nis,nama) VALUES ('$nis','$nama')";
 $exeinsert = mysqli_query($koneksi,$insert);
 $response = array();

 if($exeinsert){
  $response['code'] =1;
  $response['message'] = "Berhasil disimpan";
 }else{
  $response['code'] =0;
  $response['message'] = "Gagal disimpan";
 }
  echo json_encode($response);

 ?>
  • delete_data.php
<?php 
 include_once('connection.php');

 $nis = $_POST['nis']; 

 $getdata = mysqli_query($koneksi,"SELECT * FROM siswa WHERE nis ='$nis'");
 $rows = mysqli_num_rows($getdata);

 $delete = "DELETE FROM siswa WHERE nis ='$nis'";
 $exedelete = mysqli_query($koneksi,$delete);

 $respose = array();

 if($rows > 0){
  if($exedelete){
   $respose['code'] =1;
   $respose['message'] = "Berhasil dihapus";
  }else{
   $respose['code'] =0;
   $respose['message'] = "Gagal dihapus";
  }
 }else{
  $respose['code'] =0;
  $respose['message'] = "Data tidak ada";
 }
 echo json_encode($respose);

 ?>
  • update_data.php
<?php  
 include_once('connection.php'); 

 $nis = $_POST['nis'];
 $nama = $_POST['nama'];

 $getdata = mysqli_query($koneksi,"SELECT * FROM siswa WHERE nis ='$nis'"); 
 $rows = mysqli_num_rows($getdata);
 
 $respose = array();

 if($rows > 0 ){
  $query = "UPDATE siswa SET nama='$nama' WHERE nis='$nis'";
  $exequery = mysqli_query($koneksi,$query);
  if($exequery){
    $respose['code'] =1;
    $respose['message'] = "Behasil diubah";
  }else{
    $respose['code'] =0;
    $respose['message'] = "Gagal diubah";
  }
 }else{
    $respose['code'] =0;
    $respose['message'] = "Data tidak ditemukan";
 }

 echo json_encode($respose);
?>
  • view_data.php
<?php 
 include_once('connection.php'); 

 $query = "SELECT * FROM siswa";
 $result = mysqli_query($koneksi,$query);

 $arraydata = array();

 while($baris = mysqli_fetch_assoc($result))
 {
  $arraydata[]= $baris;
 }

 echo json_encode($arraydata);

 ?>

Manifest
Menambahkan uses permission pada manifest
    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
Gradle
Menambahkan library volley dan library pendukung pada gradle aplikasi
    compile 'com.android.volley:volley:1.0.0' 
    compile 'com.android.support:design:25.3.1' 
    compile 'com.android.support:recyclerview-v7:25.3.1' 
    compile 'com.android.support:cardview-v7:25.3.1'
Design Layout
Membuat design layout dengan struktur


  • Masukan code xml pada layout.row.xml 
<?xml version="1.0" encoding="utf-8"?> 
<android.support.v7.widget.CardView 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:layout_marginBottom="8dp" 
    android:layout_margin="10dp" 
    app:cardCornerRadius="5dp" 
    app:cardElevation="3dp"> 
 
    <RelativeLayout 
        android:padding="20dp" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content"> 
 
        <RelativeLayout 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:layout_centerInParent="true"> 
 
            <TextView 
                android:textColor="@android:color/black" 
                android:id="@+id/NIS" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:text="NIS" /> 
 
            <TextView 
                android:layout_marginTop="10dp" 
                android:id="@+id/NAMA" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:layout_below="@id/NIS" 
                android:text="NAMA" /> 
 
        </RelativeLayout> 
    </RelativeLayout> 
</android.support.v7.widget.CardView>
  • Masukan code xml pada activity_main.xml
<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 
 
    <LinearLayout 
        android:layout_width="match_parent" 
        android:layout_height="match_parent" 
        android:alpha="0.2" 
        android:background="@color/colorAccent" /> 
 
    <android.support.v7.widget.RecyclerView 
        android:id="@+id/rvSiswa" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent" 
        android:layout_margin="5dp" /> 
 
    <android.support.design.widget.FloatingActionButton 
        android:id="@+id/btn_insert" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:layout_alignParentBottom="true" 
        android:layout_alignParentRight="true" 
        android:layout_margin="@dimen/fab" 
        android:src="@drawable/ic_add_white_24dp" /> 
</RelativeLayout>
Package Java
Membuat package dengan struktur 


  • Masukan code dalam class AdapterData.java
package com.codetr.tanwir.crudvolley.Adapter; 
 
import android.content.Context; 
import android.content.Intent; 
import android.support.v7.widget.RecyclerView; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.TextView; 
import android.widget.Toast; 
 
import com.codetr.tanwir.crudvolley.InsertData; 
import com.codetr.tanwir.crudvolley.Model.ModelData; 
import com.codetr.tanwir.crudvolley.R; 
 
import java.util.List; 
 
public class AdapterData extends RecyclerView.Adapter<AdapterData.HolderData> { 
    private List<ModelData> mItems; 
    private Context context; 
 
    public AdapterData(Context context, List<ModelData> items) { 
        this.mItems = items; 
        this.context = context; 
    } 
 
    @Override 
    public HolderData onCreateViewHolder(ViewGroup parent, int viewType) { 
        View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_row, parent, false); 
        HolderData holderData = new HolderData(layout); 
        return holderData; 
    } 
 
    @Override 
    public void onBindViewHolder(HolderData holder, int position) { 
        ModelData md = mItems.get(position); 
        holder.tvNIS.setText(md.getNis()); 
        holder.tvNAMA.setText(md.getNama()); 
 
        holder.md = md; 
    } 
 
    @Override 
    public int getItemCount() { 
        return mItems.size(); 
    } 
 
 
    class HolderData extends RecyclerView.ViewHolder { 
        TextView tvNIS, tvNAMA; 
        ModelData md; 
 
        public HolderData(View view) { 
            super(view); 
 
            tvNIS = (TextView) view.findViewById(R.id.NIS); 
            tvNAMA = (TextView) view.findViewById(R.id.NAMA); 
 
            view.setOnClickListener(new View.OnClickListener() { 
                @Override 
                public void onClick(View view) { 
                    Intent update = new Intent(context, InsertData.class); 
                    update.putExtra("update",1); 
                    update.putExtra("nis",md.getNis()); 
                    update.putExtra("nama",md.getNama()); 
                    context.startActivity(update); 
                } 
            }); 
        } 
    } 
}
  • Masukan code dalam class ModelData.java
package com.codetr.tanwir.crudvolley.Model; 
 
 
public class ModelData { 
    String nis, nama; 
 
    public ModelData() { 
    } 
 
    public ModelData(String nis, String nama) { 
        this.nis = nis; 
        this.nama = nama; 
    } 
 
    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; 
    } 
} 
  • Masukan code pada AppController.java
package com.codetr.tanwir.crudvolley.Util; 
 
import android.app.Application; 
import android.text.TextUtils; 
 
import com.android.volley.Request; 
import com.android.volley.RequestQueue; 
import com.android.volley.toolbox.Volley; 
 
public class AppController extends Application { 
    private static final String TAG = AppController.class.getSimpleName(); 
    private static AppController instance; 
    RequestQueue mRequestQueue; 
 
    @Override 
    public void onCreate() { 
        super.onCreate(); 
        instance = this; 
    } 
 
    public static synchronized AppController getInstance() { 
        return instance; 
    } 
 
    private RequestQueue getRequestQueue() { 
        if (mRequestQueue == null) { 
            mRequestQueue = Volley.newRequestQueue(getApplicationContext()); 
        } 
 
        return mRequestQueue; 
    } 
 
    public <T> void addToRequestQueue(Request<T> req, String tag) { 
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag); 
        getRequestQueue().add(req); 
    } 
 
    public <T> void addToRequestQueue(Request<T> req) { 
        req.setTag(TAG); 
        getRequestQueue().add(req); 
    } 
 
    public void cancelAllRequest(Object req) { 
        if (mRequestQueue != null) { 
            mRequestQueue.cancelAll(req); 
        } 
    } 
}
  • Masukan code pada ServerAPI.java
package com.codetr.tanwir.crudvolley.Util; 
 
public class ServerAPI { 
    public static final String URL_DATA = "https://blogspot-wtanwir.c9users.io/volley/view_data.php"; 
    public static final String URL_INSERT = "https://blogspot-wtanwir.c9users.io/volley/create_data.php"; 
    public static final String URL_DELETE = "https://blogspot-wtanwir.c9users.io/volley/delete_data.php"; 
    public static final String URL_UPDATE = "https://blogspot-wtanwir.c9users.io/volley/update_data.php"; 
} 
  • Terakhir Masukan code pada MainActivity.java
package com.codetr.tanwir.crudvolley; 
 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.Bundle; 
import android.support.design.widget.FloatingActionButton; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.LinearLayoutManager; 
import android.support.v7.widget.RecyclerView; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
 
import com.android.volley.Request; 
import com.android.volley.Response; 
import com.android.volley.VolleyError; 
import com.android.volley.toolbox.JsonArrayRequest; 
import com.codetr.tanwir.crudvolley.Adapter.AdapterData; 
import com.codetr.tanwir.crudvolley.Model.ModelData; 
import com.codetr.tanwir.crudvolley.Util.AppController; 
import com.codetr.tanwir.crudvolley.Util.ServerAPI; 
 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 
 
import java.util.ArrayList; 
import java.util.List; 
 
public class MainActivity extends AppCompatActivity { 
    RecyclerView mRecyclerview; 
    RecyclerView.Adapter mAdapter; 
    RecyclerView.LayoutManager mManager; 
    List<ModelData> mItems; 
    FloatingActionButton btnInsert; 
    ProgressDialog pd; 
 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
        setTitle("CodeTR"); 
 
        mRecyclerview = (RecyclerView) findViewById(R.id.rvSiswa); 
        btnInsert = (FloatingActionButton) findViewById(R.id.btn_insert); 
        pd = new ProgressDialog(MainActivity.this); 
        mItems = new ArrayList<>(); 
 
        loadJson(); 
 
        mManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false); 
        mRecyclerview.setLayoutManager(mManager); 
        mAdapter = new AdapterData(MainActivity.this, mItems); 
        mRecyclerview.setAdapter(mAdapter); 
 
        btnInsert.setOnClickListener(new View.OnClickListener() { 
            @Override 
            public void onClick(View view) { 
                Intent intent = new Intent(MainActivity.this, InsertData.class); 
                startActivity(intent); 
            } 
        }); 
    } 
 
 
    private void loadJson() { 
        pd.setMessage("Mengambil Data"); 
        pd.setCancelable(false); 
        pd.show(); 
 
        JsonArrayRequest reqData = new JsonArrayRequest(Request.Method.POST, ServerAPI.URL_DATA, null, 
                new Response.Listener<JSONArray>() { 
                    @Override 
                    public void onResponse(JSONArray response) { 
                        pd.cancel(); 
                        Log.d("volley", "response : " + response.toString()); 
                        for (int i = 0; i < response.length(); i++) { 
                            try { 
                                JSONObject data = response.getJSONObject(i); 
                                ModelData md = new ModelData(); 
                                md.setNis(data.getString("nis")); 
                                md.setNama(data.getString("nama")); 
                                mItems.add(md); 
                            } catch (JSONException e) { 
                                e.printStackTrace(); 
                            } 
                        } 
                        mAdapter.notifyDataSetChanged(); 
                    } 
                }, 
                new Response.ErrorListener() { 
                    @Override 
                    public void onErrorResponse(VolleyError error) { 
                        pd.cancel(); 
                        Log.d("volley", "error : " + error.getMessage()); 
                    } 
                }); 
 
        AppController.getInstance().addToRequestQueue(reqData); 
    } 
 
}
Output Aplikasi


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

Comments

Post a Comment

Popular posts from this blog

PRIVACY POLICY - APLICATION BELMANDIYSAH

PRIVACY POLICY BELMANDIYSAH

Menampilkan Data Menggunakan RecyclerView (Retrofit) Part 1