Skip to content

Instantly share code, notes, and snippets.

@dwijonarko
Created September 30, 2019 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwijonarko/ef14cd1abf97743550a08dda5ac5bce7 to your computer and use it in GitHub Desktop.
Save dwijonarko/ef14cd1abf97743550a08dda5ac5bce7 to your computer and use it in GitHub Desktop.
Android CRUD + ListView
<?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"
android:gravity="center_horizontal"
tools:context=".MainActivity" >
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="23dp"
android:orientation="vertical">
<EditText
android:id="@+id/productName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="28dp"
android:ems="10"
android:hint="Name"
android:inputType="text"
android:text="" />
<EditText
android:id="@+id/productQuantity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="28dp"
android:ems="10"
android:hint="Quantity"
android:inputType="number" />
<TextView
android:id="@+id/productId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="36dp"
android:orientation="horizontal">
<Button
android:id="@+id/btn_find"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="findProduct"
android:text="@string/find_string"
tools:layout_editor_absoluteX="4dp"
tools:layout_editor_absoluteY="401dp" />
<Button
android:id="@+id/btn_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="deleteProduct"
android:text="@string/delete_string"
tools:layout_editor_absoluteX="140dp"
tools:layout_editor_absoluteY="413dp" />
<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="addProduct"
android:text="@string/add_string"
tools:layout_editor_absoluteX="296dp"
tools:layout_editor_absoluteY="341dp" />
</LinearLayout>
<ListView
android:padding="5dp"
android:id="@+id/product_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dividerHeight="2dp" />
</LinearLayout>
package com.vokasi.basisdatamobile;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Queue;
public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION=1;
private static final String DATABASE_NAME = "product.db";
private static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "_name";
public static final String COLUMN_QUANTITY = "_quantity";
public DBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_PRODUCTS_TABLE = "CREATE TABLE "+ TABLE_PRODUCTS + "(" + COLUMN_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT,"+ COLUMN_NAME
+ " TEXT,"+ COLUMN_QUANTITY +" INTEGER "+")";
db.execSQL(CREATE_PRODUCTS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_PRODUCTS);
onCreate(db);
}
public void addProduct(Product product){
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, product.get_name());
values.put(COLUMN_QUANTITY, product.get_quantity());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_PRODUCTS,null,values);
db.close();
}
public Product findProduct(String productname){
String query = "SELECT * FROM "+ TABLE_PRODUCTS +
" WHERE "+COLUMN_NAME+" = \""+ productname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
Product product = new Product();
if (cursor.moveToFirst()){
cursor.moveToFirst();
product.set_id(Integer.parseInt(cursor.getString(0)));
product.set_name(cursor.getString(1));
product.set_quantity(Integer.parseInt(cursor.getString(2)));
cursor.close();
}else{
product = null;
}
db.close();
return product;
}
public boolean deleteProduct (String productname){
boolean result = false;
String query = "SELECT * FROM "+ TABLE_PRODUCTS +
" WHERE "+COLUMN_NAME+" = \""+ productname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
Product product = new Product();
if (cursor.moveToFirst()){
cursor.moveToFirst();
product.set_id(Integer.parseInt(cursor.getString(0)));
db.delete(TABLE_PRODUCTS,COLUMN_ID+ " = ?",
new String[]{String.valueOf(product.get_id()) });
cursor.close();
result = true;
}else{
product = null;
}
db.close();
return result;
}
public ArrayList<HashMap<String,String>> allProducts(){
ArrayList<HashMap<String,String>> productList= new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM "+TABLE_PRODUCTS;
Cursor cursor = db.rawQuery(query,null);
while(cursor.moveToNext()){
HashMap<String,String> product = new HashMap<>();
product.put("id",cursor.getString(cursor.getColumnIndex(COLUMN_ID)));
product.put("name",cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
product.put("quantity",cursor.getString(cursor.getColumnIndex(COLUMN_QUANTITY)));
productList.add(product);
}
return productList;
}
}
package com.vokasi.basisdatamobile;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
TextView productId;
EditText productName;
EditText productQuantity;
ListView productListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
productId = (TextView) findViewById(R.id.productId);
productName = (EditText) findViewById(R.id.productName);
productQuantity = (EditText) findViewById(R.id.productQuantity);
productListView = (ListView) findViewById(R.id.product_list);
DBHandler handler = new DBHandler(this,null,null,1);
final ArrayList<HashMap<String,String>> productList = handler.allProducts();
String from[]={"id","name","quantity"};
int to[]={R.id.product_id,R.id.product_name,R.id.product_quantity};
ListAdapter adapter = new SimpleAdapter(MainActivity.this,productList,R.layout.product_list,from,to);
productListView.setAdapter(adapter);
}
public void addProduct(View view){
DBHandler productHandler = new DBHandler(this,null,null,1);
int qty = Integer.parseInt(productQuantity.getText().toString());
String name = productName.getText().toString();
Product product = new Product(name,qty);
productHandler.addProduct(product);
productName.setText("");
productQuantity.setText("");
DBHandler handler = new DBHandler(this,null,null,1);
ArrayList<HashMap<String,String>> productList = handler.allProducts();
String from[]={"id","name","quantity"};
int to[]={R.id.product_id,R.id.product_name,R.id.product_quantity};
ListAdapter adapter = new SimpleAdapter(MainActivity.this,productList,R.layout.product_list,from,to);
productListView.setAdapter(adapter);
Log.d("this is my array", "arr: " + productList.toString());
}
public void findProduct(View view){
DBHandler productHandler = new DBHandler(this,null,null,1);
String name = productName.getText().toString();
Product product = productHandler.findProduct(name);
if (product != null){
productId.setText(String.valueOf(product.get_id()));
productQuantity.setText(String.valueOf(product.get_quantity()));
}else{
productId.setText("No match found");
}
}
public void deleteProduct(View view){
DBHandler handler = new DBHandler(this,null,null,1);
String name = productName.getText().toString();
boolean result = handler.deleteProduct(name);
if (result){
productId.setText("Record deleted");
productName.setText("");
productQuantity.setText("");
}else{
productId.setText("No match found");
}
ArrayList<HashMap<String,String>> productList = handler.allProducts();
String from[]={"id","name","quantity"};
int to[]={R.id.product_id,R.id.product_name,R.id.product_quantity};
ListAdapter adapter = new SimpleAdapter(MainActivity.this,productList,R.layout.product_list,from,to);
productListView.setAdapter(adapter);
}
}
package com.vokasi.basisdatamobile;
public class Product {
private int _id;
private String _name;
private int _quantity;
public Product(String _name, int _quantity) {
this._name = _name;
this._quantity = _quantity;
}
public Product() {
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_name() {
return _name;
}
public void set_name(String _name) {
this._name = _name;
}
public int get_quantity() {
return _quantity;
}
public void set_quantity(int _quantity) {
this._quantity = _quantity;
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="@+id/product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16dp"
android:text="Name" />
<TextView
android:id="@+id/product_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/product_name"
android:textSize="14dp"
android:text="Id" />
<TextView
android:id="@+id/product_quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@id/product_id"
android:layout_alignBottom="@id/product_id"
android:layout_alignParentRight="true"
android:text="Quantity" />
</RelativeLayout>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment