`
huiqinbo
  • 浏览: 333981 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

无废话Android 系列教程36-1 [模仿listview的工作原理&测试]

阅读更多

 声明: LinearLayout(线性布局) ,同时是一个View对象的容器;既然是一个容器就应该有addView的方法

 

1.  com.andy.listview包下  MainActivity.java

package com.andy.listview;

import java.util.List;

import com.andy.listview.R;
import com.andy.listview.dao.PersonDao2;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andy.listview.domain.Person;

/**
 * 这是一个模仿listview 的类
 * @author huiqinbo
 *
 */
public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		LinearLayout ll_root = (LinearLayout)findViewById(R.id.ll_root);
		PersonDao2 dao = new PersonDao2(this);
		List<Person> persons = dao.findAllPerson();
		for(Person person : persons){
			String p = person.toString();
			TextView tv = new TextView(this);
			tv.setText(p);
			tv.setTextColor(Color.BLUE);
			tv.setTextSize(25);
			ll_root.addView(tv);
		}
		
	}

	
}

 

2. com.andy.listview包下  PersonSQLiteOpenHelper.java

package com.andy.listview;

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

/**
 * 创建PersonSQLiteOpenHelper类 继承SQLiteOpenHelper抽象类,此时必须创建构造方法
 * @author huiqinbo
 *
 */
public class PersonSQLiteOpenHelper extends SQLiteOpenHelper {

	//通过getSimpleName()方法获取到值为"PersonSQLiteOpenHelper"
	private static final String tag = PersonSQLiteOpenHelper.class.getSimpleName();

	/**
	 * 数据库的构造方法, 用来定义数据库的名称/数据库的查询结果集/数据库的版本号
	 * 
	 * 当版本号发生变化时才可以调用onUpgrade方法; 如版本号从1 →2
	 * @param context
	 * @param name
	 * @param factory
	 * @param version
	 */
	public PersonSQLiteOpenHelper(Context context) {
//		super(context, "person.db", null, 1);
		super(context, "person.db", null, 3);
		// TODO Auto-generated constructor stub
	}
	
	

	/**
	 * 数据库第一次被创建的时候调用的方法
	 * @param db 被创建的数据库
	 */
	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("create table person (id integer primary key autoincrement, name varchar(20), number varchar(20))");
	}

	
	/**
	 * sqlite中ALTER TABLE语句不支持DROP COLUMN,只有RENAME 和ADD 语句.
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		Log.i(tag, "数据库的版本发生变化了");
		db.execSQL("alter table person add account varchar(20)");

	}

}

 

3. com.andy.listview.dao PersonDao2.java

package com.andy.listview.dao;

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

import com.andy.listview.PersonSQLiteOpenHelper;
import com.andy.listview.domain.Person;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class PersonDao2 {
	private PersonSQLiteOpenHelper helper;
	public PersonDao2(Context context){
		helper = new PersonSQLiteOpenHelper(context);
	}
	
	/*
	 * 插入用户名和手机号到SQLite数据库
	 * 
	 * the row ID of the newly inserted row, or -1 if an error occurred
	 */
	public long addPerson(String name, String number,int account){
		
		//此时就获取到了数据库
		SQLiteDatabase db = helper.getWritableDatabase();
		//db.execSQL("insert into person (name,number) values (?,?)", new Object[]{name,number});
		ContentValues values = new ContentValues();
		values.put("name", name);
		values.put("number", number);
		values.put("account", account);
		long row_id = db.insert("person", null, values);
		db.close();
		return row_id;
	}
	
	/**
	 * 删除一条数据,按用户名的条件
	 * @param name
	 * 
	 * WhereClause :the optional WHERE clause to apply when deleting. Passing null will delete all rows.
	 */
	public int deletePerson(String name){
		SQLiteDatabase db = helper.getWritableDatabase();
//		db.execSQL("delete from person where name =?", new Object[]{name});
		int row_id = db.delete("person", "name=?", new String[]{name});
		db.close();
		
		return row_id;
	}
	
	
	/**
	 * 修改一条数据,按用户名的条件
	 * @param name
	 * @param number
	 */
	public int updatePerson(String name, String number){
		SQLiteDatabase db = helper.getWritableDatabase();
//		db.execSQL("update person set number = ? where name = ?", new Object[]{name,number} );
		ContentValues values = new  ContentValues();
		values.put("number", number);
		
		int row_id = db.update("person", values, "name=?", new String[]{name});
		db.close();
		
		return row_id;
	}
	
	/**
	 * 查询一条数据,按用户名的条件
	 * @param name
	 * @param number
	 * selection : A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
	 * selectionArgs:  You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
	 */
	public boolean findPerson(String name){
		SQLiteDatabase db = helper.getWritableDatabase();
//		Cursor cursor = db.rawQuery("select * from person where name=?", new String[]{name});
		Cursor cursor = db.query("person", new String[]{"id", "name", "number"}, "name=?", new String[]{name}, null, null, null);
		boolean result = cursor.moveToNext();
		cursor.close();
		db.close();
		return result;
	}
	
	
	public List<Person> findAllPerson(){
		SQLiteDatabase db = helper.getWritableDatabase();
//		Cursor cursor = db.rawQuery("select * from person", null);
		Cursor cursor = db.query("person", new String[]{"id","name","number"}, null, null, null, null, null);
		List<Person> persons = new ArrayList<Person>(); 
		Person person;
		while(cursor.moveToNext()){
			int id = cursor.getInt(cursor.getColumnIndex("id"));
			String name = cursor.getString(cursor.getColumnIndex("name"));
			String number = cursor.getString(cursor.getColumnIndex("number"));
			person = new Person(id,name,number);
			persons.add(person);
		}
		cursor.close();
		db.close();
		return persons;
	}

}

 

4. com.andy.listview.domain 包下的Person.java 类

package com.andy.listview.domain;

public class Person {
	private int id;
	private String name;
	private String number;
	
	public Person(int id, String name, String number){
		this.id = id;
		this.name= name;
		this.number = number;
	}
	
	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", number=" + number
				+ "]";
	}
	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 String getNumber() {
		return number;
	}
	public void setNumber(String number) {
		this.number = number;
	}
	
	

}

 

5.  com.andy.listview.test 包下的TestPersonListView.java

package com.andy.listview.test;

import java.util.List;
import java.util.Random;

import com.andy.listview.PersonSQLiteOpenHelper;
import com.andy.listview.dao.PersonDao2;
import com.andy.listview.domain.Person;

import android.database.sqlite.SQLiteDatabase;
import android.test.AndroidTestCase;
import android.util.Log;

/**
 * 
 * @author huiqinbo
 *
 */
public class TestPersonListView extends AndroidTestCase {

	private static final String tag = TestPersonListView.class.getSimpleName();
	public PersonDao2 pd;

	/**
	 * getContext() 是测试框架给提供的上下文件 来源:android.test.AndroidTestCase.getContext()
	 * 
	 * 第一次执行时调用PersonSQLiteOpenHelper.java 内的onCreate方法,
	 * 当版本号发生变化时,会调用PersonSQLiteOpenHelper.java 内的onUpgrade方法.
	 */
	public void testCreatePersonDb() {
		PersonSQLiteOpenHelper db = new PersonSQLiteOpenHelper(getContext());
		// 打开或创建一个可写的数据库
		db.getWritableDatabase();
	}

	public void testAddPerson() {
		pd = new PersonDao2(getContext());
		
		Random random = new Random();
		for(int i=0; i<50; i++){
			pd.addPerson("ZhangSan"+i, "138001380"+i, random.nextInt(10000));
		}
	}
	
	
	//注:查询数据表的结构SQL语句:
	//select * from sqlite_master where type="table" and name="person";
}

 

6. res → layout 下的 activity_main.xml

<!--  其实这里是能满足展示的, 但不能滚动
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/ll_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.andy.listview.MainActivity"
    android:orientation="vertical"
    tools:ignore="MergeRootFrame" >
</LinearLayout>-->



<!-- 为了能在页面中进行多条数据时滚动, 所以加入了ScrollView . 对于任何一个View 都是要指定宽和高的!-->
<ScrollView 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">
    
	<LinearLayout 
	    android:id="@+id/ll_root"
	    android:layout_width="match_parent"
	    android:layout_height="match_parent"
	    tools:context="com.andy.listview.MainActivity"
	    android:orientation="vertical"
	    tools:ignore="MergeRootFrame" >
	</LinearLayout>
</ScrollView>

 

7. 效果如下:



 

 

8.  源码参照附件

 

 

 

注:如果只想查看具体一张表的表结构,比如查看person表的结构(也就是都有哪些字段, 字段的类型是什么),命令为:

select * from sqlite_master where type="table" and name="person";



 

 

 

 

 

 

 

 

  • 大小: 218.4 KB
  • 大小: 260.9 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics