27 January 2017

Android: Làm việc với Database SQLite Update Delete P2


Update Delete 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";
    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) {

        //CREATE TABLE TBL_USER (
        //_id INTEGER PRIMARY KEY,
        // name TEXT,
        // gender TEXT,
        // des TEXT )

        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;
    }

    public String updateUser(int _id, String uName, String gender, String des) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(NAME,uName);
        contentValues.put(GENDER,gender);
        contentValues.put(DES,des);
        int isUpdate = db.update(TABLE_USER,contentValues, ID + " = ?",new String[]{_id+""});
        if (isUpdate > 0) {
            return "Update Success";
        }
        return "Update Fail";
    }

    public String deleteUser(int _id) {
        SQLiteDatabase db = this.getWritableDatabase();
        int isDelete = db.delete(TABLE_USER, ID + " = ?", new String[]{_id+""});
        if (isDelete > 0) {
            return "Delete Sucess";
        }
        return "Delete fail";
    }
}
ListUserAct.java
Java Android 2017
package com.example.lonely.demo.activity;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
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);

        lvUser.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Cursor c = (Cursor) adapter.getItem(position);
                String name = c.getString(c.getColumnIndex(DBHelper.NAME));
                String gender = c.getString(c.getColumnIndex(DBHelper.GENDER));
                String des = c.getString(c.getColumnIndex(DBHelper.DES));
                int _id = c.getInt(c.getColumnIndex(DBHelper.ID));

                Intent intent = new Intent(ListUserAct.this, UpdateAct.class);
                intent.putExtra(DBHelper.ID,_id);
                intent.putExtra(DBHelper.NAME,name);
                intent.putExtra(DBHelper.GENDER,gender);
                intent.putExtra(DBHelper.DES,des);

                startActivity(intent);

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        cursor = db.getUser();
        adapter.changeCursor(cursor);
        adapter.notifyDataSetChanged();
    }
} 
UpdateAct.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 com.example.lonely.demo.R;
import com.example.lonely.demo.database.DBHelper;

public class UpdateAct extends AppCompatActivity implements View.OnClickListener {

    private EditText eduser;
    private EditText edGender;
    private EditText edDes;
    private Button btUpdate;
    private Button btDelete;
    private DBHelper db;
    private int _id;

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

        db = new DBHelper(this);

        initView();

        Intent intent = getIntent();
        String name = intent.getStringExtra(DBHelper.NAME);
        String gender = intent.getStringExtra(DBHelper.GENDER);
        String des = intent.getStringExtra(DBHelper.DES);
        _id = intent.getIntExtra(DBHelper.ID,0);


        eduser.setText(name);
        edGender.setText(gender);
        edDes.setText(des);

    }

    private void initView() {
        eduser = (EditText) findViewById(R.id.edName);
        edGender = (EditText) findViewById(R.id.edGender);
        edDes = (EditText) findViewById(R.id.edDes);
        btUpdate = (Button) findViewById(R.id.btUpdate);
        btDelete = (Button) findViewById(R.id.btDelete);
        btUpdate.setOnClickListener(this);
        btDelete.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v == btDelete) {
            db.deleteUser(_id);
        }
        if (v == btUpdate) {
            db.updateUser(_id,eduser.getText().toString(),edGender.getText().toString(),edDes.getText().toString());
        }

        finish();
    }
}
activity_update.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_update"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.lonely.demo.activity.UpdateAct">

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

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

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

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btUpdate"
        android:layout_gravity="center"
        android:text="Update"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Delete"
        android:layout_gravity="center"
        android:id="@+id/btDelete"/>

</LinearLayout>

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang