android ListView使用

1.DbOpenHelper

复制代码
package dbOpenHelper;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Administrator on 2014/8/25.
 */
public class DbOpenHelper extends SQLiteOpenHelper {

    public DbOpenHelper(Context context)
    {
        //Context 上下文
        //name 数据库名
        //CursorFactory 游标工厂模式 当为null时 使用默认值
        //version 数据库版本 版本号从1开始
        super(context, "person.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //create table person(id integer primary key autoincrement,name varchar(20),age int,phone varchar(11))
        String sql = "create table person(id integer primary key autoincrement,name varchar(20),int age,phone varchar(11))";
        db.execSQL(sql);
    }

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

    }
}
复制代码

2.entity

复制代码
package domain;

/**
 * Created by Administrator on 2014/8/25.
 */
public class Person {
    private int id;
    private String name;
    private int age;
    private String phone;

    public Person(){}

    public Person(int id, String name, int age, String phone) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.phone = phone;
    }

    public Person(int id, String name, String phone) {
        this.id = id;
        this.name = name;
        this.phone = phone;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getPhone() {
        return phone;
    }

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

    @Override
    public String toString() {
        return "个人信息{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", phone='" + phone + '\'' +
                '}';
    }
}
复制代码

3.DAO

复制代码
package dao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import dbOpenHelper.DbOpenHelper;
import domain.Person;

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

/**
 * Created by Administrator on 2014/8/25.
 */
public class PersonDao {
    private DbOpenHelper helper;

    public PersonDao(Context context)
    {
        helper = new DbOpenHelper(context);
    }

    public void add(Person p)
    {
        SQLiteDatabase db = helper.getWritableDatabase();
        String sql = "insert into person(name,phone) values(?,?)";
        db.execSQL(sql,new Object[]{p.getName(),p.getPhone()});
        db.close();
    }

    public void update(Person p)
    {
        SQLiteDatabase db = helper.getWritableDatabase();
        String sql = "update person set phone=? where name=?";
        db.execSQL(sql,new Object[]{p.getPhone(),p.getName()});
        db.close();
    }

    public void delete(String name)
    {
        SQLiteDatabase db = helper.getWritableDatabase();
        String sql = "delete from person where name=?";
        db.execSQL(sql,new Object[]{name});
        db.close();
    }

    public Person findByName(String name)
    {
        SQLiteDatabase db = helper.getWritableDatabase();
        String sql = "select * from person where name=?";
        Cursor cursor = db.rawQuery(sql,new String[]{name});
        Person p = null;
        while(cursor.moveToFirst())
        {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String phone = cursor.getString(cursor.getColumnIndex("phone"));
            p = new Person(id,name,phone);
        }
        db.close();
        return p;
    }

    public List<Person> findAll()
    {
        SQLiteDatabase db = helper.getWritableDatabase();
        String sql = "select * from person";
        Cursor cursor = db.rawQuery(sql,null);
        List<Person> list = new ArrayList<Person>();
        while(cursor.moveToNext())
        {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String phone = cursor.getString(cursor.getColumnIndex("phone"));
            Person p = new Person(id,name,phone);
            list.add(p);
        }
        db.close();
        return list;
    }

}
复制代码

4.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="fill_parent"
              android:layout_height="fill_parent">

    <TextView
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:text="@string/id"
            android:id="@+id/tv_id"
            />
    <TextView
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:text="@string/name"
            android:id="@+id/tv_name"
            />
    <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/phone"
            android:id="@+id/tv_phone"
            />

</LinearLayout>
复制代码

5.main.xml

复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">
    <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
        <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:text="@string/id"
                />
        <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:text="@string/name"
                />
        <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="@string/phone"
                />
    </LinearLayout>

   <ListView
           android:layout_width="fill_parent"
           android:layout_height="fill_parent"
           android:id="@+id/list"
           />

</LinearLayout>
复制代码

6.mainActivity.java

复制代码
package com.example.dbTest;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import dao.PersonDao;
import domain.Person;
import service.PersonAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2014/8/25.
 */
public class PersonListActivity extends Activity {

    private PersonDao dao;
    private ListView lv;
    private List<Person> persons;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview);

        lv = (ListView)this.findViewById(R.id.list);
        dao = new PersonDao(this);
        persons = dao.findAll();
        //show();
        //对单个对象绑定点击事件
        lv.setOnItemClickListener(new MyItemClickListener());
        show2();

    }

    public class MyItemClickListener implements AdapterView.OnItemClickListener
    {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ListView lView = (ListView)parent;
            Person p = (Person)lView.getItemAtPosition(position);
            Toast.makeText(getApplicationContext(),p.getName(),0).show();
        }
    }

    private void show2() {
        PersonAdapter adapter = new PersonAdapter(this,persons,R.layout.item);
        lv.setAdapter(adapter);
    }

    private void show() {
        List<Person> persons = dao.findAll();
        List<HashMap<String,Object>>data = new ArrayList<HashMap<String,Object>>();
        for (Person p:persons)
        {
            HashMap<String,Object> item = new HashMap<String,Object>();
            item.put("id",p.getId());
            item.put("name",p.getName());
            item.put("phone",p.getPhone());
            data.add(item);
        }
        SimpleAdapter sa = new SimpleAdapter(this,data,R.layout.item,new String[]{"id","name","phone"},new int[]{R.id.tv_id,R.id.tv_name,R.id.tv_phone});
        lv.setAdapter(sa);
    }
}
复制代码

 

 6.继承BaseAdapter适配器

复制代码
package service;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.dbTest.R;
import domain.Person;

import java.util.List;

/**
 * Created by Administrator on 2014/8/26.
 */
public class PersonAdapter extends BaseAdapter {
    private List<Person> persons;
    private int resource;
    private LayoutInflater inflater;

    public PersonAdapter(Context context,List<Person> persons, int resource) {
        this.persons = persons;
        this.resource = resource;
        inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return persons.size();
    }

    @Override
    public Object getItem(int position) {
        return persons.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView==null)
        {
            convertView = inflater.inflate(resource,null);
        }
        TextView idView = (TextView)convertView.findViewById(R.id.tv_id);
        TextView nameView = (TextView)convertView.findViewById(R.id.tv_name);
        TextView phoneView = (TextView)convertView.findViewById(R.id.tv_phone);
        
        Person p = persons.get(position);
        
        idView.setText(p.getId()+"");
        nameView.setText(p.getName());
        phoneView.setText(p.getPhone());
        
        return convertView;
    }
}
复制代码

 

posted @   大空白纸  阅读(201)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示