Selasa, 24 Juni 2014

Contoh Aplikasi SQLite Berbasis Andoid Menggunakan Eclipse



1.     Membuat dua package pada satu project dengan fungsinya masing-masing, package pertama saya namakan com.androidadvance.db yaitu untuk menyimpan database yang akan dipanggil pada aplikasi jika dijalankan. Lalu ada package kedua yang saya namai com.androidadvance.screen yaitu berupa terdapat tujuh buah file java yang berfungsi untuk membuat data, menghapus data, mengupdate data, dan mencari record.




2.  beberapa file pada package com.android.screen

  •    AddRecord.java yaitu untuk membuat record baru pada SQLite :

    package com.androidadvance.screen;
     
    import com.androidadvance.db.DatabaseHelper;

    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    public class AddRecord extends Activity implements OnClickListener {

         private Button btn_addrecord;
         private EditText txtpname, txtpprice, txtpid;
         DatabaseHelper db;
         ProductModel pm;

         @Override
         protected void onCreate(Bundle savedInstanceState) {
                     // TODO Auto-generated method stub
                     super.onCreate(savedInstanceState);
                     setContentView(R.layout.addrecord);

                     txtpname = (EditText) findViewById(R.id.txtpname);
                     txtpprice = (EditText) findViewById(R.id.txtpprice);
                     btn_addrecord = (Button) findViewById(R.id.btn_addrecord);

                     txtpid = (EditText) findViewById(R.id.txtpid);
                     btn_addrecord.setOnClickListener(this);

         }

         @Override
         public void onClick(View v) {
                     // TODO Auto-generated method stub
                     switch (v.getId()) {
                     case R.id.btn_addrecord:

                                 if (txtpname.getText().toString().equals("")
                                                         || txtpprice.getText().toString().equals("")) {
                                             Toast.makeText(AddRecord.this, "Please add values..",
                                                                     Toast.LENGTH_LONG).show();
                                 } else {

                                             db = new DatabaseHelper(getApplicationContext());
                                             db.getWritableDatabase();
                                             pm = new ProductModel();
                                             pm.idno = (txtpid.getText().toString());
                                             pm.productname = txtpname.getText().toString();
                                             pm.productprice = txtpprice.getText().toString();

                                             Log.i("idno,productname,productprice", "" + pm.idno + ""
                                                                     + pm.productname + "" + pm.productprice);
                                             db.addProduct(pm);
                                             Toast.makeText(AddRecord.this, "Record Added successfully.",
                                                                     Toast.LENGTH_LONG).show();
                                             finish();
                                 }
                                 break;

                     default:
                                 break;
                     }

         }
    }





     
  • AddUpdateValues.java untuk mengupdate data yang sudah ada untuk diubah, berikut inti source code nya :    
package com.androidadvance.screen;
import com.androidadvance.db.DatabaseHelper;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddUpdateValues extends Activity implements OnClickListener {

     private Button btn_updaterecord;

     private EditText txtpname, txtpprice;

     DatabaseHelper db;

     ProductModel pm;

     Intent i;



     @Override

     protected void onCreate(Bundle savedInstanceState) {

                 // TODO Auto-generated method stub

                 super.onCreate(savedInstanceState);

                 setContentView(R.layout.addupdatevalues);



                 i = getIntent();



                 txtpname = (EditText) findViewById(R.id.txt_udatepname);

                 txtpprice = (EditText) findViewById(R.id.txt_udatepprice);

                 txtpname.setText(i.getExtras().getString("name"));

                 txtpprice.setText(i.getExtras().getString("price"));

                 btn_updaterecord = (Button) findViewById(R.id.btn_updaterecord);

                 btn_updaterecord.setOnClickListener(this);

     }

      @Override

     public void onClick(View v) {

                 // TODO Auto-generated method stub

                 switch (v.getId()) {

                 case R.id.btn_updaterecord:

                             if (txtpname.getText().toString().equals("")

                                                     || txtpprice.getText().toString().equals("")) {

                                         Toast.makeText(AddUpdateValues.this, "Please add values..",

                                                                 Toast.LENGTH_LONG).show();

                             } else {

                                          db = new DatabaseHelper(getApplicationContext());

                                         db.getWritableDatabase();

                                         pm = new ProductModel();

                                         pm.productname = txtpname.getText().toString();

                                         pm.productprice = txtpprice.getText().toString();

                                         pm.idno = i.getExtras().getString("id");



                                         Log.i(">>>>>productid<<<<<", "" + i.getExtras().getString("id"));

                                         db.updateProduct(pm);

                                         Toast.makeText(AddUpdateValues.this,

                                                                 "Record Update successfully.", Toast.LENGTH_LONG)

                                                                 .show();



                                         db.close();

                                         super.onResume();

                                         finish();
                             }

                             break;
                 }

      }

}



  •      AndroidAdvanceSQLite.java yaitu untuk menampilkan halaman utama yang berisi button Add Product, View Product, dan Search Product 

    package com.androidadvance.screen;
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.Toast;

    public class AndroidAdvanceSqliteActivity extends Activity implements
                     OnClickListener {

         private Button btn_add, btn_view, btn_search;

         /** Called when the activity is first created. */
         @Override
         public void onCreate(Bundle savedInstanceState) {
                     super.onCreate(savedInstanceState);
                     setContentView(R.layout.main);

                     btn_add = (Button) findViewById(R.id.btn_add);
                     btn_view = (Button) findViewById(R.id.btn_view);
                     btn_search = (Button) findViewById(R.id.btn_search);
                     btn_search.setOnClickListener(this);

                     btn_add.setOnClickListener(this);
                     btn_view.setOnClickListener(this);
         }

         @Override
         public void onClick(View v) {
                     // TODO Auto-generated method stub
                     switch (v.getId()) {
                     case R.id.btn_add:
                                 Intent addintent = new Intent(AndroidAdvanceSqliteActivity.this,
                                                         AddRecord.class);
                                 startActivity(addintent);
                                 break;

                     case R.id.btn_view:
                                 Intent viewintent = new Intent(AndroidAdvanceSqliteActivity.this,
                                                         ViewRecord.class);
                                 startActivity(viewintent);
                                 break;
                     case R.id.btn_search:
                                 Intent searchintent = new Intent(AndroidAdvanceSqliteActivity.this,
                                                         SearchProduct.class);
                                 startActivity(searchintent);
                                 break;
                     default:
                                 break;
                     }

         }

         public void contactMe(View v) {

                     final Intent emailIntent = new Intent(
                                             android.content.Intent.ACTION_SEND);
                     emailIntent.setType("plain/text");
                     emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                                             new String[] { "androiddevelopmentworld@gmail.com" });
                     emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                                             "Android sqlite tutorial");
                     emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
                                             "Android sqlite tutorial contact Me");
                     startActivity(Intent.createChooser(emailIntent, "Send mail..."));

         }
    }


  • ProductModel.java untuk menampilkan product dari database yang dibuat

    package com.androidadvance.screen;

    public class ProductModel {

       public String getProductname() {
             return productname;
       }

       public void setProductname(String productname) {
             this.productname = productname;
       }

       public String getProductprice() {
             return productprice;
       }

       public void setProductprice(String productprice) {
             this.productprice = productprice;
       }

       public String idno="", productname="", productprice="";

       public String getIdno() {
             return idno;
       }

       public void setIdno(String idno) {
             this.idno = idno;
       }

    }
  •   

  •       SearchProduct.java merupakan file yang mengandung fungsi sebagai mesin pencarian sebuah produk yang sudah dibuat dengan mengetikan product Id, atau product Name, berikut code nya

    package com.androidadvance.screen;
     import java.util.ArrayList;
    import java.util.List;
     import com.androidadvance.db.DatabaseHelper;
     import android.app.Activity;
    import android.content.Context;
    import android.graphics.Color;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.os.Handler;
    import android.text.Editable;
    import android.text.TextWatcher;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.AutoCompleteTextView;
    import android.widget.BaseAdapter;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.ListView;
    import android.widget.ProgressBar;
    import android.widget.RelativeLayout;
    import android.widget.TextView;
    import android.widget.Toast;

    public class SearchProduct extends Activity implements TextWatcher {
         EditText _searchbox;
         private ProgressBar showprogress;
         searchtask dotask;
         private ArrayList<ProductModel> _productList;
         ListView _listview;
         DatabaseHelper db;
         public AutoCompleteTextView myAutoComplete;
         private ArrayList<ProductModel> _productList_Temp;
         String query = "";

         @Override
         protected void onCreate(Bundle savedInstanceState) {
                     // TODO Auto-generated method stub
                     super.onCreate(savedInstanceState);
                     setContentView(R.layout.searchproduct);
                     _searchbox = (EditText) findViewById(R.id.txtsearchproduct);
                     showprogress = (ProgressBar) findViewById(R.id.showprogress);
                     _listview = (ListView) findViewById(R.id.searchlistview);
                     _searchbox.addTextChangedListener(textwatcher);

         }

         Runnable runn = new Runnable() {

                     @Override
                     public void run() {
                                 // TODO Auto-generated method stub
                                 handlersearch.sendEmptyMessage(0);
                     }
         };
         TextWatcher textwatcher = new TextWatcher() {

                     public void onTextChanged(CharSequence s, int start, int before,
                                             int count) {
                                 Log.i("---onTextChanged ----", "---------onTextChanged ----");

                                 if (_searchbox.getText().toString().length() > 2) {
                                             query = _searchbox.getText().toString().replace(" ", "%20");

                                             handlersearch.removeCallbacks(runn);
                                             handlersearch.post(runn);

                                 } else {
                                             showprogress.setVisibility(View.GONE);

                                             if (dotask != null) {
                                                         if (dotask.getStatus().equals(AsyncTask.Status.RUNNING)) {
                                                                     dotask.cancel(true);
                                                         }
                                             }

                                             handlersearch.removeCallbacks(runn);

                                             _productList = new ArrayList<ProductModel>();
                                             _productList.clear();
                                             _listview.setAdapter(new CustomBaseAdapter(SearchProduct.this,
                                                                     _productList));
                                 }

                     }

                     public void beforeTextChanged(CharSequence s, int start, int count,
                                             int after) {
                                 // TODO Auto-generated method stub

                     }

                     public void afterTextChanged(Editable s) {
                                 // TODO Auto-generated method stub

                     }
         };

         Handler handlersearch = new Handler() {

                     public void handleMessage(android.os.Message msg) {
                                 dotask = new searchtask();
                                 dotask.execute();
                     };
         };

         private class searchtask extends AsyncTask<Void, Void, Void> {

                     protected void onPreExecute() {

                                 showprogress.setVisibility(View.VISIBLE);
                     };

                     protected void onPostExecute(Void param) {
                                 // animation.dismiss();
                                 showprogress.setVisibility(View.GONE);
                                 if (_productList == null)
                                             return;

                                 ArrayList<String> item = new ArrayList<String>();

                                 for (int i = 0; i < _productList.size(); i++) {
                                             item.add(_productList.get(i).productname);
                                 }

                                 myAutoComplete = (AutoCompleteTextView) findViewById(R.id.myautocomplete);

                                 myAutoComplete.addTextChangedListener(SearchProduct.this);

                                 myAutoComplete.setAdapter(new ArrayAdapter<String>(
                                                         SearchProduct.this,
                                                         android.R.layout.simple_dropdown_item_1line, item));

                                 _productList_Temp = new ArrayList<ProductModel>();

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

                                             _productList_Temp.add(_productList.get(i));

                                 }

                                 _listview.setAdapter(new CustomBaseAdapter(SearchProduct.this,
                                                         _productList_Temp));

                     }

                     @Override
                     protected Void doInBackground(Void... params) {

                                 db = new DatabaseHelper(getApplicationContext());
                                 db.getWritableDatabase();
                                 ArrayList<ProductModel> product_list = db.getProudcts(query);

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

                                             String tidno = product_list.get(i).getIdno();

                                             System.out.println("tidno>>>>>" + tidno);
                                             String tname = product_list.get(i).getProductname();
                                             String tprice = product_list.get(i).getProductprice();

                                             ProductModel _ProductModel = new ProductModel();

                                             _ProductModel.setIdno(tidno);
                                             _ProductModel.setProductname(tname);
                                             _ProductModel.setProductprice(tprice);

                                             _productList.add(_ProductModel);
                                 }
                                 // _productList = _parser.getProductList();

                                 return null;
                     }

         }

         private class CustomBaseAdapter extends BaseAdapter {
                     LayoutInflater _inflater;

                     List<ProductModel> productList;

                     public CustomBaseAdapter(Context context, List<ProductModel> productList) {
                                 _inflater = LayoutInflater.from(context);
                                 this.productList = productList;

                     }

                     public int getCount() {
                                                                     return productList.size();
                     }

                     public Object getItem(int position) {
                                                                     return position;
                     }

                     public long getItemId(int position) {
                                                                     return position;
                     }

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

                                 ViewHolder _holder;
                                 if (convertView == null) {

                                             convertView = _inflater.inflate(R.layout.product_list, null);
                                             _holder = new ViewHolder();

                                             _holder.title = (TextView) convertView
                                                                     .findViewById(R.id.txt_title_text);
                                             _holder.price = (TextView) convertView
                                                                     .findViewById(R.id.txt_price);

                                             convertView.setTag(_holder);
                                 } else {
                                             _holder = (ViewHolder) convertView.getTag();
                                 }

                                 _holder.title.setText(productList.get(position).productname.trim());

                                 _holder.price.setText(productList.get(position).productprice);

                                 return convertView;
                     }

                     private class ViewHolder {
                                 TextView title;
                                 TextView price;
                     }
         }

         @Override
         public void afterTextChanged(Editable arg0) {
         }

         @Override
         public void beforeTextChanged(CharSequence s, int start, int count,
                                 int after) {
         }

         @Override
         public void onTextChanged(CharSequence s, int start, int before, int count) {
         }
    }

     
  •  ViewRecord.java merupakan class java yang berfungsi menampilkan data yang telah dibuat pada menu AddRecord

    package com.androidadvance.screen;
    import java.util.ArrayList;
    import com.androidadvance.db.DatabaseHelper;
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.view.View.OnClickListener;
    import android.widget.BaseAdapter;
    import android.widget.EditText;
    import android.widget.ListView;
    import android.widget.Spinner;
    import android.widget.TextView;
    import android.widget.Toast;

    public class ViewRecord extends Activity {

           private ListView listview;

           TextView totalrecords;
           DatabaseHelper db;
           public ArrayList<ProductModel> _productlist = new ArrayList<ProductModel>();

           @Override
           protected void onCreate(Bundle savedInstanceState) {
                // TODO Auto-generated method stub
                super.onCreate(savedInstanceState);
                setContentView(R.layout.viewrecord);

                totalrecords = (TextView) findViewById(R.id.totalrecords);
                listview = (ListView) findViewById(R.id.listview);
           }

           @Override
           protected void onResume() {
                // TODO Auto-generated method stub
                super.onResume();

                _productlist.clear();

                db = new DatabaseHelper(getApplicationContext());
                db.getWritableDatabase();
                ArrayList<ProductModel> product_list = db.getProudcts();

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

                            String tidno = product_list.get(i).getIdno();

                            System.out.println("tidno>>>>>" + tidno);
                            String tname = product_list.get(i).getProductname();
                            String tprice = product_list.get(i).getProductprice();

                            ProductModel _ProductModel = new ProductModel();

                            _ProductModel.setIdno(tidno);
                            _ProductModel.setProductname(tname);
                            _ProductModel.setProductprice(tprice);

                            _productlist.add(_ProductModel);
                }
                totalrecords.setText("Total Records :-" + _productlist.size());
                listview.setAdapter(new ListAdapter(this));
                db.close();

           }

           private class ListAdapter extends BaseAdapter {
                LayoutInflater inflater;
                ViewHolder viewHolder;

                public ListAdapter(Context context) {
                            // TODO Auto-generated constructor stub
                            inflater = LayoutInflater.from(context);
                }

                @Override
                public int getCount() {
                            // TODO Auto-generated method stub
                            return _productlist.size();
                }

                @Override
                public Object getItem(int position) {
                            // TODO Auto-generated method stub
                            return position;
                }

                @Override
                public long getItemId(int position) {
                            // TODO Auto-generated method stub
                            return position;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                            // TODO Auto-generated method stub
                            if (convertView == null) {

                                        convertView = inflater.inflate(R.layout.listview_row, null);
                                        viewHolder = new ViewHolder();

                                        viewHolder.txt_pname = (TextView) convertView
                                                                .findViewById(R.id.txtdisplaypname);
                                        viewHolder.txt_pprice = (TextView) convertView
                                                                .findViewById(R.id.txtdisplaypprice);

                                        viewHolder.txtidno = (TextView) convertView
                                                                .findViewById(R.id.txtdisplaypid);
                                        convertView.setTag(viewHolder);

                            } else {
                                        viewHolder = (ViewHolder) convertView.getTag();
                            }

                            viewHolder.txt_pname.setText(_productlist.get(position)
                                                    .getProductname().trim());
                            viewHolder.txt_pprice.setText(_productlist.get(position)
                                                    .getProductprice().trim());

                            viewHolder.txtidno.setText(_productlist.get(position).getIdno()
                                                    .trim());

                            final int temp = position;
                            (convertView.findViewById(R.id.btn_update))
                                                    .setOnClickListener(new OnClickListener() {

                                                                public void onClick(View arg0) {

                                                                            String _productid = String.valueOf(_productlist
                                                                                                    .get(temp).getIdno());
                                                                            String _productname = _productlist.get(temp)
                                                                                                    .getProductname();
                                                                            String _productprice = _productlist.get(temp)
                                                                                                    .getProductprice();

                                                                            Intent intent = new Intent(ViewRecord.this,
                                                                                                    AddUpdateValues.class);

                                                                            Bundle bundle = new Bundle();
                                                                            bundle.putString("id", _productid);
                                                                            bundle.putString("name", _productname);
                                                                            bundle.putString("price", _productprice);
                                                                            intent.putExtras(bundle);
                                                                            startActivity(intent);

                                                                }
                                                    });

                            (convertView.findViewById(R.id.btn_delete))
                                                    .setOnClickListener(new OnClickListener() {

                                                                public void onClick(View arg0) {

                                                                            AlertDialog.Builder alertbox = new AlertDialog.Builder(
                                                                                                    ViewRecord.this);
                                                                            alertbox.setCancelable(true);
                                                                            alertbox.setMessage("Are you sure you want to delete ?");
                                                                            alertbox.setPositiveButton("Yes",
                                                                                                    new DialogInterface.OnClickListener() {

                                                                                                                public void onClick(
                                                                                                                                        DialogInterface arg0, int arg1) {

                                                                                                                            Log.i(">>>TEMP>>>", temp + "");
                                                                                                                            Log.i(">>>getIdno>>>>>>",
                                                                                                                                               _productlist.get(temp)
                                                                                                                                                                       .getIdno().trim()
                                                                                                                                                                            + "");
                                                                                                                            System.out
                                                                                                                                               .println(">>>getIdno>>>>>>"
                                                                                                                                                                            + _productlist
                                                                                                                                                                                        .get(temp)
                                                                                                                                                                                        .getIdno()
                                                                                                                                                                                        .trim());
                                                                                                                            db.removeProduct(
                                                                                                                                               _productlist.get(temp)
                                                                                                                                                                       .getIdno().trim(),
                                                                                                                                                    "", "");

                                                                                                                            ViewRecord.this.onResume();

                                                                                                                            Toast.makeText(
                                                                                                                                               getApplicationContext(),
                                                                                                                                                    "Record Deleted...",
                                                                                                                                               Toast.LENGTH_SHORT).show();

                                                                                                                }

                                                                                                    });
                                                                            alertbox.setNegativeButton("No",
                                                                                                    new DialogInterface.OnClickListener() {
                                                                                                                public void onClick(
                                                                                                                                        DialogInterface arg0, int arg1) {

                                                                                                                }
                                                                                                    });
                                                                            alertbox.show();
                                                                }
                                                    });
                            return convertView;

                }
           }

           private class ViewHolder {
                TextView txt_pname;
                TextView txt_pprice;
                TextView txtidno;

           }

    }
     
       
 
 
2.  Berikut adalah tampilan hasil printsceen project
  •      Tampilan awal project  


  • Tampilan Add Product

 

  • Tampilan View Products
     
     
     
    • Tampilan Search
     

Tidak ada komentar: