19 January 2017

Android: Register show ListView làm việc với Database SQLite INSERT vs SELECT P1

INSERT SELECT với Database 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 anhtran on 1/18/17.
 */

public class DBHelper extends SQLiteOpenHelper{

    public static String DB_NAME = "user";
    public static int DB_VERSION = 2;

    public static String TABLE_USER = "TBL_USER";
    public static String ID = "_id"; //Chú ý: id có dấu để tránh gặp lỗi
    public static String NAME = "name";
    public static String GENDER = "gender";
    public static String DES = "des";


    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, " +
                GENDER + " TEXT, " +
                DES + " TEXT )";
        db.execSQL(sql);

    }

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

    }

    public String saveUser(String userName, String gender, String des) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(NAME,userName);
        contentValues.put(GENDER,gender);
        contentValues.put(DES,des);

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

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

}
item_user.xml
Java Android 2017
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_margin="10dp"
    android:weightSum="100">

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/tvID"
        android:text="1"
        android:layout_weight="5"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/tvUserName"
        android:text="Obama"
        android:layout_weight="75"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/tvGender"
        android:text="Male"
        android:layout_weight="20"/>

</LinearLayout>
activity_list_user.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_list_user"
    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.ListUserAct">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/lvUser">
    </ListView>

</RelativeLayout>
ListUserAct.java
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;

public class ListUserAct extends AppCompatActivity {

    private DBHelper db;
    private Cursor cursor;
    private SimpleCursorAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_user);
        db = new DBHelper(this);

        //B1: Datasource
        cursor = db.getUser();
//B2: Adapter adapter = new SimpleCursorAdapter( this,R.layout.item_user,cursor, new String[]{DBHelper.ID,DBHelper.NAME,DBHelper.GENDER}, new int[]{R.id.tvID,R.id.tvUserName,R.id.tvGender}, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); //B3: Listview ListView lvUser = (ListView) findViewById(R.id.lvUser); lvUser.setAdapter(adapter); } }
activity_main.xml
Java Android 2017
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context="com.example.lonely.demo.activity.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Register"
        android:textColor="#da0a0a"
        android:textSize="30sp"
        android:layout_gravity="center"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Username"
        android:id="@+id/edUser"/>

    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/spinner"
        android:layout_marginTop="10dp">

    </Spinner>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:inputType="textMultiLine"
        android:hint="Description"
        android:layout_marginTop="10dp"
        android:gravity="top"
        android:id="@+id/edDes"/>

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ck"
        android:text="I have read and agree."/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btRegister"
        android:text="Register"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"/>
</LinearLayout>
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.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
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 EditText edUser;
    private EditText edDes;
    private Spinner spinner;
    private CheckBox checkBox;
    private Button btRegister;
    private DBHelper db;

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

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

        initView();
    }

    private void initView() {
        edUser = (EditText) findViewById(R.id.edUser);
        edDes = (EditText) findViewById(R.id.edDes);
        spinner = (Spinner) findViewById(R.id.spinner);
        checkBox = (CheckBox) findViewById(R.id.ck);
        btRegister = (Button) findViewById(R.id.btRegister);

        btRegister.setOnClickListener(this);

        String[] genders = {"Male","Female","Unknow"};

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,genders);
        spinner.setAdapter(adapter);
    }

    private void onRegister() {
        if (edUser.getText().toString().isEmpty()) {
            Toast.makeText(this,"Please enter username", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!checkBox.isChecked()) {
            Toast.makeText(this,"Please agree rules", Toast.LENGTH_SHORT).show();
            return;
        }
        //Save data
        String mes = db.saveUser(edUser.getText().toString(), spinner.getSelectedItem().toString(), edDes.getText().toString());
        Toast.makeText(this, mes, Toast.LENGTH_SHORT).show();

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

    }

    @Override
    public void onClick(View v) {
        if (v == btRegister) {
            onRegister();
        }
    }

}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang