21 January 2017

Android: Test thực hành. INSERT + ListView + SQLite

DBHelper.java
Java Android 2017
package com.example.lonely.demo.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Lonely on 1/20/2017.
 */


public class DBHelper extends SQLiteOpenHelper {

    public static String DB_NAME = "product";
    public static int DB_VERSION = 1;

    public static String TABLE_USER = "tb_product";
    public static String ID = "_id"; //Chú ý: id có dấu để tránh gặp lỗi
    public static String NAME = "name";
    public static String QUANTITY = "_quantity"; //Chú ý quantity để dấu tránh gặp lỗi


    public DBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        String sql = "CREATE TABLE " + TABLE_USER + "(" +
                ID + " INTEGER " + "PRIMARY KEY AUTOINCREMENT, " +
                NAME + " TEXT, " +
                QUANTITY + " INTEGER)";
        db.execSQL(sql);

    }

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

    }

    public String saveProduct(String name, int quantity) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(NAME, name);
        contentValues.put(QUANTITY, quantity);

        long isInsert = db.insert(TABLE_USER, null, contentValues);
        if (isInsert == -1) {
            return "Insert Fail";
        } else return "Insert Success";
    }

    public Cursor getProduct() {
        SQLiteDatabase db = this.getReadableDatabase();
        String sql = "SELECT * FROM " + TABLE_USER;
        Cursor cursor = db.rawQuery(sql, null);
        return cursor;
    }

}
item_product.xml
Java Android 2017
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="1"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:textSize="17sp"
        android:id="@+id/tv_id" />

    <TextView
        android:text="Product 1"
        android:textSize="17sp"
        android:layout_toRightOf="@id/tv_id"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:id="@+id/tv_name" />

    <TextView
        android:text="5"
        android:textSize="17sp"
        android:layout_toRightOf="@id/tv_name"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:id="@+id/tv_quantity" />
</RelativeLayout>
list_product.xml
Java Android 2017
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/lv_product" />
</LinearLayout>
ListProduct
Java Android 2017
package com.example.lonely.demo.activity;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.example.lonely.demo.R;
import com.example.lonely.demo.database.DBHelper;

/**
 * Created by Lonely on 1/20/2017.
 */

public class ListProduct extends AppCompatActivity {
    private DBHelper db;
    private Cursor cursor;
    private SimpleCursorAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_product);

        db = new DBHelper(this);

        //B1: Datasource
        cursor = db.getProduct();
//B2: Adapter adapter = new SimpleCursorAdapter( this,R.layout.item_product,cursor, new String[]{DBHelper.ID,DBHelper.NAME,DBHelper.QUANTITY}, new int[]{R.id.tv_id,R.id.tv_name,R.id.tv_quantity}, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); //B3: Listview ListView lvUser = (ListView) findViewById(R.id.lv_product); lvUser.setAdapter(adapter); } }
product_activity.xml
Java Android 2017
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.lonely.demo.activity.MainActivity">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="12"
        android:id="@+id/edt_name"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:text="Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/edt_name"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="15dp"
        android:layout_marginStart="5dp"
        android:id="@+id/textView" />

    <TextView
        android:text="Quantity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView"
        android:layout_marginTop="25dp"
        android:id="@+id/textView2" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="12"
        android:layout_below="@+id/edt_name"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="16dp"
        android:id="@+id/edt_quantity" />

    <Button
        android:text="ADD"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/edt_quantity"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="26dp"
        android:id="@+id/btn_add" />

    <Button
        android:text="VIEW"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btn_add"
        android:layout_alignLeft="@+id/btn_add"
        android:layout_alignStart="@+id/btn_add"
        android:layout_marginTop="29dp"
        android:id="@+id/btn_view" />
</RelativeLayout> 
MainActivity.java
Java Android 2017
package com.example.lonely.demo.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.lonely.demo.R;
import com.example.lonely.demo.database.DBHelper;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private DBHelper db;
    private EditText edName;
    private EditText edQuantity;
    private Button btnAdd;
    private Button btnView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.product_activity);

        db = new DBHelper(this);
        db.getReadableDatabase();

        initView();
    }

    private void initView() {
        edName = (EditText) findViewById(R.id.edt_name);
        edQuantity = (EditText) findViewById(R.id.edt_quantity);
        btnAdd = (Button) findViewById(R.id.btn_add);
        btnView = (Button) findViewById(R.id.btn_view);

        btnAdd.setOnClickListener(this);
        btnView.setOnClickListener(this);
    }
    private void onAdd() {
        if (edName.getText().toString().isEmpty()) {
            Toast.makeText(this,"Please enter product name", Toast.LENGTH_SHORT).show();
            return;
        }

        if (edQuantity.getText().toString().isEmpty()) {
            Toast.makeText(this,"Please enter product quantity", Toast.LENGTH_SHORT).show();
            return;
        }
        //Save data
        String mes = db.saveProduct(edName.getText().toString(), Integer.parseInt(edQuantity.getText().toString()));
        Toast.makeText(this, mes, Toast.LENGTH_SHORT).show();

        Intent intent = new Intent(MainActivity.this, ListProduct.class);
        startActivity(intent);
    }

    private void onView(){
        Intent intent = new Intent(MainActivity.this, ListProduct.class);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_add:
                onAdd();
                break;
            case R.id.btn_view:
                onView();
                break;
            default:
                break;
        }
    }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang