团队——和谐共生(7)


和谐共生(7)

这次学习了数据库的简单操作,可以添加数据,并返回在listView中

效果图

 团队——和谐共生(7)

 

 

 

 代码:

<?xml version=”1.0″ encoding=”utf-8″?>

<RelativeLayout 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”

    tools:context=”.MainActivity”>

 

    <ListView

        android:id=”@+id/lv_user_list”

        android:layout_width=”match_parent”

        android:layout_height=”wrap_content”/>

    <Button

        android:layout_width=”match_parent”

        android:layout_height=”wrap_content”

        android:id=”@+id/btn_add_info”

        android:layout_alignParentBottom=”true”

        android:text=”添加”/>

 

</RelativeLayout>

<?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=”wrap_content”>

 

    <TextView

        android:layout_width=”match_parent”

        android:layout_height=”wrap_content”

        android:gravity=”center”

        android:padding=”5dp”

        android:layout_marginBottom=”3dp”

        android:text=”添加用户信息”

        android:textSize=”23dp”/>

    <EditText

        android:layout_width=”match_parent”

        android:layout_height=”wrap_content”

        android:id=”@+id/et_name”

        android:hint=”请输入姓名”/>

    <EditText

        android:layout_width=”match_parent”

        android:layout_height=”wrap_content”

        android:id=”@+id/et_desc”

        android:hint=”请输入描述”/>

    <LinearLayout

        android:layout_width=”match_parent”

        android:layout_height=”wrap_content”

        android:orientation=”horizontal”>

        <Button

            android:id=”@+id/btn_confirm”

            android:layout_width=”0dp”

            android:layout_height=”wrap_content”

            android:layout_weight=”1″

            android:text=”确定”/>

        <Button

            android:id=”@+id/btn_cancel”

            android:layout_width=”0dp”

            android:layout_height=”wrap_content”

            android:layout_weight=”1″

            android:text=”取消”/>

    </LinearLayout>

</LinearLayout>

这个是弹出界面,用来填写用户的数据。

下面这个item用来设置信息显示的布局

<?xml version=”1.0″ encoding=”utf-8″?>

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

    android:layout_width=”match_parent”

    android:padding=”3dp”

    android:orientation=”vertical”

    android:layout_height=”wrap_content”>

 

    <TextView

        android:text=”姓名”

        android:layout_width=”wrap_content”

        android:layout_height=”wrap_content”

        android:textSize=”20dp”

        android:id=”@+id/tv_name”/>

    <TextView

        android:text=”描述”

        android:layout_width=”wrap_content”

        android:layout_height=”wrap_content”

        android:textSize=”18dp”

        android:id=”@+id/tv_dec”/>

 

</LinearLayout>

后台代码

首先要有一个实体类(就不写了),平常写B/S使用的实体类

然后创建数据库和表

package com.example.dboperate;

 

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

 

import androidx.annotation.NonNull;

import androidx.annotation.Nullable;

 

public class UserOpenHelper extends SQLiteOpenHelper {

 

    public UserOpenHelper(@Nullable Context context) {

        super(context, “user.db”, null, 1);

    }

 

    @Override

    public void onCreate(SQLiteDatabase db) {

        String sql=”create table user(_id integer primary key autoincrement,name varchar(20),dec varchar(50))”;

        db.execSQL(sql);

    }

 

    @Override

    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

 

    }

}

创建适配器,数据的显示

package com.example.dboperate;

 

import android.app.Application;

import android.content.Context;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.TextView;

 

import androidx.appcompat.app.AppCompatActivity;

 

import java.util.List;

 

public class UserAdapter extends BaseAdapter {

 

    private final Context context;

    private final List<User> userList;

 

    public UserAdapter(Context context, List<User> userList){

        this.context=context;

        this.userList=userList;

    }

 

    @Override

    public int getCount() {

        return userList.size();

    }

 

    @Override

    public Object getItem(int i) {

        return userList.get(i);

    }

 

    @Override

    public long getItemId(int i) {

        return userList.get(i).getId();

    }

 

    @Override

    public View getView(int i, View view, ViewGroup viewGroup) {

        if (view==null){

            view=View.inflate(context,R.layout.item_user,null);

        }

        TextView tvName = view.findViewById(R.id.tv_name);

        TextView tvDec = view.findViewById(R.id.tv_dec);

        tvName.setText(userList.get(i).getName());

        tvDec.setText(userList.get(i).getDec());

        return view;

    }

}

数据库操作

package com.example.dboperate;

 

import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

 

import java.util.ArrayList;

import java.util.List;

 

public class UserDao {

    private final UserOpenHelper userOpenHelper;

    private static UserDao userDao=null;

 

    public UserDao(Context context) {

        userOpenHelper = new UserOpenHelper(context);

    }

    public static UserDao getInstance(Context context){

        if (userDao==null){

            userDao=new UserDao(context);

        }

        return userDao;

    }

 

    //保存

    public void insert(User user){

        SQLiteDatabase db=userOpenHelper.getWritableDatabase();

        ContentValues values=new ContentValues();

        values.put(“name”,user.getName());

        values.put(“dec”,user.getDec());

        db.insert(“user”,null,values);

        db.close();

    }

 

    //获取所有数据

    public List<User> findAll(){

        SQLiteDatabase db=userOpenHelper.getWritableDatabase();

        Cursor cursor=db.query(“user”,new String[]{“_id”,”name”,”dec”},null,null,null,null,null);

 

        List<User> userList=new ArrayList<>();

        while (cursor.moveToNext()){

            User user=new User();

            user.setId(cursor.getInt(0));

            user.setName(cursor.getString(1));

            user.setDec(cursor.getString(2));

            userList.add(user);

        }

 

        db.close();

        return userList;

    }

}

MainActivity

package com.example.dboperate;

 

import androidx.appcompat.app.AppCompatActivity;

 

import android.app.AlertDialog;

import android.os.Bundle;

import android.view.View;

import android.widget.EditText;

import android.widget.ListView;

import android.widget.Toast;

 

import java.util.List;

 

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ListView mUserList;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        //初始化控件

        initUI();

        //初始化数据

        initData();

    }

 

    private void initData() {

        UserDao userDao=UserDao.getInstance(getApplicationContext());

        List<User> userList=userDao.findAll();

        UserAdapter adapter = new UserAdapter(getApplicationContext(), userList);

        mUserList.setAdapter(adapter);

    }

 

    private void initUI() {

        mUserList=findViewById(R.id.lv_user_list);

        findViewById(R.id.btn_add_info).setOnClickListener(this);

    }

 

    @Override

    public void onClick(View view) {

        if(view.getId()==R.id.btn_add_info){

            showAlertDialog();

        }

    }

 

    private void showAlertDialog() {

        //实例化弹窗构造者对象

        AlertDialog.Builder builder=new AlertDialog.Builder(this);

        //自定义弹窗内容

        AlertDialog alertDialog= builder.create();

        View view = View.inflate(getApplicationContext(), R.layout.dialog_user_info, null);

        alertDialog.setView(view);

        alertDialog.show();

 

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

        EditText etDec=view.findViewById(R.id.et_desc);

 

 

        //点击事件

        view.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                String name=etName.getText().toString();

                String dec=etDec.getText().toString();

                if (name.length()==0||dec.length()==0){

                    Toast.makeText(getApplicationContext(),”内容不能为空”,Toast.LENGTH_SHORT).show();

                    return;

                }

                save2db(name,dec);

            }

        });

        view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                alertDialog.dismiss();

            }

        });

    }

 

    private void save2db(String name, String dec) {

        UserDao userDao=UserDao.getInstance(getApplicationContext());

        User user = new User(name, dec);

        userDao.insert(user);

        initData();//初始化数据

    }

}

 

 

 

 

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/273152.html

(0)
上一篇 2022年7月10日
下一篇 2022年7月10日

相关推荐

发表回复

登录后才能评论