Android_U5_UI进阶作业实现思路

Android_U5_UI进阶作业实现思路

  • 使用DAO的方式访问数据库

这次作业可以参考课本P158页的例子,实现起来也比课本习题简单,先按照SimpleAdapter实现试试,看看能否完成

老师要求效果:                                 自己实现的效果:

 Android_U5_UI进阶作业实现思路_第1张图片Android_U5_UI进阶作业实现思路_第2张图片

准备工作:改变这个安卓应用主题、编写xml布局

  1. 打开清单文件修改主题和标题
  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       
    package="com.example.u5_homework">

        <
    application
           
    android:allowBackup="true"
           
    android:icon="@mipmap/ic_launcher"
           
    android:label="@string/app_name"
           
    android:roundIcon="@mipmap/ic_launcher_round"
           
    android:supportsRtl="true"
           
    android:theme="@style/Theme.AppCompat.DayNight.DarkActionBar">
            <activity android:name=".MainActivity" android:label="SaveInDatabase">
                <intent-filter>
                    <
    action android:name="android.intent.action.MAIN" />

                    <
    category android:name="android.intent.category.LAUNCHER" />
                intent-filter>
            activity>
        application>
    manifest>
  2.  

 

  1. 编写主布局及表项布局listview

activity_main.xml

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:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".MainActivity"

    android:padding="20dp">

    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content">

        <TextView

            android:layout_width="0dp"

            android:layout_weight="1"

            android:layout_height="match_parent"

            android:textSize="16sp"

            android:gravity=""

            android:text="姓名:"

            >TextView>

        <EditText

            android:id="@+id/et_name"

            android:layout_width="0dp"

            android:layout_weight="1"

            android:layout_height="wrap_content">EditText>

    LinearLayout>

    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content">

        <TextView

            android:layout_width="0dp"

            android:layout_weight="1"

            android:layout_height="match_parent"

            android:gravity=""

            android:textSize="16sp"

            android:text="年龄:"

            >TextView>

        <EditText

            android:id="@+id/et_age"

            android:layout_width="0dp"

            android:layout_weight="1"

            android:layout_height="wrap_content">EditText>

    LinearLayout>

    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_gravity="center"

        android:layout_marginTop="20dp"

        android:padding="0dp"

        android:orientation="horizontal">

        <Button

            android:id="@+id/bt_add"

            android:layout_width="0dp"

            android:layout_weight="1"

            android:layout_height="wrap_content"

            android:layout_marginRight="20dp"

            android:text="存入"

            >Button>

        <Button

            android:id="@+id/bt_del"

            android:layout_width="0dp"

            android:layout_weight="1"

            android:layout_height="wrap_content"

            android:text="清空数据库"

            >Button>

    LinearLayout>

    <LinearLayout

        android:orientation="horizontal" android:layout_width="match_parent"

        android:layout_height="wrap_content">

        <TextView

            android:text="序号"

            android:gravity="center"

            android:id="@+id/tv_id"

            android:layout_width="0dp"

            android:layout_weight="1"

            android:layout_height="wrap_content"

            >

        TextView>

        <TextView

            android:text="姓名"

            android:gravity="center"

            android:id="@+id/tvname"

            android:layout_width="0dp"

            android:layout_weight="2"

            android:layout_height="wrap_content">TextView>

        <TextView

            android:text="年龄"

            android:gravity="center"

            android:id="@+id/tvage"

            android:layout_width="0dp"

            android:layout_weight="2"

            android:layout_height="wrap_content">TextView>

    LinearLayout>

    <ListView

        android:id="@+id/listView"

        android:layout_width="match_parent"

        android:layout_height="wrap_content">

    ListView>

  

LinearLayout>
 

List_item.xml

xml version="1.0" encoding="utf-8"?>

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="horizontal" android:layout_width="match_parent"

    android:layout_height="match_parent">

    <TextView

        android:id="@+id/tv_id"

        android:layout_width="0dp"

        android:layout_weight="1"

        android:layout_height="wrap_content"

        >

    TextView>

    <TextView

        android:id="@+id/tvname"

        android:layout_width="0dp"

        android:layout_weight="2"

        android:layout_height="wrap_content">TextView>

    <TextView

        android:id="@+id/tvage"

        android:layout_width="0dp"

        android:layout_weight="2"

        android:layout_height="wrap_content">TextView>

LinearLayout>

 

到此,准备工作完毕

  1. 设计抽象类SQLiteOpenHelper的子类MyDbHelper,其代码如下:
