Tampilkan postingan dengan label crud. Tampilkan semua postingan

Membuat Aplikasi CRUD Sederhana dengan database SQLite di Android Studio

Halo sobat blogger sudah lama admin tidak membuat postingan artikel dikarenakan sibuk dengan urusan di dunia nyata. pada kesempatan kali ini admin akan memberikan tutorial cara membuat aplikasi CRUD (Create Read Update Delete) di Android dengan Database SQLite. SQLite ini adalah database yang portable karena data-datanya akan tersimpan pada memori handhone kalian masing-masing, tidak disimpan di server. namun jika di perlukan bisa juga database ini disinkronkan ke server kita akan membahasnya pada kesempatan yang lain. Pada kesempatan kali ini kita akan membuat Aplikasi CRUD yang sederhana kedepanya kita akan bahas membuat CRUD dengan Content Provider.



Ok langsung saja untuk membuatnya kita buat desain tampilanya dulu.
<?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:theme="@android:style/Theme.NoTitleBar"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:orientation="vertical"
   
android:background="#ddd"
   
android:padding="10dp"
   
tools:context="giviews.id.splash.MainActivity">

    <LinearLayout
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_marginTop="20dp"
       
android:orientation="horizontal">

        <TextView
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:layout_weight="3"
           
android:textColor="#000"
           
android:text="Name"/>

        <EditText
           
android:id="@+id/editText_name"
           
style="@android:style/Widget.Material.Light.EditText"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:layout_weight="1"
           
android:ems="10"
           
android:hint="Name"
           
android:inputType="textPersonName" />
    </LinearLayout>

    <LinearLayout
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_marginTop="20dp"
       
android:orientation="horizontal">

        <TextView
            
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:layout_weight="3"
           
android:textColor="#000"
           
android:text="Surname"/>

        <EditText
           
android:id="@+id/editText_surname"
           
style="@android:style/Widget.Material.Light.EditText"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:layout_weight="1"
           
android:ems="10"
            
android:hint="Surname"
           
android:inputType="textPersonName" />
    </LinearLayout>

    <LinearLayout
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_marginTop="20dp"
       
android:orientation="horizontal">

        <TextView
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:layout_weight="3"
           
android:textColor="#000"
           
android:text="Marks"/>

        <EditText
           
android:id="@+id/editText_marks"
           
style="@android:style/Widget.Material.Light.EditText"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:layout_weight="1"
           
android:ems="10"
           
android:hint="Marks"
           
android:inputType="textPersonName"/>
    </LinearLayout>

    <LinearLayout
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_marginTop="20dp"
       
android:orientation="horizontal">

        <TextView
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:layout_weight="3"
           
android:textColor="#000"
           
android:text="Id"/>

        <EditText
           
android:id="@+id/editTextId"
           
style="@android:style/Widget.Material.Light.EditText"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:layout_weight="1"
           
android:ems="10"
           
android:hint="Id"
           
android:inputType="textPersonName" />
    </LinearLayout>

        <LinearLayout
           
android:layout_marginTop="20dp"
            
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:orientation="horizontal">

            <Button
               
android:id="@+id/button_add"
               
style="@android:style/Widget.Material.Light.Button"
               
android:background="@color/colorAccent"
               
android:textColor="@android:color/background_light"
               
android:layout_width="match_parent"
               
android:layout_height="wrap_content"
                
android:text="Add Data"
               
android:textAppearance="@android:style/TextAppearance.Material.Button"
               
android:layout_weight="1" />

            <Button
               
android:id="@+id/button_view"
               
style="@android:style/Widget.Material.Light.Button"
               
android:layout_width="match_parent"
               
android:layout_height="wrap_content"
               
android:background="@color/colorAccent"
               
android:layout_weight="1"
                
android:text="view all"
               
android:textAppearance="@android:style/TextAppearance.Material.Button"
               
android:textColor="@android:color/background_light" />
        </LinearLayout>

        <LinearLayout
           
android:layout_marginTop="20dp"
           
android:layout_width="match_parent"
           
android:orientation="horizontal"
           
android:layout_height="wrap_content">

            <Button
               
android:id="@+id/button_update"
               
style="@android:style/Widget.Material.Light.Button"
               
android:background="@color/colorAccent"
               
android:textColor="@android:color/background_light"
               
android:layout_width="match_parent"
               
android:layout_height="wrap_content"
               
android:layout_weight="1"
               
android:text="Update"
               
android:textAppearance="@style/TextAppearance.AppCompat.Button" />

            <Button
               
android:id="@+id/button_delete"
                
style="@android:style/Widget.Material.Light.Button"
               
android:background="@color/colorAccent"
               
android:textColor="@android:color/background_light"
               
android:layout_width="match_parent"
               
android:layout_height="wrap_content"
               
android:layout_weight="1"
               
android:text="Delete"
               
android:textAppearance="@style/TextAppearance.AppCompat.Button" />
        </LinearLayout>
    </LinearLayout>

Selanjutnya buat class DatabaseHelper di java, class ini berfungsi untuk membuat database, table, metode untuk menambah, mengupdate, menampilkan dan menghapus data.

package giviews.id.splash;



import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;



/**

 * Created by asus on 02/04/2017.

 */



public class DatabaseHelper extends SQLiteOpenHelper{

    //nama database

    public static final String DATABASE_NAME = "Student.db";

    //nama table

    public static final String TABLE_NAME = "student_table";

    //versi database

    private static final int DATABASE_VERSION = 1;

    //table field

    public static final String COL_1 = "ID";

    public static final String COL_2 = "NAME";

    public static final String COL_3 = "SURNAME";

    public static final String COL_4 = "MARKS";



    public DatabaseHelper(Context context) {

        super(context, DATABASE_NAME, null, DATABASE_VERSION);

        SQLiteDatabase db = this.getWritableDatabase();

    }



    @Override

    public void onCreate(SQLiteDatabase db) {

        db.execSQL("create table student_table(id integer primary key autoincrement," +

                "name text null," +

                "surname text null," +

                "marks integer null);");

    }



    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);

        onCreate(db);

    }



    //metode untuk tambah data

    public boolean insertData(String name, String surname, String marks) {

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues contentValues = new ContentValues();

        contentValues.put(COL_2,name);

        contentValues.put(COL_3,surname);

        contentValues.put(COL_4,marks);

        long result = db.insert(TABLE_NAME, null, contentValues);

        if(result == -1)

            return false;

        else

            return true;

    }



    //metode untuk mengambil data

    public Cursor getAllData() {

        SQLiteDatabase db = this.getWritableDatabase();

        Cursor res = db.rawQuery("select * from student_table", null);

        return res;

    }



    //metode untuk merubah data

    public boolean updateData(String id,String name,String surname,String marks) {

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues contentValues = new ContentValues();

        contentValues.put(COL_1,id);

        contentValues.put(COL_2,name);

        contentValues.put(COL_3,surname);

        contentValues.put(COL_4,marks);

        db.update(TABLE_NAME,contentValues,"ID = ?",new String[] {id});

        return true;

    }



    //metode untuk menghapus data

    public int deleteData (String id) {

        SQLiteDatabase db = this.getWritableDatabase();

        return db.delete(TABLE_NAME, "ID = ?", new String[] {id});

    }

}
Terakhir kita buat script untuk memfungsikan tombol add, edit, view dan delete yang telah kita desain tadi, kodenya seperti berikut:

package giviews.id.splash;



import android.database.Cursor;

import android.os.Bundle;

import android.support.v7.app.AlertDialog;

import android.support.v7.app.AppCompatActivity;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;



public class MainActivity extends AppCompatActivity {

    DatabaseHelper myDb;

    EditText editName,editSurname,editMarks,editTextId;

    Button btnAddData;

    Button btnViewAll;

    Button btnUpdate;

    Button btnDelete;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        myDb = new DatabaseHelper(this);

        editName = (EditText)findViewById(R.id.editText_name);

        editSurname = (EditText)findViewById(R.id.editText_surname);

        editMarks = (EditText)findViewById(R.id.editText_marks);

        editTextId = (EditText)findViewById(R.id.editTextId);

        btnAddData = (Button)findViewById(R.id.button_add);

        btnViewAll = (Button)findViewById(R.id.button_view);

        btnUpdate = (Button)findViewById(R.id.button_update);

        btnDelete = (Button)findViewById(R.id.button_delete);

        AddData();

        viewAll();

        UpdateData();

