SQLiteDatabase和listView结合,数据库可更新,listview动态刷新,数据库存入数据输入的时间

项目介绍 及 总体思路

项目功能是查询同学发量变化的数据,可以对数据库进行增加(删除功能未做)。记录一下编写过程,同时也是学习过程。
对整个学校建立一个SQLiteDataBase,可以查看学生发量数据:

  • 在listview中展示同学名单,可根据sqlitedatabase数据变化而刷新页面
  • 为listview设置监听,可跳转到学生详细数据页面
  • 对数据库进行处理:
    • 建立数据库,add按钮监听,生成一张表
    • 长按删除条目,同时删除对应表(暂时不做)

所有学生的数据存在一张表中(表名info),数据展示时,以名字为条件查询所有数据,保存为volume_list展示。
首先实现listview展示条目的刷新和监听,这部分并没有将数据存入database中,为了数据方便传递,使用了数据类,类中包含静态的list。
然后修改代码,将学生数据存入database中,此时不再使用静态list传递数据,而是写一个帮助类,对数据库进行查询来传递数据。(复习的时候可以直接从第二部分开始看)
(数据库时间是后面新加的功能,实现页面见第三部分)
具体实现页面:
app界面

[1] 实现listview展示条目的刷新和监听

实现界面如下,可输入数据,点击添加后会展示在上方的界面中。listview设置了监听,点击跳转到详细界MainActivity界面
点击item后:
数据展示页面
具体实现如下:
包括
所有文件
以及三个布局文件:
布局文件

主页面的布局文件:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:orientation="vertical"  
    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.listview_0710.MainActivity" >  
  
    <ListView  
        android:layout_width="match_parent"  
        android:layout_height="270dp"  
        android:id="@+id/lv_student" >  
    </ListView>  
  
    <LinearLayout  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:orientation="horizontal" >  
  
        <TextView  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:text="name:"  
            android:textSize="20dp" />  
  
        <EditText  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:id="@+id/et_name" />  
    </LinearLayout>  
  
    <LinearLayout  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:orientation="horizontal" >  
  
        <TextView  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:text="sex:"  
            android:textSize="20dp" />  
  
        <EditText  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:id="@+id/et_sex" />  
    </LinearLayout>  
  
    <LinearLayout  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:orientation="horizontal" >  
  
        <TextView  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:text="species:"  
            android:textSize="20dp" />  
  
        <EditText  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:id="@+id/et_species" />  
    </LinearLayout>  
      
    <Button  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:text="add"  
        android:id="@+id/btn_add" />  
  
</LinearLayout>  

写Student对象类:



package com.example.listView_0710_data;  
  
public class Student {  
      
    private String name;  
    private String sex;  
    private String species;  
      
    public Student(String name, String sex, String species) {  
        this.name = name;  
        this.sex = sex;  
        this.species = species;  
    }  
  
    @Override  
    public String toString() {  
        return "Student [name=" + name + ", sex=" + sex + ", species=" + species + "]";  
    }  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
    public String getSex() {  
        return sex;  
    }  
  
    public void setSex(String sex) {  
        this.sex = sex;  
    }  
  
    public String getSpecies() {  
        return species;  
    }  
  
    public void setSpecies(String species) {  
        this.species = species;  
    }  
    

为了方便数据传递,写了数据类StudentData,其中有静态的list,使用时通过类名直接调用:


package com.example.listView_0710_data;  
  
import java.util.ArrayList;  
import java.util.List;  
  
public class StudentData {  
      
    public static List<Student> student_list = new ArrayList<Student>();  
  
}  

item的数据展示界面xml文件:


<?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="match_parent"  
    android:orientation="horizontal" >  
      
    <TextView  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:id="@+id/tv_name"  
        android:layout_weight="1" />  
      
    <TextView  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:id="@+id/tv_sex"  
        android:layout_weight="1" />  
      
    <TextView  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:id="@+id/tv_species"  
        android:layout_weight="1" />  
  
</LinearLayout>  

接着写StudentAdapter,继承自ArrayAdapter。复写getView方法,将数据填入layout中。


package com.example.listview_0710;  
  
import java.util.List;  
  
import com.example.listView_0710_data.Student;  
  
import android.content.Context;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.ViewGroup;  
import android.widget.ArrayAdapter;  
import android.widget.TextView;  
  
public class StudentAdapter extends ArrayAdapter<Student> {  
  
    private int resourceId;  
  
    public StudentAdapter(Context context, int textViewsourceId, List<Student> objects) {  
        super(context, textViewsourceId, objects);  
        resourceId = textViewsourceId;  
    }  
      
    @Override  
    public View getView(int position, View convertView, ViewGroup parent) {  
        Student student = getItem(position);  
        View view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);  
        TextView tv_name = (TextView) view.findViewById(R.id.tv_name);  
        TextView tv_sex = (TextView) view.findViewById(R.id.tv_sex);  
        TextView tv_species = (TextView) view.findViewById(R.id.tv_species);  
        tv_name.setText(student.getName());  
        tv_sex.setText(student.getSex());  
        tv_species.setText(student.getSpecies());  
        return view;  
    }  
  
}  

在mainActivity中将数据加载到listview中,同时设置监听,将position传递到展示的Activity中(使用int和bundle)。在用于展示的Activity中接收position,获得对应的student对象,将信息加载到页面上(Student实例类中复写了tostring方法)。
其中,mainActivity:


package com.example.listview_0710;  
  
import com.example.listView_0710_data.Student;  
import com.example.listView_0710_data.StudentData;  
  
import android.R.layout;  
import android.app.Activity;  
import android.content.Intent;  
import android.os.Bundle;  
import android.view.Menu;  
import android.view.MenuItem;  
import android.view.View;  
import android.widget.AdapterView;  
import android.widget.Button;  
import android.widget.EditText;  
import android.widget.ListView;  
  
public class MainActivity extends Activity {  
  
    private ListView lv_student;  
    private EditText et_name;  
    private EditText et_sex;  
    private EditText et_species;  
    private Button btn_add;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        initstudent();  //初始化学生的数据  
        //将初始化数据绑定在listview上  
        StudentAdapter studentAdapter = new StudentAdapter(MainActivity.this, R.layout.student_item, StudentData.student_list);  
          
        lv_student = (ListView) findViewById(R.id.lv_student);  
        lv_student.setAdapter(studentAdapter);  
          
        addAStudent();  //增加数据,  
        studentAdapter.notifyDataSetChanged();  
          
        lv_student.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
              
            @Override  
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {  
                Intent intent = new Intent(MainActivity.this, Student_show.class);  
                Bundle bundle = new Bundle();  
                bundle.putInt("position", position);  
                intent.putExtra("bun", bundle);  
                startActivity(intent);  
            }  
        });  
    }  
  
    private void addAStudent() {  
        et_name = (EditText) findViewById(R.id.et_name);  
        et_sex = (EditText) findViewById(R.id.et_sex);  
        et_species = (EditText) findViewById(R.id.et_species);  
          
        btn_add = (Button) findViewById(R.id.btn_add);  
        btn_add.setOnClickListener(new View.OnClickListener() {  
              
            @Override  
            public void onClick(View arg0) {  
                String name = et_name.getText().toString();  
                String sex = et_sex.getText().toString();  
                String species = et_species.getText().toString();  
                Student student = new Student(name, sex, species);  
                StudentData.student_list.add(student);  
                et_name.setText("");et_sex.setText("");et_species.setText("");  
            }  
        });  
    }  
  
    private void initstudent() {  
        StudentData.student_list.add(new Student("name", "sexual", "species"));  //相当于表头  
    }  
  
}  

数据展示页面:


package com.example.listview_0710;  
  
import com.example.listView_0710_data.Student;  
import com.example.listView_0710_data.StudentData;  
  
import android.app.Activity;  
import android.content.Intent;  
import android.os.Bundle;  
import android.view.Menu;  
import android.view.MenuItem;  
import android.widget.LinearLayout;  
import android.widget.TextView;  
  
public class Student_show extends Activity {  
  
    private LinearLayout ll_student;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_student_show);  
          
        ll_student = (LinearLayout) findViewById(R.id.ll_student);  
          
        Intent intent = getIntent();  
        Bundle bundle = intent.getBundleExtra("bun");  
        int position = bundle.getInt("position");  
        Student student = StudentData.student_list.get(position);  
        //new一个TextView,用于显示学生数据。其实也可以直接在layout中提前放好TextView,然后用settext方法填进去
        TextView tv = new TextView(this);  
        tv.setText(student.toString());  
        ll_student.addView(tv);  
    }  
      
    /** 
     * 展示所有数据,这个方法暂时用不上 
     */  
    /*public void showAllData() { 
        //展示所有数据 
        for(Student student : StudentData.student_list) { 
            TextView tv = new TextView(this); 
            tv.setText(student.toString()); 
            ll_student.addView(tv); 
        } 
    }*/  
  
}  

[2] 实现数据库与listview结合,数据展示页面添加发量数据

所有用到的代码如下:
项目文件构成

需要用到SQLiteDatabase,因此首先写一个MyOpenHelper用于建立/打开数据库:


package com.example.listView_0710_data;  
  
import android.content.Context;  
import android.database.sqlite.SQLiteDatabase;  
import android.database.sqlite.SQLiteDatabase.CursorFactory;  
import android.database.sqlite.SQLiteOpenHelper;  
  
public class MyOpenHelper extends SQLiteOpenHelper {  
  
    public MyOpenHelper(Context context) {  
        super(context, "student.db", null, 1);  
    }  
  
    @Override  
    public void onCreate(SQLiteDatabase db) {  //包括姓名、性别、种族、发量,通过姓名进行查找  
        db.execSQL("create table info(_id integer  PRIMARY KEY AUTOINCREMENT ,name varchar(20),sex varchar(10),species varchar(20),volume varchar(10))");  
    }  
  
    @Override  
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {  
        // TODO Auto-generated method stub  
  
    }  
  
}  

然后写帮助类ZSGC,其中包括:

  • queryVolume():查询学生发量
  • queryStudent():查询学生名单
  • insert():将数据插入数据库

详细代码如下:


package com.example.listView_0710_data;  
  
import java.util.ArrayList;  
import java.util.HashSet;  
import java.util.Iterator;  
import java.util.List;  
import java.util.Set;  
  
import android.content.ContentValues;  
import android.content.Context;  
import android.database.Cursor;  
import android.database.sqlite.SQLiteDatabase;  
  
/** 
 * 这个类主要是帮助实现对数据库的增删改查工作 
 * @author X1 Carbon 
 * 
 */  
public class ZSGC {  
      
    private MyOpenHelper myOpenHelper;  
      
    public ZSGC(Context context) {  
        myOpenHelper = new MyOpenHelper(context);  //在构造函数中生成一个openhelper  
    }  
      
    /** 
     * 将数据插入数据库 
     * @param student  学生基本数据 
     * @param volume  发量 
     */  
    public void insert(Student student, long volume) {  
        SQLiteDatabase db = myOpenHelper.getWritableDatabase();  
          
        //借用contentvalues将数据插入database  
        ContentValues values = new ContentValues();  
        values.put("name", student.getName());  
        values.put("sex", student.getSex());  
        values.put("species", student.getSpecies());  
        values.put("volume", volume);  
          
        db.insert("info", null, values);  
    }  
      
    /** 
     * 查询制定学生发量 
     * @param name  查询对象姓名 
     * @return  volume_list 返回该名学生发量数组 
     */  
    public List<Long> queryVolume(String name){    
        List<Long> volume_list = new ArrayList<Long>();  
        SQLiteDatabase db = myOpenHelper.getWritableDatabase();  
        Cursor cursor = db.rawQuery("select * from info where name = ? order by _id", new String[] {name});  //按照名字查找数据,按照id排序  
        if(cursor != null && cursor.getCount() > 0) {  
            while(cursor.moveToNext()) {  
                long volume = cursor.getLong(4);  
                volume_list.add(volume);  
            }  
        }  
        cursor.close();  
        db.close();  
        return volume_list;  
    }  
      
    /** 
     * 查询所有学生名单 
     * @return  返回List<Student>,无重复项 
     */  
    public List<Student> queryStudent(){  
        List<Student> student_list = new ArrayList<Student>();  
          
        SQLiteDatabase db = myOpenHelper.getWritableDatabase();  
        Cursor cursor = db.rawQuery("select * from info", null);  
        if(cursor != null && cursor.getCount() > 0) {  
            while(cursor.moveToNext()) {  
                String name = cursor.getString(1);  
                String sex = cursor.getString(2);  
                String species = cursor.getString(3);  
                student_list.add(new Student(name, sex, species));  
            }  
        }  
        cursor.close();  
        db.close();  
        //删除重复项  
        List<Student> new_studentList = removeDuplicateWithOrder(student_list);  
        return new_studentList;  
    }  
  
    /** 
     * 删除list中重复的学生名单, 将list放入set自动去重。需要在实例类中复写equals和hashcode方法。 
     * @param student_list 
     * @return  new_studentList 
     */  
    private List<Student> removeDuplicateWithOrder(List<Student> student_list) {  
        Set<Student> student_set = new HashSet<Student>(student_list);  
        List<Student> new_studentList = new ArrayList<Student>(student_set);  
        return new_studentList;  
    }  
  
}  

为了实现ZSGC帮助类中去除list中的重复项,需要在Student实例类中复写equals和hashcode方法。现设定名字相同则为同一位同学
Student实例类更新如下:


package com.example.listView_0710_data;  
  
public class Student {  
      
    private String name;  
    private String sex;  
    private String species;  
      
    public Student(String name, String sex, String species) {  
        this.name = name;  
        this.sex = sex;  
        this.species = species;  
    }  
      
    /** 
     * 复写equals方法,比较两个实例对象是否相同。认为名字相同则为同一对象 
     */  
    public boolean equals(Object obj) {  
        Student s = (Student) obj;  
        return name.equals(s.name);  
    }  
      
    /** 
     * 复写hashcode方法,用于去重 
     */  
    public int hashCode() {  
        String in = name;  
        return in.hashCode();  
    }  
  
    @Override  
    public String toString() {  
        return "Student [name=" + name + ", sex=" + sex + ", species=" + species + "]";  
    }  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
    public String getSex() {  
        return sex;  
    }  
  
    public void setSex(String sex) {  
        this.sex = sex;  
    }  
  
    public String getSpecies() {  
        return species;  
    }  
  
    public void setSpecies(String species) {  
        this.species = species;  
    }  
      
      
  
}  

MainActivity中,要增加一个edittext读入发量数据,更新主界面的layout如下:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:orientation="vertical"  
    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.listview_0710.MainActivity" >  
  
    <ListView  
        android:id="@+id/lv_student"  
        android:layout_width="match_parent"  
        android:layout_height="190dp" >  
  
    </ListView>  
  
    <LinearLayout  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:orientation="horizontal" >  
  
        <TextView  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:text="name:"  
            android:textSize="20dp" />  
  
        <EditText  
            android:id="@+id/et_name"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content" />  
    </LinearLayout>  
  
    <LinearLayout  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:orientation="horizontal" >  
  
        <TextView  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:text="sex:"  
            android:textSize="20dp" />  
  
        <EditText  
            android:id="@+id/et_sex"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content" />  
    </LinearLayout>  
  
    <LinearLayout  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:orientation="horizontal" >  
  
        <TextView  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:text="species:"  
            android:textSize="20dp" />  
  
        <EditText  
            android:id="@+id/et_species"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content" />  
    </LinearLayout>  
  
    <LinearLayout  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:orientation="horizontal" >  
  
        <TextView  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:text="volume:"  
            android:textSize="20dp" />  
  
        <EditText  
            android:id="@+id/et_volume"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:hint="输入发量随时间变化值,以空格隔开" />  
    </LinearLayout>  
  
    <Button  
        android:id="@+id/btn_add"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:text="add" />  
  
</LinearLayout>  

修改mainActivity如下,主要改动点是:

  • 数据传递不是静态list,而是database
  • 新输入的数据不仅将数据放入list中,也要存入database

package com.example.listview_0710;  
  
import java.util.ArrayList;  
import java.util.List;  
  
import com.example.listView_0710_data.MyOpenHelper;  
import com.example.listView_0710_data.Student;  
import com.example.listView_0710_data.StudentData;  
import com.example.listView_0710_data.ZSGC;  
  
import android.R.layout;  
import android.app.Activity;  
import android.content.Intent;  
import android.database.sqlite.SQLiteDatabase;  
import android.os.Bundle;  
import android.view.Menu;  
import android.view.MenuItem;  
import android.view.View;  
import android.widget.AdapterView;  
import android.widget.Button;  
import android.widget.EditText;  
import android.widget.ListView;  
  
public class MainActivity extends Activity {  
  
    private ListView lv_student;  
    private EditText et_name;  
    private EditText et_sex;  
    private EditText et_species;  
    private Button btn_add;  
      
    private MyOpenHelper myOpenHelper;  
    private EditText et_volume;  
      
    private List<Student> student_list;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
          
        student_list = new ArrayList<Student>();  
          
        //初始化学生的数据  
        //initstudent();   
        myOpenHelper = new MyOpenHelper(MainActivity.this);  
        SQLiteDatabase db = myOpenHelper.getWritableDatabase();  
        ZSGC tool = new ZSGC(MainActivity.this);  
        student_list = tool.queryStudent();  
          
        //将初始化数据绑定在listview上  
        StudentAdapter studentAdapter = new StudentAdapter(MainActivity.this, R.layout.student_item, student_list);  
          
        lv_student = (ListView) findViewById(R.id.lv_student);  
        lv_student.setAdapter(studentAdapter);  
          
        addAStudent();  //增加数据,student_list更新、db更新  
        studentAdapter.notifyDataSetChanged();  //刷新listview  
          
        lv_student.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
              
