android之显示数据库信息

关键字


  • ListView
  • adapter
  • MVC

在android开发中也使用到了MVC架构,其中的xml布局文件就是V,M就是我们定义好的javabean类,而控制器就是就是适配器类adapter

布局文件


采用线性布局的方式,ListView就是一个View容器,可以往里面放任何的View对象

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     tools:context="xidian.dy.com.chujia.MainActivity">
 7 
 8        <ListView
 9            android:id="@+id/lv"
10            android:layout_width="match_parent"
11            android:layout_height="match_parent">
12 
13        </ListView>
14 </LinearLayout>

javabean


 

package xidian.dy.com.chujia;

/**
 * Created by dy on 2016/6/17.
 */
public class Person {
    private String name;
    private int salary;
    private String phone;

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name +' ' + salary + ' ' + phone;
    }
}

 

Activity


  先将数据从数据库中读出来封装成一个javabean对象,然后在将所以的对象放到List容器中。使用系统提供的adapter对象来遍历list容器,将取得内容封装成一个View对象,返回给ListView。ListView每拿到一个View对象就将其显示出来。这里的为了使用方便将pater作为内部类来使用。

package xidian.dy.com.chujia;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private SQLiteDatabase db;
    private List<Person> personList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        MainActivity mContext = MainActivity.this;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyDBOpenHelper myDBHelper = new MyDBOpenHelper(mContext, "my.db", null, 1);
        db = myDBHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        for(int i=0; i<50; i++){
            values.put("name", "data"+i);
            values.put("salary", 1000+i);
            values.put("phone","12345678901");
            db.insert("person", null, values);
            values.clear();
        }

        personList = new ArrayList<>();
        Cursor cursor = db.query("person",new String[]{"name", "salary", "phone"},null,null,null,null,null,null);
        while (cursor.moveToNext()){
            Person person = new Person();
            person.setName(cursor.getString(0));
            person.setSalary(cursor.getInt(1));
            person.setPhone(cursor.getString(2));
            personList.add(person);
        }
        cursor.close();
        ListView lv = (ListView) findViewById(R.id.lv);
        if(lv != null)
            lv.setAdapter(new MyAdapter());
    }

    class MyAdapter extends BaseAdapter{

        //提供给系统调用,指定集合中有多少个元素
        @Override
        public int getCount() {
            return personList.size();
        }
        //提供给系统调用,获取一个View来显示
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
        //这个TextView将来要在MainActivity中显示,所以应将MainActivity.this作为TextView的上下文 TextView text
= new TextView(MainActivity.this); text.setText(personList.get(position).toString()); text.setTextSize(18); return text; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } } }

效果


布局优化


对上面的显示效果可以作出如下的优化

  • 新增布局文件item_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="xidian.dy.com.chujia.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="15sp"
             />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="15sp"
            />
    </LinearLayout>
</RelativeLayout>
  • 修改Activity

package xidian.dy.com.chujia;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private SQLiteDatabase db;
    private List<Person> personList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        MainActivity mContext = MainActivity.this;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyDBOpenHelper myDBHelper = new MyDBOpenHelper(mContext, "my.db", null, 1);
        db = myDBHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        for(int i=0; i<50; i++){
            values.put("name", "data"+i);
            values.put("salary", 1000+i);
            values.put("phone","12345678901");
            db.insert("person", null, values);
            values.clear();
        }

        personList = new ArrayList<>();
        Cursor cursor = db.query("person",new String[]{"name", "salary", "phone"},null,null,null,null,null,null);
        while (cursor.moveToNext()){
            Person person = new Person();
            person.setName(cursor.getString(0));
            person.setSalary(cursor.getInt(1));
            person.setPhone(cursor.getString(2));
            personList.add(person);
        }
        cursor.close();
        ListView lv = (ListView) findViewById(R.id.lv);
        if(lv != null)
            lv.setAdapter(new MyAdapter());
    }

    class MyAdapter extends BaseAdapter{

        //提供给系统调用,指定集合中有多少个元素
        @Override
        public int getCount() {
            return personList.size();
        }
        //提供给系统调用,获取一个View来显示
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            //将一个布局文件转为一个View对象
            View v =  View.inflate(MainActivity.this, R.layout.item_list,null);
            //设置该对象中的值
            TextView txt1 = (TextView) v.findViewById(R.id.name);
            TextView txt2 = (TextView) v.findViewById(R.id.salary);
            TextView txt3 = (TextView) v.findViewById(R.id.phone);
            Person p = personList.get(position);
            if (txt1 != null)
                txt1.setText(p.getName());
            if (txt2 != null)
                //因为p.getSalary()是int类型,所以应转为字符串类型
                txt2.setText(String.valueOf(p.getSalary()));
            if (txt3 != null )
                txt3.setText(p.getPhone());
            //将一个布局嵌套到另一个中
            return v;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }
    }
}

效果


优化


  当我们在滑动屏幕的时候,每出现一个新的条目,适配器中getView方法就会被调用一次。在每次调用的时候都会创建一个View对象,这样非常消耗内存。但是getView中有一个参数convertView,这个一个缓存对象。当一个条目被移除屏幕的时候,该条目对应的View对象就会被缓存起来。当getView方法被调用的时候,我们可以获取缓存对象,从而避免去创建新的对象了。

package xidian.dy.com.chujia;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private SQLiteDatabase db;
    private List<Person> personList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        MainActivity mContext = MainActivity.this;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyDBOpenHelper myDBHelper = new MyDBOpenHelper(mContext, "my.db", null, 1);
        db = myDBHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        for(int i=0; i<50; i++){
            values.put("name", "data"+i);
            values.put("salary", 1000+i);
            values.put("phone","12345678901");
            db.insert("person", null, values);
            values.clear();
        }

        personList = new ArrayList<>();
        Cursor cursor = db.query("person",new String[]{"name", "salary", "phone"},null,null,null,null,null,null);
        while (cursor.moveToNext()){
            Person person = new Person();
            person.setName(cursor.getString(0));
            person.setSalary(cursor.getInt(1));
            person.setPhone(cursor.getString(2));
            personList.add(person);
        }
        cursor.close();
        ListView lv = (ListView) findViewById(R.id.lv);
        if(lv != null)
            lv.setAdapter(new MyAdapter());
    }

    class MyAdapter extends BaseAdapter{

        //提供给系统调用,指定集合中有多少个元素
        @Override
        public int getCount() {
            return personList.size();
        }
        //提供给系统调用,获取一个View来显示
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v;
            if(convertView == null)
            //将一个布局文件转为一个View对象
                v = View.inflate(MainActivity.this, R.layout.item_list, null);
            else
                //使用缓存中的View对象,避免重新创建
                v=convertView;
            //设置该对象中的值
            TextView txt1 = (TextView) v.findViewById(R.id.name);
            TextView txt2 = (TextView) v.findViewById(R.id.salary);
            TextView txt3 = (TextView) v.findViewById(R.id.phone);
            Person p = personList.get(position);
            if (txt1 != null)
                txt1.setText(p.getName());
            if (txt2 != null)
                //因为p.getSalary()是int类型,所以应转为字符串类型
                txt2.setText(String.valueOf(p.getSalary()));
            if (txt3 != null )
                txt3.setText(p.getPhone());
            //将一个布局嵌套到另一个中
            return v;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }
    }
}

 

posted @ 2016-06-19 10:19  被罚站的树  阅读(1550)  评论(0编辑  收藏  举报