        deleteData();

    }



    //fungsi hapus

    public void deleteData() {

        btnDelete.setOnClickListener(

                new View.OnClickListener() {

                    @Override

                    public void onClick(View v) {

                        Integer deletedRows = myDb.deleteData(editTextId.getText().toString());

                        if (deletedRows > 0)

                            Toast.makeText(MainActivity.this,"Data Deleted",Toast.LENGTH_LONG).show();

                        else

                            Toast.makeText(MainActivity.this,"Data Failed to Deleted!",Toast.LENGTH_LONG).show();

                    }

                }

        );

    }



    //fungsi update

    public void UpdateData() {

        btnUpdate.setOnClickListener(

                new View.OnClickListener() {

                    @Override

                    public void onClick(View v) {

                        boolean isUpdate = myDb.updateData(editTextId.getText().toString(),

                                editName.getText().toString(),

                                editSurname.getText().toString(),

                                editMarks.getText().toString());

                        if(isUpdate == true)

                            Toast.makeText(MainActivity.this,"Data Updated",Toast.LENGTH_LONG).show();

                        else

                            Toast.makeText(MainActivity.this,"Data Failed to Update",Toast.LENGTH_LONG).show();

                    }

                }

        );

    }



    //fungsi tambah

    public void AddData() {

        btnAddData.setOnClickListener(

                new View.OnClickListener() {

                    @Override

                    public void onClick(View v) {

                        boolean isInserted = myDb.insertData(editName.getText().toString(),

                                editSurname.getText().toString(),

                                editMarks.getText().toString() );

                        if(isInserted == true)

                            Toast.makeText(MainActivity.this,"Data Iserted",Toast.LENGTH_LONG).show();

                        else

                            Toast.makeText(MainActivity.this,"Data Not Iserted",Toast.LENGTH_LONG).show();

                    }

                }

        );

    }



    //fungsi menampilkan data

    public void viewAll() {

        btnViewAll.setOnClickListener(

            new View.OnClickListener(){

                 @Override

                     public void onClick(View v) {

                     Cursor res = myDb.getAllData();

                     if(res.getCount() == 0) {

                     // show message

                         showMessage("Error","Noting Found");

                     return;

                 }



                 StringBuffer buffer = new StringBuffer();

                     while (res.moveToNext() ) {

                         buffer.append("Id :"+ res.getString(0)+"\n");

                         buffer.append("Name :"+ res.getString(1)+"\n");

                         buffer.append("Surname :"+ res.getString(2)+"\n");

                         buffer.append("Marks :"+ res.getString(3)+"\n\n");

                     }



                     // show all data

                     showMessage("Data",buffer.toString());

                }

            }

        );

    }



    //membuat alert dialog

    public void showMessage(String title, String Message){

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setCancelable(true);

        builder.setTitle(title);

        builder.setMessage(Message);

        builder.show();

    }

}





Sekarang jalankan program crud anda, selamat mencoba semoga berhasil. jika ada yang kurang jelas bisa ditanyakan pada komentar dibawah, jika artikel ini bermanfaat silakan share. pada postingan selanjutnya kita akan membuat Aplikasi CRUD dengan menggunakan Content Provider dan Circular Reveal Animation

Membuat Aplikasi CRUD Data Mahasiswa Menggunakan RESTful API di Android Studio


Pada postingan sebelumnya kita telah membuat API CRUD sederhana menggunakan PHP danMYSQL sekarang kita akan mengkonsumsi API yang sudah kita buat tersebut Pada kasus ini saya akan menggunakan API tadi di Projek Android dengan menggunakan library retrofit



Pertama-tama buat projek baru di Android Studio, kemudian tambahkan library retrofit pada build.gradle(module:app) di bagian  despendencies, kemudian klik sync now
implementation 'com.squareup.retrofit:retrofit:1.9.0'

lalu tambahkan network permission pada AndroidManifest
android:name="android.permission.INTERNET" />

android:name="android.permission.ACCESS_NETWORK_STATE" />

Untuk Susunan Folder nya seperti berikut:
Susunan Folder Projek di Android Studio


Kemudian buat Class BaseApp, kelas ini berfungsi untuk kumpulan perintah yang sering digunakan dalam pembuatan program, sehingga nanti dapat digunakan pada class lain. Berikut kode programnya: untuk ROOT_URL karena saya sudah menguploadnya pada web hosting jadi saya menggunakan url yang ada di web hosting saya, jika anda menyimpanya di localhost dan ingin mengaksesnya dari HP ganti url nya menjadi alamat IP komputer anda, dan pastikan HP dan komputer anda menggunakan jaringan wifi yang sama.
public class BaseApp extends AppCompatActivity {