            @Override  
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {  
                Intent intent = new Intent(MainActivity.this, Student_show.class);  
                Bundle bundle = new Bundle();  
                bundle.putInt("position", position);  
                intent.putExtra("bun", bundle);  
                startActivity(intent);  
            }  
        });  
    }  
  
    private void addAStudent() {  
        et_name = (EditText) findViewById(R.id.et_name);  
        et_sex = (EditText) findViewById(R.id.et_sex);  
        et_species = (EditText) findViewById(R.id.et_species);  
        et_volume = (EditText) findViewById(R.id.et_volume);  
          
        btn_add = (Button) findViewById(R.id.btn_add);  
        btn_add.setOnClickListener(new View.OnClickListener() {  
              
            @Override  
            public void onClick(View arg0) {  
                String name = et_name.getText().toString();  
                String sex = et_sex.getText().toString();  
                String species = et_species.getText().toString();  
                String volume = et_volume.getText().toString();  
                //分割volume字符串得到数据  
                String[] volume_data = volume.split(" ");  
                  
                Student student = new Student(name, sex, species);  
                student_list.add(student);  
                  
                //将数据存入db  
                SQLiteDatabase db = myOpenHelper.getWritableDatabase();  
                ZSGC tool = new ZSGC(MainActivity.this);  
                for(int i =0; i < volume_data.length; i++) {  
                    tool.insert(student, Long.valueOf(volume_data[i]));  
                }  
                  
                //把输入框清空  
                et_name.setText("");et_sex.setText("");et_species.setText("");et_volume.setText("");  
            }  
        });  
    }  
  
    private void initstudent() {  
        StudentData.student_list.add(new Student("name", "sexual", "species"));  //相当于表头  
          
    }  
  
}  

数据展示界面,需要添加发量数据。发量数据用listview展示,更新数据展示界面的layout:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    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.listview_0710.Student_show"  
    android:orientation="vertical" >  
  
    <TextView  
        android:layout_width="match_parent"  
        android:layout_height="match_parent"  
        android:textSize="20dp"  
        android:id="@+id/tv_student"  
        android:layout_weight="3" />  
      
    <ListView  
        android:layout_width="match_parent"  
        android:layout_height="match_parent"  
        android:id="@+id/lv_volume"  
        android:layout_weight="1" >  
  
    </ListView>  
  
</LinearLayout>  

数据展示界面的代码更新如下:


package com.example.listview_0710;  
  
import java.util.ArrayList;  
import java.util.List;  
  
import com.example.listView_0710_data.MyOpenHelper;  
import com.example.listView_0710_data.Student;  
import com.example.listView_0710_data.StudentData;  
import com.example.listView_0710_data.ZSGC;  
  
import android.app.Activity;  
import android.content.Intent;  
import android.os.Bundle;  
import android.view.Menu;  
import android.view.MenuItem;  
import android.widget.ArrayAdapter;  
import android.widget.LinearLayout;  
import android.widget.ListView;  
import android.widget.TextView;  
  
public class Student_show extends Activity {  
  
    private TextView tv_student;  
    private ListView lv_volume;  
      
    private List<Student> student_list;  //学生名单,用于获取被点击学生  
    private List<Long> volume_list;  //储存该学生发量  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_student_show);  
          
        tv_student = (TextView) findViewById(R.id.tv_student);  //用来展示基本信息  
        lv_volume = (ListView) findViewById(R.id.lv_volume);  //用来展示发量  
        ZSGC tool = new ZSGC(getApplicationContext());  
          
        //获取点击位置  
        Intent intent = getIntent();  
        Bundle bundle = intent.getBundleExtra("bun");  
        int position = bundle.getInt("position");  
          
        //将学生基本信息和发量表示出来  
        //[1]获得学生基本信息并展示  
        student_list = new ArrayList<Student>();  
        student_list = tool.queryStudent();  
          
        Student student = student_list.get(position);  
        tv_student.setText(student.toString());  
          
        //[2]获得该学生发量并展示  
        volume_list = new ArrayList<Long>();  
        volume_list = tool.queryVolume(student.getName());  
        ArrayAdapter<Long> arrayAdapter = new ArrayAdapter<Long>(Student_show.this, android.R.layout.simple_list_item_1, volume_list);  
        lv_volume.setAdapter(arrayAdapter);  
    }  
      
}  

[3] 实现数据输入的同时,数据录入时间自动存入(年月日时分秒)

增加一个功能,数据查询页面可以展示数据存入时间。主要任务是:

  • 修改帮助类ZSGC中的insert方法,在学生信息、发量数据插入数据库的同时,自动获取系统时间,将时间信息也存入数据库中,
  • 修改数据展示页面,写一个类继承ArrayAdapter,将时间数据、发量数据与listview适配。

最终实现效果如下:
数据展示页面实现效果
最终包含的类如下:
所有类及布局
首先,在MyOpenHelper里面,info表加上两栏,date用来记录数据录入的年月日,time用来记录数据录入的时分秒。记得要删掉虚拟机中data-data-包名文件夹中的数据库文件,不然数据库增加两栏的操作应该在update方法里面实现,同时将版本号+1。


package com.example.listView_0710_data;  
  
import android.content.Context;  
import android.database.sqlite.SQLiteDatabase;  
import android.database.sqlite.SQLiteDatabase.CursorFactory;  
import android.database.sqlite.SQLiteOpenHelper;  
  
public class MyOpenHelper extends SQLiteOpenHelper {  
  
    public MyOpenHelper(Context context) {  
        super(context, "student.db", null, 1);  
    }  
  
    @Override  
    public void onCreate(SQLiteDatabase db) {  //包括姓名、性别、种族、发量,通过姓名进行查找,date用来记录数据录入的年月日,time用来记录数据录入的时分秒  
        db.execSQL("create table info(_id integer  PRIMARY KEY AUTOINCREMENT ,name varchar(20),sex varchar(10),species varchar(20),volume varchar(10),date varchar(10),time varchar(10))");  
    }  
  
    @Override  
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {  
        // TODO Auto-generated method stub  
  
    }  
  
}  

在ZSGC类中,修改insert方法,获取当前时间,将时间放入values插入数据库。


package com.example.listView_0710_data;  
  
import java.util.ArrayList;  
import java.util.Calendar;  
import java.util.HashSet;  
import java.util.Iterator;  
import java.util.List;  
import java.util.Set;  
  
import android.content.ContentValues;  
import android.content.Context;  
import android.database.Cursor;  
import android.database.sqlite.SQLiteDatabase;  
  
/** 
 * 这个类主要是帮助实现对数据库的增删改查工作 
 * @author X1 Carbon 
 * 
 */  
public class ZSGC {  
      
    private MyOpenHelper myOpenHelper;  
      
    public ZSGC(Context context) {  
        myOpenHelper = new MyOpenHelper(context);  //在构造函数中生成一个openhelper  
    }  
      
    /** 
     * 将数据插入数据库 
     * @param student  学生基本数据 
     * @param volume  发量 
     */  
    public void insert(Student student, long volume) {  
        SQLiteDatabase db = myOpenHelper.getWritableDatabase();  
          
        //借用contentvalues将数据插入database  
        ContentValues values = new ContentValues();  
        values.put("name", student.getName());  
        values.put("sex", student.getSex());  
        values.put("species", student.getSpecies());  
        values.put("volume", volume);  
          
        //把时间信息放入表中  
        Calendar calendar = Calendar.getInstance();  
        int year = calendar.get(Calendar.YEAR);  
        int month = calendar.get(Calendar.MONTH) + 1;  
        int date = calendar.get(Calendar.DATE);  
        int hour = calendar.get(Calendar.HOUR_OF_DAY);  
        int minute = calendar.get(Calendar.MINUTE);  
        int second = calendar.get(Calendar.SECOND);  
          
        String str_date = year + "-" + month + "-" + date;  
        String str_time = hour + "-" + minute + "-" + second;  
          
        values.put("date", str_date);  
        values.put("time", str_time);  
          
        db.insert("info", null, values);  
    }  
      
    /** 
     * 查询制定学生发量 
     * @param name  查询对象姓名 
     * @return  volume_list 返回该名学生发量数组 
     */  
    public List<Long> queryVolume(String name){    
        List<Long> volume_list = new ArrayList<Long>();  
        SQLiteDatabase db = myOpenHelper.getWritableDatabase();  
        Cursor cursor = db.rawQuery("select * from info where name = ? order by _id", new String[] {name});  //按照名字查找数据,按照id排序  
        if(cursor != null && cursor.getCount() > 0) {  
            while(cursor.moveToNext()) {  
                long volume = cursor.getLong(4);  
                volume_list.add(volume);  
            }  
        }  
        cursor.close();  
        db.close();  
        return volume_list;  
    }  
      
    /** 
     * 根据名字查询时间、发量 
     * @param name 
     * @return dateAndVolumeData_list 
     */  
    public List<DateAndVolumeData> queryDateAndVolume(String name){  
          
        List<DateAndVolumeData> dateAndVolumeData_list = new ArrayList<DateAndVolumeData>();  
        SQLiteDatabase db = myOpenHelper.getWritableDatabase();  
        Cursor cursor = db.rawQuery("select * from info where name = ? order by _id", new String[] {name});  //按照名字进行查找  
        if(cursor != null && cursor.getCount() > 0) {  
            while(cursor.moveToNext()) {  
                String str_date = cursor.getString(5);  
                String str_time = cursor.getString(6);  
                int volume = cursor.getInt(4);  
                dateAndVolumeData_list.add(new DateAndVolumeData(str_date, str_time, volume));  
            }  
        }  
        cursor.close();  
        db.close();  
        return dateAndVolumeData_list;  
    }  
      
    /** 
     * 查询所有学生名单 
     * @return  返回List<Student>,无重复项 
     */  
    public List<Student> queryStudent(){  
        List<Student> student_list = new ArrayList<Student>();  
          
        SQLiteDatabase db = myOpenHelper.getWritableDatabase();  
        Cursor cursor = db.rawQuery("select * from info", null);  
        if(cursor != null && cursor.getCount() > 0) {  
            while(cursor.moveToNext()) {  
                String name = cursor.getString(1);  
                String sex = cursor.getString(2);  
                String species = cursor.getString(3);  
                student_list.add(new Student(name, sex, species));  
            }  
        }  
        cursor.close();  
        db.close();  
        //删除重复项  
        List<Student> new_studentList = removeDuplicateWithOrder(student_list);  
        return new_studentList;  
    }  
  
    /** 
     * 删除list中重复的学生名单, 将list放入set自动去重。需要在实例类中复写equals和hashcode方法。 
     * @param student_list 
     * @return  new_studentList 
     */  
    private List<Student> removeDuplicateWithOrder(List<Student> student_list) {  
        Set<Student> student_set = new HashSet<Student>(student_list);  
        List<Student> new_studentList = new ArrayList<Student>(student_set);  
        return new_studentList;  
    }  
  
}  

写一个对象类DateAndVolumedate,里面包含日期和发量数据。对象类中有两个构造方法


package com.example.listView_0710_data;  
  
import java.util.Calendar;  
  
public class DateAndVolumeData {  
      
    private String str_date;  
    private String str_time;  
    private int volume;  
    private Calendar calendar;  
      
    //有两个构造方法  
      
    public DateAndVolumeData(Calendar calendar, int volume) {  
        int year = calendar.get(Calendar.YEAR);  
        int month = calendar.get(Calendar.MONTH) + 1;  
        int date = calendar.get(Calendar.DATE);  
        int hour = calendar.get(Calendar.HOUR_OF_DAY);  
        int minute = calendar.get(Calendar.MINUTE);  
        int second = calendar.get(Calendar.SECOND);  
          
        this.str_date = year + "-" + month + "-" + date;  
        this.str_time = hour + "-" + minute + "-" + second;  
        this.volume = volume;  
        this.calendar = calendar;  
    }  
      
    public DateAndVolumeData(String str_date, String str_time, int volume) {  
          
        this.str_date = str_date;  
        this.str_time = str_time;  
          
        String[] year_month_date = str_date.split("-");  
        String[] hour_minute_second = str_time.split("-");  
        this.calendar = Calendar.getInstance();  
        calendar.set(Integer.valueOf(year_month_date[0]), Integer.valueOf(year_month_date[1]), Integer.valueOf(year_month_date[2]), Integer.valueOf(hour_minute_second[0]), Integer.valueOf(hour_minute_second[1]), Integer.valueOf(hour_minute_second[2]));  
        this.volume = volume;  
    }  
  
    public String getStr_date() {  
        return str_date;  
    }  
  
    public void setStr_date(String str_date) {  
        this.str_date = str_date;  
    }  
  
    public String getStr_time() {  
        return str_time;  
    }  
  
    public void setStr_time(String str_time) {  
        this.str_time = str_time;  
    }  
  
    public int getVolume() {  
        return volume;  
    }  
  
    public void setVolume(int volume) {  
        this.volume = volume;  
    }  
  
    public Calendar getCalendar() {  
        return calendar;  
    }  
  
    public void setCalendar(Calendar calendar) {  
        this.calendar = calendar;  
    }  
      
      
  
}  

新写一个数据展示页面的listview的layout,三个TextView框,分别显示日期、时间、发量


<?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="match_parent"  
    android:orientation="horizontal" >  
      
    <TextView  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:id="@+id/tv_date"  
        android:layout_weight="1" />  
      
    <TextView  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:id="@+id/tv_time"  
        android:layout_weight="1" />  
      
    <TextView  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:id="@+id/tv_volume"  
        android:layout_weight="1" />  
      
  
</LinearLayout>  

写一个showAdapter,用于数据展示页面的listview加载。注意mainActivity中不用修改此功能——添加新的数据存入数据库时,将当前时间同时存入——已在insert中实现。


package com.example.listview_0710;  
  
import java.util.Calendar;  
import java.util.List;  
  
import com.example.listView_0710_data.DateAndVolumeData;  
  
import android.content.Context;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.ViewGroup;  
import android.widget.ArrayAdapter;  
import android.widget.TextView;  
  
public class ShowAdapter extends ArrayAdapter<DateAndVolumeData> {  
  
    private int resourceId;  
      
    public ShowAdapter(Context context, int textViewsourceId, List<DateAndVolumeData> objects) {  
        super(context, textViewsourceId, objects);  
        resourceId = textViewsourceId;  
    }  
      
    @Override  
    public View getView(int position, View convertView, ViewGroup parent) {  
        DateAndVolumeData dateAndVolumeData = getItem(position);  
        View view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);  
          
        TextView tv_date = (TextView) view.findViewById(R.id.tv_date);  
        TextView tv_time = (TextView) view.findViewById(R.id.tv_time);  
        TextView tv_volume = (TextView) view.findViewById(R.id.tv_volume);  
          
        tv_date.setText(dateAndVolumeData.getStr_date());  
        tv_time.setText(dateAndVolumeData.getStr_time());  
        tv_volume.setText(String.valueOf(dateAndVolumeData.getVolume()));  //setText里面填字符串  
          
        return view;  
    }  
  
}  

Student_show页面中的[2]获得学生发量并展示,首先需要在ZSGC帮助类中写一个方法queryDateAndVolume(String name),通过此方法查询得到发量和时间数据。


package com.example.listView_0710_data;  
  
import java.util.ArrayList;  
import java.util.Calendar;  
import java.util.HashSet;  
import java.util.Iterator;  
import java.util.List;  
import java.util.Set;  
  
import android.content.ContentValues;  
import android.content.Context;  
import android.database.Cursor;  
import android.database.sqlite.SQLiteDatabase;  
  
/** 
 * 这个类主要是帮助实现对数据库的增删改查工作 
 * @author X1 Carbon 
 * 
 */  
public class ZSGC {  
      
    private MyOpenHelper myOpenHelper;  
      
    public ZSGC(Context context) {  
        myOpenHelper = new MyOpenHelper(context);  //在构造函数中生成一个openhelper  
    }  
      
    /** 
     * 将数据插入数据库 
     * @param student  学生基本数据 
     * @param volume  发量 
     */  
    public void insert(Student student, long volume) {  
        SQLiteDatabase db = myOpenHelper.getWritableDatabase();  
          
        //借用contentvalues将数据插入database  
        ContentValues values = new ContentValues();  
        values.put("name", student.getName());  
        values.put("sex", student.getSex());  
        values.put("species", student.getSpecies());  
        values.put("volume", volume);  
          
        //把时间信息放入表中  
        Calendar calendar = Calendar.getInstance();  
        int year = calendar.get(Calendar.YEAR);  
        int month = calendar.get(Calendar.MONTH) + 1;  
        int date = calendar.get(Calendar.DATE);  
        int hour = calendar.get(Calendar.HOUR_OF_DAY);  
        int minute = calendar.get(Calendar.MINUTE);  
        int second = calendar.get(Calendar.SECOND);  
          
        String str_date = year + "-" + month + "-" + date;  
        String str_time = hour + "-" + minute + "-" + second;  
          
        values.put("date", str_date);  
        values.put("time", str_time);  
          
        db.insert("info", null, values);  
    }  
      
    /** 
     * 查询制定学生发量 
     * @param name  查询对象姓名 
     * @return  volume_list 返回该名学生发量数组 
     */  
    public List<Long> queryVolume(String name){    
        List<Long> volume_list = new ArrayList<Long>();  
        SQLiteDatabase db = myOpenHelper.getWritableDatabase();  
        Cursor cursor = db.rawQuery("select * from info where name = ? order by _id", new String[] {name});  //按照名字查找数据,按照id排序  
        if(cursor != null && cursor.getCount() > 0) {  
            while(cursor.moveToNext()) {  
                long volume = cursor.getLong(4);  
                volume_list.add(volume);  
            }  
        }  
        cursor.close();  
        db.close();  
        return volume_list;  
    }  
      
    /** 
     * 根据名字查询时间、发量 
     * @param name 
     * @return dateAndVolumeData_list 
     */  
    public List<DateAndVolumeData> queryDateAndVolume(String name){  
          
        List<DateAndVolumeData> dateAndVolumeData_list = new ArrayList<DateAndVolumeData>();  
        SQLiteDatabase db = myOpenHelper.getWritableDatabase();  
        Cursor cursor = db.rawQuery("select * from info where name = ? order by _id", new String[] {name});  //按照名字进行查找  
        if(cursor != null && cursor.getCount() > 0) {  
            while(cursor.moveToNext()) {  
                String str_date = cursor.getString(5);  
                String str_time = cursor.getString(6);  
                int volume = cursor.getInt(4);  
                dateAndVolumeData_list.add(new DateAndVolumeData(str_date, str_time, volume));  
            }  
        }  
        cursor.close();  
        db.close();  
        return dateAndVolumeData_list;  
    }  
      
    /** 
     * 查询所有学生名单 
     * @return  返回List<Student>,无重复项 
     */  
    public List<Student> queryStudent(){  
        List<Student> student_list = new ArrayList<Student>();  
          
        SQLiteDatabase db = myOpenHelper.getWritableDatabase();  
        Cursor cursor = db.rawQuery("select * from info", null);  
        if(cursor != null && cursor.getCount() > 0) {  
            while(cursor.moveToNext()) {  
                String name = cursor.getString(1);  
                String sex = cursor.getString(2);  
                String species = cursor.getString(3);  
                student_list.add(new Student(name, sex, species));  
            }  
        }  
        cursor.close();  
        db.close();  
        //删除重复项  
        List<Student> new_studentList = removeDuplicateWithOrder(student_list);  
        return new_studentList;  
    }  
  
    /** 
     * 删除list中重复的学生名单, 将list放入set自动去重。需要在实例类中复写equals和hashcode方法。 
     * @param student_list 
     * @return  new_studentList 
     */  
    private List<Student> removeDuplicateWithOrder(List<Student> student_list) {  
        Set<Student> student_set = new HashSet<Student>(student_list);  
        List<Student> new_studentList = new ArrayList<Student>(student_set);  
        return new_studentList;  
    }  
  
}  

然后修改Student_show页面。


package com.example.listview_0710;  
  
import java.util.ArrayList;  
import java.util.List;  
  
import com.example.listView_0710_data.DateAndVolumeData;  
import com.example.listView_0710_data.Student;  
import com.example.listView_0710_data.ZSGC;  
  
import android.app.Activity;  
import android.content.Intent;  
import android.os.Bundle;  
import android.widget.ArrayAdapter;  
import android.widget.ListView;  
import android.widget.TextView;  
  
public class Student_show extends Activity {  
  
    private TextView tv_student;  
    private ListView lv_volume;  
      
    private List<Student> student_list;  //学生名单,用于获取被点击学生  
    private List<Long> volume_list;  //储存该学生发量  
    private List<DateAndVolumeData> dateAndVolumeDate_list;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_student_show);  
          
        tv_student = (TextView) findViewById(R.id.tv_student);  //用来展示基本信息  
        lv_volume = (ListView) findViewById(R.id.lv_volume);  //用来展示发量  
        ZSGC tool = new ZSGC(getApplicationContext());  
          
        //获取点击位置  
        Intent intent = getIntent();  
        Bundle bundle = intent.getBundleExtra("bun");  
        int position = bundle.getInt("position");  
          
        //将学生基本信息和发量表示出来  
        //[1]获得学生基本信息并展示  
        student_list = new ArrayList<Student>();  
        student_list = tool.queryStudent();  
          
        Student student = student_list.get(position);  
        tv_student.setText(student.toString());  
          
        //[2]获得学生发量、日期和时间,并展示  
        dateAndVolumeDate_list = new ArrayList<DateAndVolumeData>();  
        dateAndVolumeDate_list = tool.queryDateAndVolume(student.getName());  
        ShowAdapter myShowAdapter = new ShowAdapter(Student_show.this, R.layout.show_item, dateAndVolumeDate_list);  
        lv_volume.setAdapter(myShowAdapter);  
        myShowAdapter.notifyDataSetChanged();  
        /*volume_list = new ArrayList<Long>(); 
        volume_list = tool.queryVolume(student.getName()); 
        ArrayAdapter<Long> arrayAdapter = new ArrayAdapter<Long>(Student_show.this, android.R.layout.simple_list_item_1, volume_list); 
        lv_volume.setAdapter(arrayAdapter);*/  
    }  
      
}  

主程序修改addStudent()方法,增加一个判断语句,提高程序可靠性


package com.example.listview_0710;  
  
import java.util.ArrayList;  
  
import java.util.List;  
  
import com.example.listView_0710_data.MyOpenHelper;  
import com.example.listView_0710_data.Student;  
import com.example.listView_0710_data.ZSGC;  
  
import android.R.layout;  
import android.app.Activity;  
import android.content.Intent;  
import android.database.sqlite.SQLiteDatabase;  
import android.os.Bundle;  
import android.view.Menu;  
import android.view.MenuItem;  
import android.view.View;  
import android.widget.AdapterView;  
import android.widget.Button;  
import android.widget.EditText;  
import android.widget.ListView;  
  
public class MainActivity extends Activity {  
  
    private ListView lv_student;  
    private EditText et_name;  
    private EditText et_sex;  
    private EditText et_species;  
    private Button btn_add;  
      
    private MyOpenHelper myOpenHelper;  
    private EditText et_volume;  
      
    private List<Student> student_list;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
          
        student_list = new ArrayList<Student>();  
          
        //初始化学生的数据  
        //initstudent();   
        myOpenHelper = new MyOpenHelper(MainActivity.this);  
        SQLiteDatabase db = myOpenHelper.getWritableDatabase();  
        ZSGC tool = new ZSGC(MainActivity.this);  
        student_list = tool.queryStudent();  
          
        //将初始化数据绑定在listview上  
        StudentAdapter studentAdapter = new StudentAdapter(MainActivity.this, R.layout.student_item, student_list);  
          
        lv_student = (ListView) findViewById(R.id.lv_student);  
        lv_student.setAdapter(studentAdapter);  
          
        addAStudent();  //增加数据,student_list更新、db更新  
        studentAdapter.notifyDataSetChanged();  //刷新listview  
          
        lv_student.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
              
            @Override  
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {  
                Intent intent = new Intent(MainActivity.this, Student_show.class);  
                Bundle bundle = new Bundle();  
                bundle.putInt("position", position);  
                intent.putExtra("bun", bundle);  
                startActivity(intent);  
            }  
        });  
    }  
  
    private void addAStudent() {  
        et_name = (EditText) findViewById(R.id.et_name);  
        et_sex = (EditText) findViewById(R.id.et_sex);  
        et_species = (EditText) findViewById(R.id.et_species);  
        et_volume = (EditText) findViewById(R.id.et_volume);  
          
        btn_add = (Button) findViewById(R.id.btn_add);  
        btn_add.setOnClickListener(new View.OnClickListener() {  
              
            @Override  
            public void onClick(View arg0) {  
                String name = et_name.getText().toString();  
                String sex = et_sex.getText().toString();  
                String species = et_species.getText().toString();  
                String volume = et_volume.getText().toString();  
                //分割volume字符串得到数据  
                String[] volume_data = volume.split(" ");  
                  
                Student student = new Student(name, sex, species);  
                //判断,当前列表无重复姓名则添加进入  
                if(!student_list.contains(student))     student_list.add(student);  
                  
                //将数据存入db  
                SQLiteDatabase db = myOpenHelper.getWritableDatabase();  
                ZSGC tool = new ZSGC(MainActivity.this);  
                for(int i =0; i < volume_data.length; i++) {  
                    tool.insert(student, Long.valueOf(volume_data[i]));  
                }  
                  
                //把输入框清空  
                et_name.setText("");et_sex.setText("");et_species.setText("");et_volume.setText("");  
            }  
        });  
    }  
  
    /*private void initstudent() { 
        StudentData.student_list.add(new Student("name", "sexual", "species"));  //相当于表头 
         
    }*/  
  
}  