public class MyDbHelper extends SQLiteOpenHelper {

    public static final String TB_NAME = "users";

    public MyDbHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {

        super(context, name, factory, version);

    }

  

    @Override

    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE IF NOT EXISTS "+TB_NAME+"(_id integer primary key autoincrement,"+

                "name varchar,"+"age integer " + ")" );

    }

  

    @Override

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

        db.execSQL("DROP TABLE IF EXISTS "+TB_NAME);

        onCreate(db);

    }

}

 

  1. 封装对数据库增删改查的方法到MyDao中

本类MyDAO调用了打开数据库的助手类MyDbHelper

本类MyDAO提供对数据库test.db的表users的增删改查

查询数据库表所有记录的方法:allQuery()

插入记录的方法:insertInfo(String name,int age)

删除所有记录的方法deleteAllInfo()

public class MyDAO {

    private SQLiteDatabase myDb;

    private MyDbHelper dbHelper;

    public MyDAO(Context context){

        dbHelper = new MyDbHelper(context,"test.db",null,1);

        myDb = dbHelper.getReadableDatabase();

    }

    public Cursor allQuery(){

        return myDb.rawQuery("select * from users",null);

    }

    public int getRecordsNumber(){

        return allQuery().getCount();

    }

    public void insertInfo(String name,int age){

        myDb = dbHelper.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put("name",name);

        values.put("age",age);

        long rowid = myDb.insert(MyDbHelper.TB_NAME,null,values);

        if (rowid==-1){

            Log.i("myDbDemo","数据库插入失败!");

        }else {

            Log.i("myDbDemo","数据库插入成功!"+rowid);

        }

    }

    public void deleteAllInfo(){

        int i = myDb.delete(MyDbHelper.TB_NAME,null,null);

        if (i>0){

            Log.i("myDbDemo","数据删除成功!");

        }else {

            Log.i("myDbDemo","数据未删除");

        }

    }

}

 

  1. 编写MainActivity程序:

MainActivity中完成对数据库的插入和查询,使用了MyDAO类的相关方法

首次运行时,增加两条记录并使用ListView空间显示出来

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private MyDAO myDAO;

    private ListView listView;

    private List> listData;

    private Map listItem;

    private SimpleAdapter listAdapter;

    private EditText et_name;

    private EditText et_age;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Button bt_add = (Button)findViewById(R.id.bt_add);

        bt_add.setOnClickListener(this);

        Button bt_del = (Button)findViewById(R.id.bt_del);

        bt_del.setOnClickListener(this);

        et_name = (EditText)findViewById(R.id.et_name);

        et_age = (EditText)findViewById(R.id.et_age);

        myDAO = new MyDAO(this);

        if (myDAO.getRecordsNumber()==0){//初始化一些表项布局

            myDAO.insertInfo("xiaoming",20);

            myDAO.insertInfo("wangqiang",23);

        }

        displayRecords();

    }

  

    private void displayRecords() {

        listView = (ListView)findViewById(R.id.listView);

        listData = new ArrayList>();

        Cursor cursor = myDAO.allQuery();

        while (cursor.moveToNext()){

            int id = cursor.getInt(0);

            String name = cursor.getString(1);

            int age = cursor.getInt(cursor.getColumnIndex("age"));

            listItem = new HashMap();//必须在循环体中新建

            listItem.put("_id",id);

            listItem.put("name",name);

            listItem.put("age",age);

            listData.add(listItem);

        }

        listAdapter = new SimpleAdapter(this,listData,R.layout.list_item,new String[]{"_id","name","age"},new int[]{R.id.tv_id,R.id.tvname,R.id.tvage});

        listView.setAdapter(listAdapter);

    }

  

    @Override

    public void onClick(View v) {

        String p1 = et_name.getText().toString().trim();

        String p2 = et_age.getText().toString().trim();

        switch (v.getId()){

            case R.id.bt_add:

                if (p1.equals("")||p2.equals("")){

                    Toast.makeText(getApplicationContext(),"姓名和年龄不能为空",Toast.LENGTH_SHORT).show();

                }else {

                    myDAO.insertInfo(p1,Integer.parseInt(p2));//第二个参数要转成符合数据库的类型

                }

                displayRecords();

                break;

            case R.id.bt_del:

                myDAO.deleteAllInfo();

                displayRecords();

                break;

        }

    }

}

 

如果想消除数据库表autoincrement的影响可以在MainActivity修改此处代码,即可实现每次都是从序号1开始递增

 

你可能感兴趣的:(Android)