    public static Context c;

    public static final String ROOT_URL = "http://giviews.000webhostapp.com";

    private static final int DEBUG = 1;

    public SessionManager sessionManager;

    AlphaAnimation btnAnimasi = new AlphaAnimation(1F,0.5F);



    public BaseApp() {

        sessionManager = new SessionManager(c);

    }



    @Override

    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        c =  this;

    }



    public void pesan(String a){

        Toast.makeText(c, a, Toast.LENGTH_LONG).show();

    }



    //method untuk menghilangkan action bar

    public void fullScreen(){

        requestWindowFeature(Window.FEATURE_NO_TITLE);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

                WindowManager.LayoutParams.FLAG_FULLSCREEN);

    }



    private class SessionManager {

        public SessionManager(Context c) {

        }

    }

}

selanjutnya membuat class Model Mahasiswa, Class ini berisi geter dan seter yang nanti akan digunakan ketika get data dan set data mahasiswa, berikut kode programnya:
public class DataMahasiswa {

    private String nim;

    private String nama;

    private String alamat;

    private String jurusan;



    public String getNim() {

        return nim;

    }

    public void setNim(String nim) {

        this.nim = nim;

    }

    public String getNama() {

        return nama;

    }

    public void setNama(String nama) {

        this.nama = nama;

    }

    public String getAlamat() {

        return alamat;

    }

    public void setAlamat(String alamat) {

        this.alamat = alamat;

    }

    public String getJurusan() {

        return jurusan;

    }

    public void setJurusan(String jurusan) {

        this.jurusan = jurusan;

    }

}

kemudian buat Class CDataMahasiswa, berikut kode programnya:
public class CDataMahasiswa {





    private List DataMahasiswa = new ArrayList();



    public List getDataMahasiswa() {

        return DataMahasiswa;

    }



    public void setDataMahasiswa(List DataMahasiswa) {

        this.DataMahasiswa = DataMahasiswa;

    }

}

selanjutnya membuat interface ModuleApi.java berikut kode programnya: Class ini berfungsi untuk mengakses API nya
interface ModuleAPI {



    //getdata

    @GET("/server_api/view.php")

    public void getDataMahasiswa(Callback callback);



    //update

    @FormUrlEncoded

    @POST("/server_api/update.php")

    public void updateData(

            @Field("vsnim") String vsnim,

            @Field("vsnama") String vsnama,

            @Field("vsalamat") String vsalamat,

            @Field("vsjurusan") String vsjurusan,

            Callback callback);



    //insert

    @FormUrlEncoded

    @POST("/server_api/create.php")

    public void insertData(

            @Field("vsnim") String vsnim,

            @Field("vsnama") String vsnama,

            @Field("vsalamat") String vsalamat,

            @Field("vsjurusan") String vsjurusan,

            Callback callback);



    //delete

    @FormUrlEncoded

    @POST("/server_api/delete.php")

    public void deleteData(

            @Field("vsnim") String vsnim,

            Callback callback);

    }

Selanjutnya Membuat DataMahasiswaActivity.java berikut kode programnya:
public class DataMahasiswaActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    ProgressDialog progressDialog;

    Dialog dialog, dialog2;

    List listdatamahasiswa;

    String strnim, strnama, strjurusan, stralamat;

    ListView listmahasiswa;

    Button update, delete, reset, insert;

    SwipeRefreshLayout swipeRefreshLayout;

    EditText nimmhs, namamhs, alamatmhs, jurusanmhs;

    AdapterCariMahasiswa cariMahasiswa;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_data_mahasiswa);

        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) {

                dialog2 = new Dialog(DataMahasiswaActivity.this);

                dialog2.setTitle("data mahasiswa");

                dialog2.setCanceledOnTouchOutside(false);

                dialog2.setContentView(R.layout.tampilaninsertdata);



                nimmhs = (EditText) dialog2.findViewById(R.id.edtnim);

                namamhs = (EditText) dialog2.findViewById(R.id.edtnama);

                jurusanmhs = (EditText) dialog2.findViewById(R.id.edtjurusan);

                alamatmhs = (EditText) dialog2.findViewById(R.id.edtalamat);





                insert = (Button) dialog2.findViewById(R.id.btninsert);

                reset = (Button) dialog2.findViewById(R.id.btnreset);

                reset.setOnClickListener(new View.OnClickListener() {

                    @Override

                    public void onClick(View v) {

                        nimmhs.setText("");

                        namamhs.setText("");

                        alamatmhs.setText("");

                        jurusanmhs.setText("");



                    }

                });

                insert.setOnClickListener(new View.OnClickListener() {

                    @Override

                    public void onClick(View v) {

                        strnim = nimmhs.getText().toString();

                        strnama = namamhs.getText().toString();

                        strjurusan = jurusanmhs.getText().toString();

                        stralamat = alamatmhs.getText().toString();



                        insertDataMahasiswa();

                        getDataMahasiswa();



                    }

                });

                dialog2.show();

            }

        });



        //inisialisasi

        listmahasiswa = (ListView) findViewById(R.id.listmahasiswa);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);

        swipeRefreshLayout.setOnRefreshListener(this);

        swipeRefreshLayout.post(new Runnable() {

                                    @Override

                                    public void run() {



                                        getDataMahasiswa();

                                    }

                                }

        );

    }



    private void getDataMahasiswa() {

        overridePendingTransition(0, 0);

        progressDialog = ProgressDialog.show(DataMahasiswaActivity.this, "", " Proses...");

        RestAdapter adapter = new RestAdapter.Builder()

                .setEndpoint(ROOT_URL) //Setting the Root URL

                .build(); //Finally building the adapter



        //Creating object for our interface

        ModuleAPI api = adapter.create(ModuleAPI.class);



        //Calling method to get whether report

        api.getDataMahasiswa(



                new Callback() {

                    @Override

                    public void success(CDataMahasiswa cdataMahasiswa, Response response) {

                        listdatamahasiswa = new ArrayList();

                        listdatamahasiswa = cdataMahasiswa.getDataMahasiswa();

                        final String[] nim = new String[listdatamahasiswa.size()];

                        final String[] nama = new String[listdatamahasiswa.size()];

                        final String[] alamat = new String[listdatamahasiswa.size()];

                        final String[] jurusan = new String[listdatamahasiswa.size()];



                        for (int i = 0; i < listdatamahasiswa.size(); i++) {

                            nim[i] = listdatamahasiswa.get(i).getNim().toString();

                            nama[i] = listdatamahasiswa.get(i).getNama().toString();

                            alamat[i] = listdatamahasiswa.get(i).getAlamat().toString();

                            jurusan[i] = listdatamahasiswa.get(i).getJurusan().toString();

                        }



                        cariMahasiswa = new AdapterCariMahasiswa(DataMahasiswaActivity.this, nim, nama,

                                alamat, jurusan);

                        listmahasiswa.setAdapter(cariMahasiswa);

                        listmahasiswa.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                            @Override

                            public void onItemClick(AdapterView parent, View view, int position, long id) {

                                dialog = new Dialog(DataMahasiswaActivity.this);

                                dialog.setTitle("data mahasiswa");

                                dialog.setCanceledOnTouchOutside(false);

                                dialog.setContentView(R.layout.tampilaneditdata);



                                nimmhs = (EditText) dialog.findViewById(R.id.edtnim);

                                namamhs = (EditText) dialog.findViewById(R.id.edtnama);

                                jurusanmhs = (EditText) dialog.findViewById(R.id.edtjurusan);

                                alamatmhs = (EditText) dialog.findViewById(R.id.edtalamat);



                                nimmhs.setEnabled(false);

                                nimmhs.setText(nim[position]);

                                namamhs.setText(nama[position]);

                                jurusanmhs.setText(jurusan[position]);

                                alamatmhs.setText(alamat[position]);

                                update = (Button) dialog.findViewById(R.id.btnupdate);

                                delete = (Button) dialog.findViewById(R.id.btnhapus);

                                reset = (Button) dialog.findViewById(R.id.btnreset);



                                reset.setOnClickListener(new View.OnClickListener() {

                                    @Override

                                    public void onClick(View v) {

                                        nimmhs.setText("");

                                        namamhs.setText("");

                                        alamatmhs.setText("");

                                        jurusanmhs.setText("");



                                    }

                                });

                                update.setOnClickListener(new View.OnClickListener() {

                                    @Override

                                    public void onClick(View v) {

                                        updateDataMahasiswa();

                                        getDataMahasiswa();

                                    }

                                });

                                delete.setOnClickListener(new View.OnClickListener() {

                                    @Override

                                    public void onClick(View v) {

                                        strnim = nimmhs.getText().toString();

                                        hapusDataMahasiswa();

                                        getDataMahasiswa();

                                    }

                                });

                                dialog.show();

                            }

                        });



                        progressDialog.dismiss();

                    }



                    @Override

                    public void failure(RetrofitError error) {



                        String merror = error.getMessage();

                        progressDialog.dismiss();

                        Toast.makeText(DataMahasiswaActivity.this, "err " + merror.toString(),

                                Toast.LENGTH_LONG).show();

                    }

                }



        );





    }



    private void hapusDataMahasiswa() {

        RestAdapter adapter = new RestAdapter.Builder()

                .setEndpoint(ROOT_URL) //Setting the Root URL

                .build(); //Finally building the adapter



        //Creating object for our interface

        ModuleAPI api = adapter.create(ModuleAPI.class);



        //Defining the method insertuser of our interface

        api.deleteData(

                //Passing the values by getting it from editTexts

                strnim.toString(),

                //Creating an anonymous callback

                new Callback() {

                    @Override

                    public void success(Response result, Response response) {

                        Toast.makeText(DataMahasiswaActivity.this, "informasi \n",

                                Toast.LENGTH_SHORT).show();

                        dialog.dismiss();

                    }



                    @Override

                    public void failure(RetrofitError error) {

                        //If any error occured displaying the error as toast

                        Toast.makeText(DataMahasiswaActivity.this, "Kesalahan Koneksi Data",

                                Toast.LENGTH_LONG).show();

                        dialog.setCancelable(false);

                    }

                }

        );



    }



    private void insertDataMahasiswa() {

        RestAdapter adapter = new RestAdapter.Builder()

                .setEndpoint(ROOT_URL) //Setting the Root URL

                .build(); //Finally building the adapter



        //Creating object for our interface

        ModuleAPI api = adapter.create(ModuleAPI.class);



        //Defining the method insertuser of our interface

        api.insertData(

                //Passing the values by getting it from editTexts

                strnim.toString(),

                strnama.toString(),

                stralamat.toString(),

                strjurusan.toString(),



                //Creating an anonymous callback

                new Callback() {

                    @Override

                    public void success(Response result, Response response) {

                        //On success we will read the server's output using bufferedreader

                        //Creating a bufferedreader object

                        BufferedReader reader = null;



                        //An string to store output from the server

                        String output = "";



                        try {

                            //Initializing buffered reader

                            reader = new BufferedReader(new InputStreamReader(result.getBody().in()));



                            //Reading the output in the string

                            output = reader.readLine();

                        } catch (IOException e) {

                            e.printStackTrace();

                        }

                        //  btncall.setEnabled(true);

                        Toast.makeText(DataMahasiswaActivity.this, "informasi \n" + output,

                                Toast.LENGTH_SHORT).show();



                        overridePendingTransition(0, 0);

                        dialog2.dismiss();

                    }



                    @Override

                    public void failure(RetrofitError error) {

                        //If any error occured displaying the error as toast

                        Toast.makeText(DataMahasiswaActivity.this, "Kesalahan Koneksi Data",

                                Toast.LENGTH_LONG).show();

                        dialog2.setCancelable(false);

                        //  btncall.setEnabled(true);

                    }

                }

        );

    }



    private void updateDataMahasiswa() {

        //Here we will handle the http request to insert user to mysql db

        //Creating a RestAdapter

        strnim = nimmhs.getText().toString();

        strnama = namamhs.getText().toString();

        strjurusan = jurusanmhs.getText().toString();

        stralamat = alamatmhs.getText().toString();



        RestAdapter adapter = new RestAdapter.Builder()

                .setEndpoint(ROOT_URL) //Setting the Root URL

                .build(); //Finally building the adapter



        //Creating object for our interface

        ModuleAPI api = adapter.create(ModuleAPI.class);



        //Defining the method insertuser of our interface

        api.updateData(

                //Passing the values by getting it from editTexts

                strnim.toString(),

                strnama.toString(),

                stralamat.toString(),

                strjurusan.toString(),

                //Creating an anonymous callback

                new Callback() {

                    @Override

                    public void success(Response result, Response response) {

                        //On success we will read the server's output using bufferedreader

                        //Creating a bufferedreader object

                        BufferedReader reader = null;



                        //An string to store output from the server

                        String output = "";



                        try {

                            //Initializing buffered reader

                            reader = new BufferedReader(new InputStreamReader(result.getBody().in()));



                            //Reading the output in the string

                            output = reader.readLine();

                            Toast.makeText(DataMahasiswaActivity.this, "informasi \n" + output,

                                    Toast.LENGTH_SHORT).show();

                        } catch (IOException e) {

                            e.printStackTrace();

                        }

                        dialog.dismiss();

                    }



                    @Override

                    public void failure(RetrofitError error) {

                        //If any error occured displaying the error as toast

                        Toast.makeText(DataMahasiswaActivity.this, "Kesalahan Koneksi Data",

                                Toast.LENGTH_LONG).show();

                        dialog.setCancelable(false);

                        //  btncall.setEnabled(true);

                    }

                }

        );

    }



    @Override

    public void onRefresh() {

        getDataMahasiswa();

        swipeRefreshLayout.setRefreshing(false);

        overridePendingTransition(0, 0);

        overridePendingTransition(0, 0);



    }



}

Membuat activity_data_mahasiswa.xml, tambahkan kode berikut:
xml version="1.0" encoding="utf-8"?>

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="giviews.id.crud_mahasiswa.DataMahasiswaActivity">



    
        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:theme="@style/AppTheme.AppBarOverlay">



        
            android:id="@+id/toolbar"

            android:layout_width="match_parent"

            android:layout_height="?attr/actionBarSize"

            android:background="?attr/colorPrimary"

            app:popupTheme="@style/AppTheme.PopupOverlay" />



    



    layout="@layout/data_mahasiswa" />



    
        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_dialog_email" />





Kemudian data_mahasiswa.xml disini untuk memasukan listviewnya, berikut ini kode nya:
xml version="1.0" encoding="utf-8"?>


    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:id="@+id/swipe_refresh_layout"

    android:layout_height="match_parent"

    app:layout_behavior="@string/appbar_scrolling_view_behavior"

    tools:showIn="@layout/data_mahasiswa">



    
        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:id="@+id/listmahasiswa">




Membuat AdapterCari Mahasiswa.java, berikut kode programnya:
public class AdapterCariMahasiswa extends BaseAdapter {



    public Context activity;

    private String[] nim, nama, alamat, jurusan;

    public TextView tvnamamahasiswa, tvnim, tvjurusan, tvalamat;

    private static LayoutInflater inflater = null;



    public AdapterCariMahasiswa(DataMahasiswaActivity dataMahasiswaActivity, String[] nim, String[]

            nama, String[] alamat, String[] jurusan) {

        activity = dataMahasiswaActivity;

        this.nim = nim;

        this.nama = nama;

        this.alamat = alamat;

        this.jurusan = jurusan;

    }

    @Override

    public int getCount() {

        return nama.length;

    }



    @Override

    public Object getItem(int position) {

        return position;

    }



    @Override

    public long getItemId(int position) {

        return position;

    }





    @Override

    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater)

                activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        convertView = inflater.inflate(R.layout.layoutlistcarimahasiswa, null);

        tvnamamahasiswa = (TextView) convertView.findViewById(R.id.tvnamamahasiswa);

        tvnim = (TextView) convertView.findViewById(R.id.tvnim);

        tvjurusan = (TextView) convertView.findViewById(R.id.tvjurusan);

        tvalamat = (TextView) convertView.findViewById(R.id.tvalamat);



        tvnamamahasiswa.setText(nama[position].toString());

        tvnim.setText(nim[position].toString());

        tvjurusan.setText(jurusan[position].toString());

        tvalamat.setText(alamat[position].toString());

        return convertView;

    }



}

selanjutnya tambhkan kode berikut pada layoutcarimahasiswa.xml:
xml version="1.0" encoding="utf-8"?>

xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:orientation="vertical">



    
        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:background="#ffffff"

        android:orientation="horizontal">





        
            android:id="@+id/layoutkanan"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:orientation="horizontal">



            
                android:layout_width="70dp"

                android:layout_height="wrap_content"

                android:orientation="vertical">



                
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_margin="2dp"

                    android:text="nim"

                    android:textColor="#000000"

                    android:textSize="12sp" />



                
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_margin="2dp"

                    android:text="nama"

                    android:textColor="#000000"

                    android:textSize="12sp" />





                
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_margin="2dp"

                    android:text="jurusan"

                    android:textColor="#000000"

                    android:textSize="15sp" />



                
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_margin="2dp"

                    android:text="alamat"

                    android:textColor="#000000"

                    android:textSize="12sp" />



            



            
                android:layout_width="10dp"

                android:layout_height="wrap_content"

                android:orientation="vertical">



                
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_margin="2dp"

                    android:text=":"

                    android:textColor="#000000"

                    android:textSize="12sp" />



                
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_margin="2dp"

                    android:text=":"

                    android:textColor="#000000"

                    android:textSize="12sp" />





                
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_margin="2dp"

                    android:text=":"

                    android:textColor="#000000"

                    android:textSize="15sp" />



                
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_margin="2dp"

                    android:text=":"

                    android:textColor="#000000"

                    android:textSize="12sp" />





            


                            android:layout_width="match_parent"
               
android:layout_height="wrap_content"
               
android:orientation="vertical">
                                   
android:id="@+id/tvnim"
                   
android:layout_width="wrap_content"
                   
android:layout_height="wrap_content"
                   
android:layout_margin="2dp"
                    
android:hint="nim"
                   
android:textColor="#000000"
                   
android:textColorHint="#000000"
                   
android:textSize="12sp" />

                                   
android:id="@+id/tvnamamahasiswa"
                   
android:layout_width="wrap_content"
                   
android:layout_height="wrap_content"
                   
android:layout_margin="2dp"
                   
android:hint="nama"
                   
android:textColor="#000000"
                   
android:textColorHint="#000000"
                   
android:textSize="12sp" />


                                   
android:id="@+id/tvjurusan"
                   
android:layout_width="wrap_content"
                    
android:layout_height="wrap_content"
                   
android:layout_margin="2dp"
                   
android:hint="jurusan"
                   
android:textColor="#000000"
                   
android:textColorHint="#000000"
                    
android:textSize="15sp" />

                                   
android:id="@+id/tvalamat"
                   
android:layout_width="wrap_content"
                   
android:layout_height="wrap_content"
                   
android:layout_margin="2dp"
                   
android:hint="alamat"
                   
android:textColor="#000000"
                   
android:textColorHint="#000000"
                   
android:textSize="12sp" />


           


       

 

Kemudian tambahkan kode berikut pada layout tampilaneditdata.xml:
xml version="1.0" encoding="utf-8"?>

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="match_parent"

    android:orientation="vertical">



    
        android:id="@+id/edtnim"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="nim"

        android:inputType="text"

        android:textSize="25sp" />



    
        android:id="@+id/edtnama"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="nama"

        android:inputType="text"

        android:textSize="25sp" />



    
        android:id="@+id/edtjurusan"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="jurusan"

        android:inputType="text"

        android:textSize="25sp" />



    
        android:id="@+id/edtalamat"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="alamat"

        android:inputType="text"

        android:textSize="25sp" />



    
        android:layout_width="match_parent"

        android:layout_height="wrap_content">

        android:id="@+id/btnupdate"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="update"

            android:layout_weight="1"/>



        android:layout_weight="1"

            android:id="@+id/btnhapus"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="hapus" />

        android:layout_weight="1"

            android:id="@+id/btnreset"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="reset" />





    



Kemudian tambahkan kode berikut pada layout tampilaninserdata.xml :

xml version="1.0" encoding="utf-8"?>

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="match_parent"

    android:orientation="vertical">



    
        android:id="@+id/edtnim"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="nim"

        android:inputType="text"

        android:textSize="25sp" />



    
        android:id="@+id/edtnama"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="nama"

        android:inputType="text"

        android:textSize="25sp" />



    
        android:id="@+id/edtjurusan"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="jurusan"

        android:inputType="text"

        android:textSize="25sp" />



    
        android:id="@+id/edtalamat"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="alamat"

        android:inputType="text"

        android:textSize="25sp" />



    
        android:layout_width="match_parent"

        android:layout_height="wrap_content">



        android:id="@+id/btninsert"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="insert"

            android:layout_weight="1"/>



        android:layout_weight="1"

            android:id="@+id/btnreset"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="reset" />

    



Selanjutnya jalankan programnya, jika tampil data nya berarti anda telah berhasil membuat program dengan menggunakan Restful Api di android, sekianlah tutorial kali ini semoga bermanfaat, jika ada yang ingin ditanyakan silakan tuliskan pertanyaan anda pada kolom komentar di bawah.

tampilan view Data Mahasiswa
tampilan insert data Mahasiswa
tampilan edit Data Mahasiswa