其余不变。
以上,完成。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Android Studio中从数据库中读取数据并将其显示ListView中,首先需要进行以下步骤: 1. 创建一个数据库帮助类:创建一个类继承自SQLiteOpenHelper类,并在其中定义数据库名称、表名、表结构和版本等相关信息。在该类中,需要重写onCreate()方法来创建数据库表,及onUpgrade()方法来更新数据库表。 2. 创建一个数据模型类:创建一个类,用于表示数据库中的每一行数据,定义相关属性和方法。 3. 创建一个数据库操作类:创建一个类,用于对数据库进行操作,包括插入数据、查询数据更新数据等。在该类中,需要获取数据库实例,并根据需要进行相关操作。 4. 在Activity中实现数据读取和ListView显示:在要显示数据的Activity中,首先实例化数据库操作类,并调用相应的方法从数据库中获取数据。然后,使用一个ArrayList来保存获取到的数据,并将其传递给一个自定义的适配器类。最后,在Activity的布局文件中添加一个ListView,然后设置适配器让ListView显示数据。 5. 创建适配器类:创建一个继承自BaseAdapter的适配器类,用于将数据绑定到ListView中。在适配器类中,需要重写getView()方法来设置每个列表项的视图,并根据数据填充相应的视图组件。 通过以上步骤,可以实现在Android Studio中从数据库中读取数据并将其显示ListView中。需要注意的是,每次有新的数据插入更新时,需更新ListView数据源,并通知适配器更新数据,以确保ListView显示最新的数据。 ### 回答2: Android Studio 是一个集成开发环境(IDE),用于开发 Android 应用程序。要从数据库读取数据,并将其显示ListView 中,可以按照以下步骤进行操作: 1. 创建一个数据库或使用现有的数据库:首先,在 Android Studio 中创建一个数据库,或者使用现有的数据库。可以使用 SQLite 数据库作为 Android 应用程序的嵌入式数据库。 2. 创建一个数据库帮助类:在 Android Studio 中创建一个继承自 SQLiteOpenHelper 类的数据库帮助类。在该类中,可以定义创建和升级数据库的方法。 ```java public class DatabaseHelper extends SQLiteOpenHelper { // 定义数据库名称和版本 private static final String DATABASE_NAME = "mydatabase.db"; private static final int DATABASE_VERSION = 1; // 在构造函数中传递数据库名称和版本 public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } // 在onCreate方法中创建表格 @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS mytable (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age INTEGER)"); } // 在onUpgrade方法中升级表格 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS mytable"); onCreate(db); } } ``` 3. 在 Activity 中使用数据库帮助类:在想要使用数据库的 Activity 中,创建一个 DatabaseHelper 对象,并使用它来获取可读写的数据库实例。 ```java DatabaseHelper dbHelper = new DatabaseHelper(this); SQLiteDatabase db = dbHelper.getWritableDatabase(); ``` 4. 查询数据库并将数据填充到 Cursor 中:使用 SQLiteDatabase 的 query 方法查询数据库,并将结果存储在 Cursor 对象中。 ```java Cursor cursor = db.query("mytable", null, null, null, null, null, null); ``` 5. 创建一个自定义的适配器:创建一个继承自 BaseAdapter 或 ArrayAdapter 的自定义适配器类,用于将数据绑定到 ListView 上。 ```java public class MyAdapter extends BaseAdapter { private Context context; private Cursor cursor; public MyAdapter(Context context, Cursor cursor) { this.context = context; this.cursor = cursor; } ... @Override public View getView(int position, View convertView, ViewGroup parent) { // 创建布局并绑定数据 if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false); } TextView nameTextView = convertView.findViewById(R.id.nameTextView); TextView ageTextView = convertView.findViewById(R.id.ageTextView); String name = cursor.getString(cursor.getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); nameTextView.setText(name); ageTextView.setText(String.valueOf(age)); return convertView; } ... } ``` 6. 将数据和适配器关联到 ListView 上:在 Activity 中,创建一个 ListView 对象,并使用自定义适配器将数据填充到 ListView 中。 ```java ListView listView = findViewById(R.id.listView); MyAdapter adapter = new MyAdapter(this, cursor); listView.setAdapter(adapter); ``` 通过以上步骤,我们可以成功从数据库读取数据,并将其填充到 ListView 中。 ### 回答3: Android Studio 是一款用于开发Android应用程序的集成开发环境(IDE)。要将数据库中的数据读取到ListView中,需要以下步骤: 1. 创建一个数据库助手类(DatabaseHelper),用于管理数据库的创建和版本控制。 2. 在数据库助手类中创建一个方法,用于查询需要的数据并返回Cursor对象。 3. 在Activity中,实例化数据库助手类并调用查询方法,将返回的Cursor对象保存到一个变量中。 4. 创建一个自定义的适配器(Adapter),继承自BaseAdapter类,用于将数据绑定到ListView上。 5. 在适配器的构造方法中,将保存查询结果的Cursor对象作为参数传入。 6. 在适配器的getView()方法中,使用Cursor对象获取数据,并将数据展示在ListView的每个Item上。 7. 在Activity中,实例化ListView和适配器,并调用setAdapter()方法将适配器与ListView绑定。 8. 最后,运行应用程序,即可看到从数据库读取的数据以列表形式展示在ListView中。 以上就是使用Android Studio从数据库读取数据并展示在ListView中的步骤。这样做可以方便地将数据库中的数据展示给用户,提供更好的用户体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值