IDE:Android Studio 3.5 RC 2
开发语言:Java
SDK版本:Android 9.0 API 28
builde.gradle
apply plugin: 'com.android.application' android { compileSdkVersion 29 buildToolsVersion "29.0.1" defaultConfig { applicationId "com.aaa.aListView" minSdkVersion 24 targetSdkVersion 29 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.0.2' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' }
1. ListView实现数据的列表显示
com.aaa.domain/Dog.java
package com.aaa.domain; /** * 作者:kevin on 2019/8/8 20:19 */ public class Dog { private Integer dogId; // 狗的编号 private String dogName; // 狗的名称 private String dogSkin; // 狗的皮肤 private Float dogPrice; // 狗的价格 public Dog() { } public Dog(String dogName, String dogSkin, Float dogPrice) { this.dogName = dogName; this.dogSkin = dogSkin; this.dogPrice = dogPrice; } public Dog(Integer dogId, String dogName, String dogSkin, Float dogPrice) { this.dogId = dogId; this.dogName = dogName; this.dogSkin = dogSkin; this.dogPrice = dogPrice; } public Integer getDogId() { return dogId; } public void setDogId(Integer dogId) { this.dogId = dogId; } public String getDogName() { return dogName; } public void setDogName(String dogName) { this.dogName = dogName; } public String getDogSkin() { return dogSkin; } public void setDogSkin(String dogSkin) { this.dogSkin = dogSkin; } public Float getDogPrice() { return dogPrice; } public void setDogPrice(Float dogPrice) { this.dogPrice = dogPrice; } @Override public String toString() { return "Dog{" + "dogId=" + dogId + ", dogName='" + dogName + '\'' + ", dogSkin='" + dogSkin + '\'' + ", dogPrice=" + dogPrice + '}'; } }
com.aaa.service/OpenDatabaseService.java
package com.aaa.service; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * 作者:kevin on 2019/8/8 17:28 */ public class OpenDatabaseService extends SQLiteOpenHelper { public OpenDatabaseService(Context context) { // 参数说明:上下文对象 数据库文件 使用默认游标 数据库版本 super(context,"kevin.db",null,1); } // 2019年8月8日17:30:17 这个方法在数据库文件第一次创建的时候被调用 @Override public void onCreate(SQLiteDatabase db) { // SQLite数据库中,除了表的主键。其他字段的值是不分类型的,VARCHAR(20)这些东西可以省略 String sql = "CREATE TABLE dog(dogId integer PRIMARY KEY AUTOINCREMENT,dogName varchar(20),dogSkin varchar(20),dogPrice float(20))"; // 创建表的语句 db.execSQL(sql); } @Override // 2019年8月8日17:38:32 这个方法在数据库版本号发生改变的时候被调用 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
com.aaa.service/DogService.java
package com.aaa.service; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.aaa.domain.Dog; import java.util.ArrayList; import java.util.List; /** * 作者:kevin on 2019/8/8 20:53 */ public class DogService { private SQLiteDatabase dbOption; public DogService(SQLiteDatabase dbOption) { this.dbOption = dbOption; } // 2019年8月8日20:53:53 插入数据 public void insert(Dog dog){ String sql = "INSERT INTO dog(dogName,dogSkin,dogPrice) values(?,?,?)"; dbOption.execSQL(sql,new Object[]{dog.getDogName(),dog.getDogSkin(),dog.getDogPrice()}); // dbOption.close(); // 可以关也可以不关 } // 2019年8月8日21:18:58 删除数据 public void delete(int id){ String sql = "DELETE FROM dog Where dogId = ?"; dbOption.execSQL(sql,new Object[]{id}); } // 2019年8月8日21:20:39 改数据 public void update(Dog dog){ String sql = "UPDATE dog SET dogName = ?,dogSkin = ?,dogPrice = ? WHERE dogId = ?"; dbOption.execSQL(sql,new Object[]{dog.getDogName(),dog.getDogSkin(),dog.getDogPrice(),dog.getDogId()}); } // 2019年8月8日21:23:26 查询数据 public Dog query(int id){ String sql = "SELECT * FROM dog WHERE dogId = ?"; Cursor cursor = dbOption.rawQuery(sql, new String[]{String.valueOf(id)}); if(cursor.moveToFirst()){ int dogId = cursor.getInt(cursor.getColumnIndex("dogId")); String dogName = cursor.getString(cursor.getColumnIndex("dogName")); String dogSkin = cursor.getString(cursor.getColumnIndex("dogSkin")); float dogPrice = cursor.getFloat(cursor.getColumnIndex("dogPrice")); return new Dog(dogId,dogName,dogSkin,dogPrice); } cursor.close(); return null; } // 2019年8月8日21:25:16 获取数据库记录的总条目数 public long getCount(){ String sql = "SELECT COUNT(*) FROM dog"; Cursor cursor = dbOption.rawQuery(sql,null); cursor.moveToFirst(); long result = cursor.getLong(0); return result; } // 2019年8月8日21:39:01 分页查询 public List<Dog> getPaginationData(int start,int pageSize){ List<Dog> dogs = new ArrayList<>(); String sql = "SELECT * FROM dog ORDER BY dogId ASC LIMIT ?,?"; Cursor cursor = dbOption.rawQuery(sql,new String[]{String.valueOf(start),String.valueOf(pageSize)}); while (cursor.moveToNext()){ int dogId = cursor.getInt(cursor.getColumnIndex("dogId")); String dogName = cursor.getString(cursor.getColumnIndex("dogName")); String dogSkin = cursor.getString(cursor.getColumnIndex("dogSkin")); float dogPrice = cursor.getFloat(cursor.getColumnIndex("dogPrice")); dogs.add(new Dog(dogId,dogName,dogSkin,dogPrice)); } return dogs; } // 2019年8月9日08:52:15 获取分页数据的第二种方式 public Cursor getCursorPagination(int start,int pageSize){ List<Dog> dogs = new ArrayList<>(); String sql = "SELECT dogId as _id,dogName,dogSkin,dogPrice FROM dog ORDER BY dogId ASC LIMIT ?,?"; Cursor cursor = dbOption.rawQuery(sql,new String[]{String.valueOf(start),String.valueOf(pageSize)}); return cursor; } }
com.aaa.aListView/Main.java
package com.aaa.aListView; import androidx.appcompat.app.AppCompatActivity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.SimpleCursorAdapter; import com.aaa.domain.Dog; import com.aaa.service.DogService; import com.aaa.service.OpenDatabaseService; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class Main extends AppCompatActivity { private ListView listView; private SQLiteDatabase dbOption; private DogService dogService; private Dog dog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); listView = this.findViewById(R.id.list_item); dbOption = new OpenDatabaseService(Main.this).getWritableDatabase(); // 得到数据库操作对象 dogService = new DogService(dbOption); // 得到dogService对象 dog = new Dog(); // insertData(); // 插入假数据40条 // showData1(); // 通过SimpleAdapter适配器绑定数据 // showData2(); showData3(); // 自定义适配器 } // 2019年8月9日08:39:38 插入假数据,方便后面查询 public void insertData(){ for(int i=0; i<40; i++){ dog.setDogId(i); dog.setDogName("阿拉斯加犬"+i+"号"); dog.setDogSkin("绿色"+i+"号"); dog.setDogPrice((float)i+100); dogService.insert(dog); } } // 2019年8月9日08:48:48 使用SimpleAdapter绑定数据 public void showData1(){ List<Dog> dogs = dogService.getPaginationData(5, 20); List<HashMap<String,Object>> data = new ArrayList<HashMap<String, Object>>(); for(Dog dog:dogs){ HashMap<String,Object> map = new HashMap<String,Object>(); map.put("dogId",dog.getDogId()); map.put("dogName",dog.getDogName()); map.put("dogSkin",dog.getDogSkin()); map.put("dogPrice",dog.getDogPrice()); data.add(map); } // 通过适配器把dogs集合中的数据显示到ListView中的条目 String[] keys = {"dogId","dogName","dogSkin","dogPrice"}; // data集合中的dogId可以对应的值绑定到R.id.dogId这个控件 int[] views ={R.id.dogId,R.id.dogName,R.id.dogSkin,R.id.dogPrice}; SimpleAdapter simpleAdapter = new SimpleAdapter(Main.this,data,R.layout.dogs,keys,views); listView.setAdapter(simpleAdapter); } // 2019年8月9日09:16:54 通过cursor对象绑定数据 public void showData2(){ Cursor cursor = dogService.getCursorPagination(5, 20); String[] keys = {"_id","dogName","dogSkin","dogPrice"}; // data集合中的dogId可以对应的值绑定到R.id.dogId这个控件 int[] views ={R.id.dogId,R.id.dogName,R.id.dogSkin,R.id.dogPrice}; SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(Main.this,R.layout.dogs,cursor,keys,views,0); listView.setAdapter(simpleCursorAdapter); } }
自定义适配器实现数据的绑定
com.aaa.adapter/MyAdapter.java
package com.aaa.adapter; 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.aaa.aListView.R; import com.aaa.domain.Dog; import java.util.List; /** * 作者:kevin on 2019/8/9 09:30 */ public class MyAdapter extends BaseAdapter { private List<Dog> dogs ; // 定义需要绑定的数据 private int resource; // 数据绑定的条目界面 private LayoutInflater inflater;// 布局填充器,可以用一个xml文件生成一个View对象 public MyAdapter(Context context, List<Dog> dogs, int resource) { this.dogs = dogs; this.resource = resource; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override // 用于得到记录的总数 public int getCount() { return dogs.size(); // 数据的总数 } @Override // 某个索引对应的元素 public Object getItem(int position) { return dogs.get(position); } @Override public long getItemId(int position) { return position; } @Override // position 该条目索要绑定的数据在集合中的索引值 public View getView(int position, View view, ViewGroup parent) { if(view == null){ view = inflater.inflate(resource,null); } TextView dogId = view.findViewById(R.id.dogId); TextView dogName = view.findViewById(R.id.dogName); TextView dogSkin = view.findViewById(R.id.dogSkin); TextView dogPrice = view.findViewById(R.id.dogPrice); Dog dog = dogs.get(position); dogId.setText(dog.getDogId()); dogName.setText(dog.getDogName()); dogSkin.setText(dog.getDogSkin()); dogPrice.setText(dog.getDogPrice().toString()); return view; } }
Main.java添加方法
// 2019年8月9日09:29:29 通过自定义适配器绑定数据 public void showData3(){ List<Dog> dogs = dogService.getPaginationData(5, 20); MyAdapter myAdapter = new MyAdapter(Main.this,dogs,R.layout.dogs); listView.setAdapter(myAdapter); }