CRUD Android PHP MySQL Database

Tak terasa sudah lama juga yah saya tidak ngeblog. Oke langsung saja kali ini kita akan bahas tentang cara input data, update data dan hapus data dari android ke database MySQL dengan perantara PHP. yah PHP ini ibarat mak comblang antara android dan MySQL.

Sekarang mari kita mulai membuat aplikasi android yang mempunyaiu kemampuan CRUD ke database MySQL.

Langkah pertama yang harus kita siapkan adalah dari sisi servr

1. Database MySQL, buat data base baru dengan nama dbbarang setelah itu jalankan scripr SQL dibawah ini

CREATE TABLE IF NOT EXISTS `tbl_barang` (
`id` int(4) NOT NULL,
`kode` varchar(8) NOT NULL,
`nama` varchar(32) NOT NULL,
`harga` int(12) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_barang`
--

INSERT INTO `tbl_barang` (`id`, `kode`, `nama`, `harga`) VALUES
(1, 'B001', 'Mouse', 50000),
(2, 'B002', 'Keyboard', 70000),
(3, 'B006', 'Kopi', 6000);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_barang`
--
ALTER TABLE `tbl_barang`
ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_barang`
--
ALTER TABLE `tbl_barang`
MODIFY `id` int(4) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7;

2. untuk bagian PHP nya.

– buat sricpt php baru  dengan nama dbconfig.php yang beguna sebagai konsatanta variabel koneksi ke database

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbbarang";
?>

– buat script untuk menampilkan data dari database, beri nama listdata.php

<?php

include 'dbconfig.php';

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$result["errorcode"]="0";
$sql = "SELECT id, kode, nama, harga FROM tbl_barang order by kode";
$res = mysqli_query($conn, $sql);
$items = array();
if (mysqli_num_rows($res) > 0) {
	while($row = mysqli_fetch_object($res)){

	    array_push($items, $row);

	}
$result["errorcode"] = "1";
    $result["data"] = $items;
}else{
     $result["errormsg"] = "Tidak ada data";
}
echo json_encode($result);
mysqli_close($conn);
?>

– buat script untuk add dan update data, beri nama savedata.php

<?php
include 'dbconfig.php';

$nama = $_POST['nama'];
$kode = $_POST['kode'];
$harga= $_POST['harga'];
$id = $_POST['id'];

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

/* grab the posts from the db */
$query = "insert into tbl_barang (kode, nama, harga) values('".$kode."','".$nama."','".$harga."')";
if ($id != "0"){
$query = "update tbl_barang set nama='".$nama."',kode='".$kode."',harga='".$harga."' where id=".$id;
}
$response = mysqli_query($conn, $query) or die('Error query:  '.$query);
$lid = mysqli_insert_id($conn);
$result["errormsg"]="Success";
$result["lid"]="$lid";
if ($response == 1){
	echo json_encode($result);
}
else{
	$result["errormsg"]="Fail";
	echo json_encode($result);
}
?>

– buat script untuk hapus data, berinama deletedata.php

<?php
include 'dbconfig.php';

$id = $_POST['id'];

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$query = "delete from tbl_barang  where id=".$id;

$response = mysqli_query($conn, $query) or die('Error query:  '.$query);
$result["errormsg"]="Success";

if ($response == 1){
	echo json_encode($result);
}
else{
	$result["errormsg"]="Fail";
	echo json_encode($result);
}

?>

Sekarang mari kita ke bagian androidnya

1. Buka Android Studio lalu buat project baru, isi project name dengan “DataBarang” dan domain name dengan “agusharyanto.net” kemudian klik next 2 kali

2. Sampai pada pada jendela add an activity to mobile pilih “BasicActivity” lalu klik next sampai finish.

3. Sekarang kita edit script gradle(Module:app)nya lalu ketikan kode berikut.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "net.agusharyanto.databarang"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.mcxiaoke.volley:library-aar:1.0.+'
    testCompile 'junit:junit:4.12'

}

Disini kita menambahkan library untuk recyclerview, cardview dan volley

4. Untuk Data Barang kita perlu buat modelnya. Untuk itu buat class baru dengan nama Barang lalu ketikan kode berikut

package net.agusharyanto.databarang;

import java.io.Serializable;

/**
 * Created by agus on 9/27/17.
 */

public class Barang implements Serializable{

    private String id="";
    private String kode="";
    private String nama="";
    private String harga ="";

    public String getId() {
        return id;
    }

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

    public String getKode() {
        return kode;
    }

    public void setKode(String kode) {
        this.kode = kode;
    }

    public String getNama() {
        return nama;
    }

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

    public String getHarga() {
        return harga;
    }

    public void setHarga(String harga) {
        this.harga = harga;
    }

    @Override
    public String toString() {
        return "Barang{" +
                "id='" + id + '\'' +
                ", kode='" + kode + '\'' +
                ", nama='" + nama + '\'' +
                ", harga='" + harga + '\'' +
                '}';
    }
}

6. Aplikasi CRUD Data Barang ini untuk tampilannya pertama kali menampilkan data barang. Untuk itu mari kita siapkan layoutnya.

7. pada directory res/layout edit activity_main.xml lalu ketikan kode berikut, disini sebeutulnya kita hanya menggan icon floatieng action button dari amplop surat ke tanda tambah

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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="net.agusharyanto.databarang.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_menu_add" />

</android.support.design.widget.CoordinatorLayout>

8. pada directory res/layout edit content_main.xml lalu ketikan kode berikut

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="net.agusharyanto.databarang.MainActivity"
    tools:showIn="@layout/activity_main">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorAccent"
    android:id="@+id/rltvheader">
    <TextView
        android:paddingLeft="10dp"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="Kode"
        android:id="@+id/textViewRowKode"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Nama"
        android:id="@+id/textViewRowNama"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/textViewRowKode"
        android:layout_toEndOf="@+id/textViewRowKode" />

    <TextView
        android:id="@+id/textViewRowHarga"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="Harga" />
</RelativeLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_below="@+id/rltvheader"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

Disini kita siapkan 1 relative layout yang berisi tiga text view untuk header data dan 1 recyclerview untuk menampilkan data.

9. pada directory res/layout buat layout baru dengan nama “row_barang.xml” lalu ketikan kode berikut

<?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"
    android:padding="0dp">
    <android.support.v7.widget.CardView
        android:id="@+id/cv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp"
            >
            <TextView
                android:id="@+id/textViewRowKode"
                android:layout_width="100dp"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:text="Kode" />

            <TextView
                android:id="@+id/textViewRowNama"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_toEndOf="@+id/textViewRowKode"
                android:layout_toRightOf="@+id/textViewRowKode"
                android:text="Nama" />

            <TextView
                android:id="@+id/textViewRowHarga"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:text="Harga" />
        </RelativeLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

Layout ini digunakan untuk isi dari recyclerview.

10. Kembali source java buat Activity baru pilih basic activity lalu beri nama BarangActivity.

11. Maka akan mengenerate juga 2 layout yaitu activity_barang.xml dan content_barang.xml

12. Edit content_barang.xml lalu ketikan kode berikut

<?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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="net.agusharyanto.databarang.BarangActivity"
    tools:showIn="@layout/activity_barang">
    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp">
        <EditText
            android:id="@+id/editTextKode"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Kode"/>
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/editTextNama"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Nama"/>
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp">
        <EditText
            android:id="@+id/editTextHarga"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Harga"/>
    </android.support.design.widget.TextInputLayout>
</LinearLayout>

13. pada directory res/menu buat menu dengan nama menu_barang

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_save"
        android:orderInCategory="100"
        android:title="Save"
        android:icon="@android:drawable/ic_menu_save"
        app:showAsAction="always" />
    <item
        android:id="@+id/action_delete"
        android:orderInCategory="100"
        android:title="Delete"
        android:icon="@android:drawable/ic_menu_delete"
        app:showAsAction="always" />
</menu>

Dimenu ini ada menu save dan menu delete

14. Sekarang kita beralih ke bagian javanya. Buat class baru dengan nama BarangAdapter.java lalu ketikan kode berikut.

package net.agusharyanto.databarang;

import android.support.v7.widget.CardView;
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.List;

/**
 * Created by agus on 9/26/17.
 */

public class BarangAdapter  extends RecyclerView.Adapter<BarangAdapter.BarangViewHolder> {
    List<Barang> barangs;

    public BarangAdapter(List<Barang> barangs) {
        this.barangs = barangs;
    }
    @Override
    public BarangViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_barang, viewGroup, false);
        BarangViewHolder barangViewHolder = new BarangViewHolder(v);
        return barangViewHolder;
    }
    @Override
    public void onBindViewHolder(BarangViewHolder barangViewHolder, int i) {
        barangViewHolder.barangName.setText(barangs.get(i).getNama());
        barangViewHolder.barangHarga.setText(barangs.get(i).getHarga());
        barangViewHolder.barangKode.setText(barangs.get(i).getKode());
    }
    @Override
    public int getItemCount() {
        return barangs.size();
    }
    public Barang getItem(int position) {
        return barangs.get(position);
    }
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    public static class BarangViewHolder extends RecyclerView.ViewHolder {
        CardView cv;
        TextView barangName;
        TextView barangHarga;
        TextView barangKode;
        BarangViewHolder(View itemView) {
            super(itemView);
            cv = (CardView) itemView.findViewById(R.id.cv);
            barangName = (TextView) itemView.findViewById(R.id.textViewRowNama);
            barangHarga = (TextView) itemView.findViewById(R.id.textViewRowHarga);
            barangKode = (TextView) itemView.findViewById(R.id.textViewRowKode);
        }
    }
}

15. Buat class baru dengan nama RecyclerItemListener.java lalu ketikan kode berikut.

package net.agusharyanto.databarang;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by agus on 9/27/17.
 */

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {

    private OnItemClickListener mListener;

    public interface OnItemClickListener {
        public void onItemClick(View view, int position);
    }

    GestureDetector mGestureDetector;
    public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
        mListener = listener;
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }
        });
    }
    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
        View childView = view.findChildViewUnder(e.getX(), e.getY());
        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
            mListener.onItemClick(childView, view.getChildPosition(childView));
            return true;
        }
        return false;
    }
    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean b) {
    }
}

Digunakan agar recylerview dapat dipasang listener.

16. Edit MainActivity.java lalu ketikan kode berikut.

package net.agusharyanto.databarang;

import android.app.ProgressDialog;
import android.content.Context;
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.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.android.volley.Request;
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.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    private BarangAdapter rvAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private Context context = MainActivity.this;

    private static  final int REQUEST_CODE_ADD =1;
    private static  final int REQUEST_CODE_EDIT =2;
    private List<Barang> barangList = new ArrayList<Barang>();
    private ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, BarangActivity.class);
                startActivityForResult(intent, REQUEST_CODE_ADD);

            }
        });

        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        pDialog = new ProgressDialog(this);
        loadDataServerVolley();

    }

    private void gambarDatakeRecyclerView(){
        rvAdapter = new BarangAdapter(barangList);
        mRecyclerView.setAdapter(rvAdapter);
        mRecyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Barang barang = rvAdapter.getItem(position);
                        Intent intent = new Intent(MainActivity.this, BarangActivity.class);
                        intent.putExtra("barang", barang);
                        startActivityForResult(intent, REQUEST_CODE_EDIT);
                    }
                })
        );
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_ADD: {
                if (resultCode == RESULT_OK && null != data) {
                    if (data.getStringExtra("refreshflag").equals("1")) {
                        loadDataServerVolley();
                    }
                }
                break;
            }
            case REQUEST_CODE_EDIT: {
                if (resultCode == RESULT_OK && null != data) {
                    if (data.getStringExtra("refreshflag").equals("1")) {
                        loadDataServerVolley();
                    }
                }
                break;
            }
        }
    }

    //ambil data sever volley
    private void loadDataServerVolley(){

        String url = AppConfig.IP_SERVER+"/barang/listdata.php";
        pDialog.setMessage("Retieve Data Barang...");
        showDialog();

        StringRequest postRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("MainActivity","response:"+response);
                        hideDialog();
                        processResponse(response);
                        gambarDatakeRecyclerView();

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        hideDialog();
                        error.printStackTrace();
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<>();
                // the POST parameters:
                //params.put("id","1");
                return params;
            }
        };
        Volley.newRequestQueue(this).add(postRequest);
    }

    private void processResponse(String response){

        try {
            JSONObject jsonObj = new JSONObject(response);
            JSONArray jsonArray = jsonObj.getJSONArray("data");
            Log.d("TAG", "data length: " + jsonArray.length());
            Barang objectbarang = null;
            barangList.clear();
            for(int i = 0; i < jsonArray.length(); i++){
                JSONObject obj = jsonArray.getJSONObject(i);
                objectbarang= new Barang();
                objectbarang.setId(obj.getString("id"));

                objectbarang.setNama(obj.getString("nama"));
                objectbarang.setKode(obj.getString("kode"));
                objectbarang.setHarga(obj.getString("harga"));

                barangList.add(objectbarang);
            }

        } catch (JSONException e) {
            Log.d("MainActivity", "errorJSON");
        }

    }
    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

17. edit BarangActivity.java lalu ketikan kode berikut.

package net.agusharyanto.databarang;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
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.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class BarangActivity extends AppCompatActivity {

    private EditText editTextKode, editTextNama, editTextHarga;
    private Barang barang;

    private String action_flag="add";
    private String refreshFlag="0";
    private static final String TAG="MahsiswaActivity";
    private ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_barang);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveDataVolley();
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        barang = new Barang();
        initUI();
        //initEvent();
        Intent intent = getIntent();
        if (intent.hasExtra("barang")) {
            barang = (Barang) intent.getSerializableExtra("barang");
            Log.d(TAG, "Barang : " + barang.toString());
            setData(barang);
            action_flag = "edit";
            editTextKode.setEnabled(false);
        }else{
            barang = new Barang();
        }
    }
    private void setData(Barang barang) {
        editTextKode.setText(barang.getKode());
        editTextNama.setText(barang.getNama());
        editTextHarga.setText(barang.getHarga());
    }
    private void initUI() {
        pDialog = new ProgressDialog(BarangActivity.this);

        editTextKode = (EditText) findViewById(R.id.editTextKode);
        editTextNama = (EditText) findViewById(R.id.editTextNama);
        editTextHarga = (EditText) findViewById(R.id.editTextHarga);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_barang, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_save) {
            saveDataVolley();
            return true;
        }else  if (id == R.id.action_delete) {
            hapusData();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void hapusData() {
        new AlertDialog.Builder(this)
                .setTitle("Data Barang")
                .setMessage("Hapus Data " + barang.getNama() + " ?")
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        hapusDataServer();
                        refreshFlag = "1";
                        //finish();
                    }
                })
                .setNegativeButton(android.R.string.no, null).show();
    }

    @Override
    public void finish() {
        System.gc();
        Intent data = new Intent();
        data.putExtra("refreshflag", refreshFlag);
        //  data.putExtra("barang", barang);
        setResult(RESULT_OK, data);
        super.finish();
    }

    private void saveDataVolley(){
        refreshFlag="1";
        final String nama = editTextNama.getText().toString();
        final String kode = editTextKode.getText().toString();
        final String harga = editTextHarga.getText().toString();

        String url = AppConfig.IP_SERVER+"/barang/savedata.php";
        pDialog.setMessage("Save Data Barang...");
        showDialog();

        StringRequest postRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        hideDialog();
                        Log.d("BarangActivity", "response :" + response);
                        // Toast.makeText(getBaseContext(),"response: "+response, Toast.LENGTH_SHORT).show();
                        processResponse("Save Data",response);
                        finish();

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        hideDialog();
                        error.printStackTrace();
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<>();
                // the POST parameters:

                params.put("nama",nama);
                params.put("kode",kode);
                params.put("harga",harga);
                if (action_flag.equals("add")){
                    params.put("id","0");
                }else{
                    params.put("id",barang.getId());
                }
                return params;
            }
        };
        Volley.newRequestQueue(this).add(postRequest);

    }
    private void processResponse(String paction, String response){

        try {
            JSONObject jsonObj = new JSONObject(response);
            String errormsg = jsonObj.getString("errormsg");
            Toast.makeText(getBaseContext(),paction+" "+errormsg,Toast.LENGTH_SHORT).show();

        } catch (JSONException e) {
            Log.d("BarangActivity", "errorJSON");
        }

    }

    private void hapusDataServer(){
        refreshFlag="1";
        String url = AppConfig.IP_SERVER+"/barang/deletedata.php";
        pDialog.setMessage("Hapus Data Barang...");
        showDialog();

        StringRequest postRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        hideDialog();
                        Log.d("BarangActivity", "response :" + response);
                        processResponse("Hapus Data", response);
                        finish();

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        hideDialog();
                        error.printStackTrace();
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<>();
                // the POST parameters:
                params.put("id",barang.getId());

                return params;
            }
        };
        Volley.newRequestQueue(this).add(postRequest);

    }
    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

}

18. Pada AndroidManifest.xml tambahkan permission internet

    <uses-permission android:name="android.permission.INTERNET"/>

19. Jika semua sudah selesai dibuat maka struktur projectnya akan terlihat seperti dibawah ini.

20. sekarang mari kita run projectnya.

Selesai sudah, gimana mudahkan belajar android membuat aplikasi Android CRUD PHP MySQL

Salam Hangat

Developer Android

Agus Haryanto

9 comments to CRUD Android PHP MySQL Database

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>