0% found this document useful (0 votes)
157 views18 pages

Android Mysql Mengunakan Metode Volley

The document provides instructions for creating an Android application using Volley to perform CRUD operations on a MySQL database. It includes steps to set up the Android project, add the Volley library, configure permissions, design layouts, create a database with a table, and write PHP files to connect to the database and handle insert, search, and other requests from the Android app. The application allows users to enter, retrieve, update and delete data from the MySQL database using an Android interface and Volley network requests.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
157 views18 pages

Android Mysql Mengunakan Metode Volley

The document provides instructions for creating an Android application using Volley to perform CRUD operations on a MySQL database. It includes steps to set up the Android project, add the Volley library, configure permissions, design layouts, create a database with a table, and write PHP files to connect to the database and handle insert, search, and other requests from the Android app. The application allows users to enter, retrieve, update and delete data from the MySQL database using an Android interface and Volley network requests.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Android Mysql Mengunakan Metode Volley (CRUD)

 BUAT PROJECT BARU DI ANDROID STUDIO


o Start a new Android Studio project
o Traget android devices
o Add an activity to mobile
o Configure activity
o Finish

 PENAMBAHAN LIBRARY
o Gradle Scripts
o Build.gradle(Module:app)
o implementation 'com.android.volley:volley:1.1.0'
o implementation 'com.android.support:recyclerview-v7:26.1.0'

 PENAMBAHAN ANDROIDMANIFEST
o App
o Manifests
o AndroidMainfest.xml
o <uses-permission android:name="android.permission.INTERNET"/>

 BUAT DESIGN LAYOUT


o Komponen
activity_main
Komponen Jumlah ID(Identitas)
Textview 3
Edittext 2 ed_nama,ed_alamat
Button 4 bt_simpan,bt_cari,bt_edit,bt_hapus
RadioGroup 1 rg_kelamin
RadioButton 2 rb_laki,rb_perempuan
Recyclerview 1 rv_tampil
LinearLayout 4

costum
Komponen Jumlah ID(Identitas)
Textview 6 tvx_nama,tvx_alamat,tvx_kelamin
LinearLayout 4

o Design
activity_main
<?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="com.example.ahmadhalimi.volley.MainActivity">

<!--LinearLayout Pertama-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:text="Nama"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="4"/>
<EditText
android:id="@+id/et_nama"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>

<!--LinearLayout Kedua-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:text="Alamat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="4"/>
<EditText
android:id="@+id/et_alamat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>

<!--LinearLayout Ketiga-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:text="Jenis Kelamin"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<RadioGroup
android:id="@+id/rg_jns_kelamin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<RadioButton
android:id="@+id/rb_laki"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Laki-laki" />
<RadioButton
android:id="@+id/rb_perempuan"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Perempuan"/>
</RadioGroup>
</LinearLayout>

<!--LinearLayout keempat-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/bt_simpan"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Simpan"/>
<Button
android:id="@+id/bt_cari"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Cari"/>
<Button
android:id="@+id/bt_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Edit"/>
<Button
android:id="@+id/bt_hapus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Hapus"/>
</LinearLayout>

</LinearLayout>
<?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">
<!--langkah pertama-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!--langkah kedua-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:text="Nama"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="4"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=": "/>
<TextView
android:text="-----------"
android:id="@+id/tvx_nama"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
<!--langkah ketiga-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:text="Alamat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="4"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=": "/>
<TextView
android:text="-----------"
android:id="@+id/tvx_alamat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
<!--langkah keempat-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:text="Kelamin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="4"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=": "/>
<TextView
android:text="-----------"
android:id="@+id/tvx_kelamin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>

 BUAT DATABASE
o Xampp
o Apache dan Mysql (Klik - Start)
o Buka browser
o http://localhost/phpmyadmin/
o Pada menu Database, silahkan masukkan nama database “volley”, kemudian klik Buat
o Lalu nama Buat Table “crud” , Jumlah Kolom “4” kemudian kilik Go

o Struktur
Nama Tipe Nilai
Id(AI) Int 11
Nama Varchar 20
Alamat Text
Jenis_kelamin Enum “L”,”P”
 BUAT FILE PHP
o Folder Xampp
o htdoc
o New folder dengan nama “volley”
o koneksi.php

ccc

o simpan.php

<?php
// ini untuk manggil koneksi
require_once('koneksi.php');
// ini untuk menerima Request pada android
if($_SERVER['REQUEST_METHOD']=='POST') {
// ini variabel
$nama = $_POST['nama'];
$alamat = $_POST['alamat'];
$kelamin = $_POST['kelamin'];
// aksi untuk simpan pada database
$sql = "INSERT INTO crud (nama,alamat,jenis_kelamin)
VALUES('$nama','$alamat','$kelamin')";
// ini untuk menerima respon
if(mysqli_query($con,$sql)) {
$response["success"] = 1;
$response["message"] = "Berhasil";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Gagal";
echo json_encode($response);
}
mysqli_close($con);
} else {
$response["success"] = 0;
$response["message"] = "Error";
echo json_encode($response);
}
?>
o cari.php

<?php
require_once('koneksi.php');
if($_SERVER['REQUEST_METHOD']=='POST') {
$response = array();
$nama = $_POST['nama'];
$result = mysqli_query($con,"SELECT * FROM crud where nama='$nama'") or
die(mysqli_error());
if (mysqli_num_rows($result) > 0){
$response["Hasil"] = array();
while($row = mysqli_fetch_array($result)){
$hasil = array();
$hasil["alamat"] = $row["alamat"];
$hasil["kelamin"] = $row["jenis_kelamin"];
array_push($response["Hasil"],$hasil);
$response["success"] = 1;
}
echo json_encode($response);

}else{
$response["success"] = 0;
$response["message"] = "Hasil Tidak Di Ditemukan";
echo json_encode($response);
}
mysqli_close($con);
} else {
$response["success"] = 0;
$response["message"] = "Error";
echo json_encode($response);
}
?>

o edit.php

<?php
require_once('koneksi.php');
if($_SERVER['REQUEST_METHOD']=='POST') {
$nama = $_POST['nama'];
$alamat = $_POST['alamat'];
$kelamin = $_POST['kelamin'];
$sql = "UPDATE crud SET alamat = '$alamat', jenis_kelamin='$kelamin' WHERE
nama = '$nama'";
if(mysqli_query($con,$sql)) {
$response["success"] = 1;
$response["message"] = "Berhasil";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Gagal";
echo json_encode($response);
}
mysqli_close($con);
} else {
$response["success"] = 0;
$response["message"] = "Error";
echo json_encode($response);
}
?>

o hapus.php

<?php
require_once('koneksi.php');
if($_SERVER['REQUEST_METHOD']=='POST') {
$nama = $_POST['nama'];
$result = mysqli_query($con,"SELECT * FROM crud where nama='$nama'") or
die(mysqli_error());
if (mysqli_num_rows($result) > 0){
$sql = "DELETE FROM crud WHERE nama = '$nama'";
if(mysqli_query($con,$sql)) {
$response["success"] = 1;
$response["message"] = "Berhasil";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Gagal";
echo json_encode($response);
}
}else{
$response["success"] = 0;
$response["message"] = "Data tidak ada";
echo json_encode($response);
}
mysqli_close($con);
} else {
$response["success"] = 0;
$response["message"] = "Error";
echo json_encode($response);
}
?>
o tampil.php

 KODING JAVA
o App
o Java
o Nama package
o Nama class
package com.example.ahmadhalimi.volley;

/**
* Created by Ahmad Halimi on 09/04/2018.
*/

public class koneksi {


public static final String internet ="http://10.0.2.2/volley/";
public static final String simpan =internet+"simpan.php";
public static final String cari =internet+"cari.php";
public static final String edit =internet+"edit.php";
public static final String hapus =internet+"hapus.php";
public static final String tampil =internet+"tampil.php";
///
public static final String key_nama ="nama";
public static final String key_alamat ="alamat";
public static final String key_kelamin ="kelamin";

package com.example.ahmadhalimi.volley;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements


View.OnClickListener {

//langkah pertama membuat variable untuk item yang akan kita gunakan
EditText nama,alamat;
RadioGroup jns_kelamin;
RadioButton laki,perempuan;
Button simpan,cari,edit,hapus;
String jk;
RecyclerView rv;
/// tampilkan data berbentuk array
ArrayList<HashMap<String, String>> tampil = new
ArrayList<HashMap<String, String>>();
//mana class adapter dibuat varibel
adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// langkah kedua yaitu memanggil ID pada activity_main.xml
nama = (EditText)findViewById(R.id.et_nama);
alamat = (EditText)findViewById(R.id.et_alamat);

jns_kelamin = (RadioGroup)findViewById(R.id.rg_jns_kelamin);

laki = (RadioButton)findViewById(R.id.rb_laki);
perempuan = (RadioButton)findViewById(R.id.rb_perempuan);

rv = (RecyclerView)findViewById(R.id.rv_tampil);
rv.setHasFixedSize(true);
//menngatur rotasi pada tampilan data.
LinearLayoutManager llm = new LinearLayoutManager(this);
// tipe oriention ada vertical dan horizontal
llm.setOrientation(LinearLayoutManager.VERTICAL);
rv.setLayoutManager(llm);

simpan = (Button)findViewById(R.id.bt_simpan);
cari = (Button)findViewById(R.id.bt_cari);
edit = (Button)findViewById(R.id.bt_edit);
hapus = (Button)findViewById(R.id.bt_hapus);

// membuat event untuk tombol onclick pada button


simpan.setOnClickListener(this);
cari.setOnClickListener(this);
edit.setOnClickListener(this);
hapus.setOnClickListener(this);
//membuat event untuk item check pada radiogroup
jns_kelamin.setOnCheckedChangeListener(new
RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int
checkedId) {
if (checkedId == R.id.rb_laki){
jk = String.valueOf("L");
}else if (checkedId == R.id.rb_perempuan){
jk = String.valueOf("P");
}
}
});

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.bt_simpan:
simpan();
break;
case R.id.bt_cari:
cari();
break;
case R.id.bt_edit:
edit();
break;
case R.id.bt_hapus:
hapus();
break;
default:
break;

}
}

private void simpan() {

final String nama_ = nama.getText().toString();


final String alamat_ = alamat.getText().toString();
final String kelamin_ = jk.toString();
StringRequest stringRequest = new
StringRequest(Request.Method.POST, koneksi.simpan,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//untuk menerima respon ketika berhasil / tidak
berhasil pada php.
if(response.contains("1")) {
Toast.makeText(MainActivity.this,
"Berhasil", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Gagal",
Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//berfungsi memberi tahu jika ada kesalahan pada
server atau koneksi aplikasi.
Toast.makeText(MainActivity.this, "Tidak
terhubung ke server", Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws
AuthFailureError {
Map<String, String> params = new HashMap<>();
//untuk mengirim request pada php
params.put(koneksi.key_nama,nama_);
params.put(koneksi.key_alamat,alamat_);
params.put(koneksi.key_kelamin,kelamin_);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

private void cari() {


final String nama_ = nama.getText().toString();
StringRequest stringRequest = new
StringRequest(Request.Method.POST, koneksi.cari,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if(response.contains("1")) {
try {
JSONObject jsonObject;
jsonObject = new JSONObject(response);
JSONArray result =
jsonObject.getJSONArray("Hasil");
for (int i = 0; i < result.length();
i++) {
JSONObject c =
result.getJSONObject(i);
String alamat_ =
c.getString(koneksi.key_alamat);
String kelamin_ =
c.getString(koneksi.key_kelamin);
alamat.setText(alamat_);
if
(kelamin_.toString().equals("L")){
laki.setChecked(true);
}else if
(kelamin_.toString().equals("P")){
perempuan.setChecked(true);
}else{

Toast.makeText(MainActivity.this, "Tidak ada jenis kelamin",


Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}

}else{
Toast.makeText(getApplicationContext(),
"Tidak ada", Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

}
}) {
@Override
protected Map<String, String> getParams() throws
AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put(koneksi.key_nama,nama_);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

private void edit() {


final String nama_ = nama.getText().toString();
final String alamat_ = alamat.getText().toString();
final String kelamin_ = jk.toString();
StringRequest stringRequest = new
StringRequest(Request.Method.POST, koneksi.edit,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if(response.contains("1")) {
Toast.makeText(MainActivity.this,
"Berhasil", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Gagal",
Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Tidak ada
jenis kelamin", Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws
AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put(koneksi.key_nama,nama_);
params.put(koneksi.key_alamat,alamat_);
params.put(koneksi.key_kelamin,kelamin_);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

private void hapus() {


final String nama_ = nama.getText().toString();
StringRequest stringRequest = new
StringRequest(Request.Method.POST, koneksi.hapus,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if(response.contains("1")) {
Toast.makeText(MainActivity.this,
"Berhasil", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Gagal",
Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Tidak ada
jenis kelamin", Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws
AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put(koneksi.key_nama,nama_);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

}
private void tampil(){
StringRequest stringRequest = new StringRequest(Request.Method.POST,
koneksi.tampil,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if(response.contains("1")) {
try {
JSONObject jsonObject;
jsonObject = new JSONObject(response);
JSONArray result =
jsonObject.getJSONArray("Hasil");
tampil.clear();
for (int i = 0; i < result.length(); i++) {
JSONObject c = result.getJSONObject(i);
String nama =
c.getString(koneksi.key_nama);
String alamat =
c.getString(koneksi.key_alamat);
String kelamin =
c.getString(koneksi.key_kelamin);
HashMap<String, String> map = new
HashMap<String, String>();
map.put(koneksi.key_nama, nama);
map.put(koneksi.key_alamat, alamat);
map.put(koneksi.key_kelamin, kelamin);
tampil.add(map);
}
adapter=new adapter(MainActivity.this,tampil);
rv.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}

}else{
Toast.makeText(getApplicationContext(), "Tidak
ada", Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//berfungsi memberi tahu jika ada kesalahan pada server
atau koneksi aplikasi.
Toast.makeText(MainActivity.this, "Tidak terhubung ke
server", Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

package com.example.ahmadhalimi.volley;

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

import java.util.ArrayList;
import java.util.HashMap;

/**
* Created by Ahmad Halimi on 11/04/2018.
*/

public class adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>


{

private Context context;


private LayoutInflater inflater;
private ArrayList<HashMap<String, String>> data;
ArrayList<HashMap<String, String>> tampil = new
ArrayList<HashMap<String, String>>();
//deklarasi pengambilan data
public adapter (Context context, ArrayList<HashMap<String, String>>
data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}

//pendeklarasian item layout


@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup,
int i) {
View v =
LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.costum, null);
MyHolder holder = new MyHolder(v);

return holder;
}

//Penampilan data recycleriew


@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int
position) {
MyHolder myHolder = (MyHolder) holder;

HashMap<String, String> data_tampil = new HashMap<String,


String>();
data_tampil = data.get(position);
myHolder.mTextView.setText(data_tampil.get(koneksi.key_nama));
myHolder.mTextView1.setText(data_tampil.get(koneksi.key_alamat));
myHolder.mTextView2.setText(data_tampil.get(koneksi.key_kelamin));

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

class MyHolder extends RecyclerView.ViewHolder {

TextView mTextView,mTextView1,mTextView2;

// create constructor to get widget reference


public MyHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.tvx_nama);
mTextView1 = (TextView) itemView.findViewById(R.id.tvx_alamat);
mTextView2 = (TextView)
itemView.findViewById(R.id.tvx_kelamin);
}

}
}

You might also like