[Experiment] The mobile terminal application development 2: database using SQLite

Disclaimer: This article is a blogger original article. Reproduced please contact bloggers authorization. Bloggers public micro-channel number] [Department of Knowing and Doing the campus. https://blog.csdn.net/cxh_1231/article/details/84454617

Note: This is WHUT School of Computer mobile terminal application development classes, Experiment 2: articles for use SQLite database.

Source Download: https://download.csdn.net/download/cxh_1231/10805430

Paper come Zhongjue know this practice is essential.


First, the purpose of the experiment:

  1. Android master the use of advanced controls and event handling methods;
  2. Familiar Android data storage scheme to master the use SQLite.

Second, the experimental content:

  1. Create a new Android application, design an input interface information of the user's name, password, phone, mail and gender;
  2. Adding to interface the "Add", "Save", "Delete" and "Empty" and other buttons and drop-down list of user names;
  3. Achieve the creation of the SQLite database connection, query and CRUD and other operations;
  4. Raw data initialization function to achieve database;
  5. Write "Add" button response code to add functionality to achieve record;
  6. When writing the code in response to drop-down list, starts the application, the drop-down list of all user names automatically loaded from the database, and the first record information is displayed in the interface. When the user selects a different user name, the user interface displays information.
  7. Write "Save", "Delete", "Clear" button response code. Respectively, to complete the changes and save the current record; delete the current record, clear interface features.

Third, the experimental guidance:

  • Create an Android application, design a GUI interface, as shown in FIG renderings.

  • SQLite database is a lightweight Android system built-in relational database. SQLite database not only supports standard SQL syntax, and follow the ACID transaction database. The basic method of operation using SQLiteDatabase SQLite database is as follows.
  • (1) create a database, the basic steps are:
    l define a class that inherits from SQLiteOpenHelper.
     method onCreate override SQLiteOpenHelper class class () method and onUpgrade ().
     create an instance of the class, call getReadableDatabase () or getWriteableDatabase () method to create the database.
    E.g:
public class BaseDBHelper extends SQLiteOpenHelper { 
       private static final String CREATE_T_MEMO = “create table t_memo(” 
                +“id integer primary key autoincrement,”
                +“memo_time text,” 
                +“memo_content text)”;
       private Context context;
       public BaseDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { 
            super(context, name, factory, version);
            this.context = context; 
        } 
        @Override 
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_T_MEMO); //创建数据库表t_memo 
        } 
        @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } 
} 
... 
        BaseDBHelper dbHelper = new BaseDBHelper(MainActivity.this, "firstdemo_db", null, 1); 
        SQLiteDatabase db = dbHelper.getWritableDatabase(); //创建数据库firstdemo_db 
...
  • insert (2) using SQLiteDataBse class () method to add data to the database. E.g:
ContentValues values = new ContentValues();
values.put("memo_time", time); 
values.put("memo_content", content); 
long f = db.insert("t_memo", null, values); //向表中插入数据
  • (3) using the query SQLiteDatabase class () method to query the data tables in the database. E.g:
Cursor cursor = db.query("t_memo", null, null, null, null, null, null); //从数据库表t_memo中读取所有数据
  • (4) update SQLiteDatabase class () method on the data in a database table is updated. E.g:
ContentValues values = new ContentValues(); 
values.put("memo_time", tv_time.getText().toString());
values.put("memo_content", et_content.getText().toString()); 
int is_succeeed = db.update("t_memo", values, "id = ? ", new String[]{memo_id}); //修改指定编号的记录
  • (5) using the delete SQLiteDatabase class () method on the data in the database table will be deleted. E.g:
int is_succeed = db.delete("t_memo", "id = ? ", new String[]{memo_id}); //从表t_memo中删除指定编号的记录
  • Radio buttons RadioButton control implemented using FIG 2. RadioButton control can be used in one of many applications. If you want to select one of the options button, the other option buttons are set to unchecked, you will need to <RadioButton> tag in a <RadioGroup> tag.
  • To make the drop-down list (with Spinner control implementation) can respond to the user's choice, the options need to listen to events on the control Spinner. The key code is as follows:
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){ 
    @Override 
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
        ... //事件处理代码 
    } 
    @Override 
    public void onNothingSelected(AdapterView<?> parent){ } 
});

Fourth, the process of recording:

1, activity_main.xml layout:

2, DBHelper.java file code:

package com.cxhit.test2;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

    private static final String CREATE_T_USER = "create table t_user("
            +"id integer primary key autoincrement,"
            +"user_Name text,"
            +"user_Password text,"
            +"user_Tel text,"
            +"user_Email text,"
            +"user_Sex int)";
    private Context context;

    public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        this.context = context;
    }
    @Override
     public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_T_USER);//创建数据表
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

3, MainActivity.java file code:

package com.cxhit.test2;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.*;
//调用
import android.widget.Toast;
import android.widget.Spinner;
import android.content.ContentValues;
import java.util.ArrayList;
import java.util.List;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    public static SQLiteDatabase database;//数据库对象
    private List<User> userList;  //用户列表

    //
    private EditText getName,getPassword,getTel,getEmail;
    private int getSex;
    //
    private Button addButton,saveButton,deleteButton,emptyButton;

    private RadioGroup sexRadio;


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

        database=getDatabase();//获得数据库对象

        //四个按钮的对象
        addButton=(Button) findViewById(R.id.buttonAdd);
        saveButton = (Button) findViewById(R.id.buttonSave);
        deleteButton = (Button) findViewById(R.id.buttonDelete);
        emptyButton = (Button) findViewById(R.id.buttonEmpty);
        //性别选项
        sexRadio = (RadioGroup) findViewById(R.id.radioSex);


        Spinner spinner = (Spinner) findViewById(R.id.spinnerNowUser);
        final List<String> datas = new ArrayList<>();
        datas.add("zhangsan");
        datas.add("lisi");
        datas.add("wangwu");
        MyAdapter adapter = new MyAdapter(this);
        spinner.setAdapter(adapter);
        adapter.setDatas(datas);

    }

    //为“添加”按钮点击点击事件
    public void buttonAdd_Click(View view){
        getName = (EditText) findViewById(R.id.editTextUsername);
        getPassword = (EditText) findViewById(R.id.editTextPassword);
        getTel = (EditText) findViewById(R.id.editTextTel);
        getEmail = (EditText) findViewById(R.id.editTextEmail);
        getSex = sexRadio.getCheckedRadioButtonId();

        if(TextUtils.isEmpty(getName.getText().toString())){
            Toast.makeText(MainActivity.this,"请输入用户名!",Toast.LENGTH_LONG).show();
        }
        else if(TextUtils.isEmpty(getPassword.getText().toString())){
            Toast.makeText(MainActivity.this,"请输入密码!",Toast.LENGTH_LONG).show();
        }
        else if(TextUtils.isEmpty(getTel.getText().toString())){
            Toast.makeText(MainActivity.this,"请输入手机号!",Toast.LENGTH_LONG).show();
        }
        else if(TextUtils.isEmpty(getEmail.getText().toString())){
            Toast.makeText(MainActivity.this,"请输入邮箱号码!",Toast.LENGTH_LONG).show();
        }
        else if(getSex<0){
            Toast.makeText(MainActivity.this,"请选择性别!",Toast.LENGTH_LONG).show();
        }else{

            //将数据保存到数据库
            ContentValues values = new ContentValues();
            values.put("user_Name",getName.getText().toString());
            values.put("user_Password",getPassword.getText().toString());
            values.put("user_Tel",getTel.getText().toString());
            values.put("user_Email",getEmail.getText().toString());
            values.put("user_Sex",getSex);
            long flag = database.insert("t_user", null, values);
            if (flag > 0) {
                Toast.makeText(MainActivity.this, "添加成功!", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(MainActivity.this, "添加失败!", Toast.LENGTH_LONG).show();
            }
        }
    }

    public void buttonSave_Click(View view){
        getName = (EditText) findViewById(R.id.editTextUsername);
        getPassword = (EditText) findViewById(R.id.editTextPassword);
        getTel = (EditText) findViewById(R.id.editTextTel);
        getEmail = (EditText) findViewById(R.id.editTextEmail);
        getSex = sexRadio.getCheckedRadioButtonId();

        if(TextUtils.isEmpty(getName.getText().toString())){
            Toast.makeText(MainActivity.this,"请输入用户名!",Toast.LENGTH_LONG).show();
        }
        else if(TextUtils.isEmpty(getPassword.getText().toString())){
            Toast.makeText(MainActivity.this,"请输入密码!",Toast.LENGTH_LONG).show();
        }
        else if(TextUtils.isEmpty(getTel.getText().toString())){
            Toast.makeText(MainActivity.this,"请输入手机号!",Toast.LENGTH_LONG).show();
        }
        else if(TextUtils.isEmpty(getEmail.getText().toString())){
            Toast.makeText(MainActivity.this,"请输入邮箱号码!",Toast.LENGTH_LONG).show();
        }
        else if(getSex<0){
            Toast.makeText(MainActivity.this,"请选择性别!",Toast.LENGTH_LONG).show();
        }else{

            //将数据保存到数据库
            ContentValues values = new ContentValues();
            values.put("user_Name",getName.getText().toString());
            values.put("user_Password",getPassword.getText().toString());
            values.put("user_Tel",getTel.getText().toString());
            values.put("user_Email",getEmail.getText().toString());
            values.put("user_Sex",getSex);
            int is_succeeed=database.update("t_user",values,"user_Name=?",new String[]{getName.getText().toString()});
           if (is_succeeed > 0) {//如果要保存的用户在数据库中
               Toast.makeText(MainActivity.this, "保存成功!", Toast.LENGTH_LONG).show();
            } else {//如果不在数据库中,改为添加操作
               long flag = database.insert("t_user", null, values);
                Toast.makeText(MainActivity.this, "保存成功!", Toast.LENGTH_LONG).show();}
        }

    }

    public void buttonDelete_Click(View view){

        getName = (EditText) findViewById(R.id.editTextUsername);
        int is_succeed=database.delete("t_user","user_Name=?",new String[]{getName.getText().toString()});
        if(is_succeed>0)
            Toast.makeText(MainActivity.this,"删除成功",Toast.LENGTH_LONG).show();
    }

    public void buttonEmpty_Click(View view){
        getName = (EditText) findViewById(R.id.editTextUsername);
        getPassword = (EditText) findViewById(R.id.editTextPassword);
        getTel = (EditText) findViewById(R.id.editTextTel);
        getEmail = (EditText) findViewById(R.id.editTextEmail);
        getSex = sexRadio.getCheckedRadioButtonId();

        getName.setText("");
        getPassword.setText("");
        getEmail.setText("");
        getTel.setText("");

        Toast.makeText(MainActivity.this,"清空成功",Toast.LENGTH_LONG).show();
    }


    //获得数据库对象
    private SQLiteDatabase getDatabase() {
        DBHelper dbHelper = new DBHelper(MainActivity.this, "demo_db", null, 1);
        return dbHelper.getReadableDatabase();
    }

}

6.3.5 Operating Screenshot:

VI Conclusion:

"Add" button, the "Save" button shix achieve the basic functions, the Delete button is not implemented. for reference only! ! !

Paper come Zhongjue know this practice is essential.

Guess you like

Origin blog.csdn.net/cxh_1231/article/details/84454617