1. 程式人生 > >Android-使用ListView把SQLite中的資料顯示至螢幕

Android-使用ListView把SQLite中的資料顯示至螢幕

結果圖:


步驟:

1.向資料庫中插入資料

2.從資料庫中取出資料放在ArrayList中;

3.將ArrayList中的資料顯示在ListView中;

佈局檔案:

activity_main.xml

<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"
    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.android04.MainActivity" >

    <ListView
        android:id="@+id/listView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </ListView>

</RelativeLayout>
listitem_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="名字"
        android:textSize="25sp" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:orientation="vertical" >
        <TextView 
	        android:id="@+id/tv_phone"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="號碼"
	    />
        <TextView 
            android:id="@+id/tv_salary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="工資"
            />
    </LinearLayout>

</RelativeLayout>

Java檔案:
Person.java
package com.example.cn;

public class Person {

	private String _id;
	private String name;
	private String phone;
	private String salary;
	
	public String get_id() {
		return _id;
	}
	public void set_id(String _id) {
		this._id = _id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getSalary() {
		return salary;
	}
	public void setSalary(String salary) {
		this.salary = salary;
	}
	@Override
	public String toString() {
		return name + ", " + phone + ", " + salary;
	}
	public Person(String _id, String name, String phone, String salary) {
		super();
		this._id = _id;
		this.name = name;
		this.phone = phone;
		this.salary = salary;
	}
	
	
}
MyOpenHelper.java
package com.example.android04;

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, "person.db", null, 1);
		// TODO Auto-generated constructor stub
		System.out.println("MyOpenHelper");
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		//建立表
		db.execSQL("create table person(_id integer primary key autoincrement, name char(10), salary char(20), phone integer(20) )");

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}

}

MainActivity.java
package com.example.android04;

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

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.example.cn.Person;

public class MainActivity extends Activity {

	List<Person> personList;
	MyOpenHelper mOpenHelper;
	SQLiteDatabase db;
	MyAdapter myAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ListView lv = (ListView) findViewById(R.id.listView);
		personList = new ArrayList<Person>();
		// 建立MyOpenHelper例項
		mOpenHelper = new MyOpenHelper(this);
		// 得到資料庫
		db = mOpenHelper.getWritableDatabase();
		// 插入資料
		Insert();
		// 查詢資料
		Query();
		// 建立MyAdapter例項
		myAdapter = new MyAdapter(this);
		// 向listview中新增Adapter
		lv.setAdapter(myAdapter);
	}

	// 建立MyAdapter繼承BaseAdapter
	class MyAdapter extends BaseAdapter {
		private Context context;
		private LayoutInflater inflater;

		public MyAdapter(Context context) {
			this.context = context;
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return personList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// 從personList取出Person
			Person p = personList.get(position);
			ViewHolder viewHolder = null;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = inflater.inflate(R.layout.listitem_layout, null);
				viewHolder.txt_name = (TextView) convertView
						.findViewById(R.id.tv_name);
				viewHolder.txt_phone = (TextView) convertView
						.findViewById(R.id.tv_phone);
				viewHolder.txt_salary = (TextView) convertView
						.findViewById(R.id.tv_salary);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			//向TextView中插入資料
			viewHolder.txt_name.setText(p.getName());
			viewHolder.txt_phone.setText(p.getPhone());
			viewHolder.txt_salary.setText(p.getSalary());

			return convertView;
		}
	}

	class ViewHolder {
		private TextView txt_name;
		private TextView txt_phone;
		private TextView txt_salary;
	}

	// 插入資料
	public void Insert() {
		for (int i = 0; i < 100; i++) {
			ContentValues values = new ContentValues();
			values.put("name", "張三" + i);
			values.put("salary", "123" + i + i);
			values.put("phone", "151" + i + i);
			db.insert("person", null, values);
		}
	}

	// 查詢資料
	public void Query() {
		Cursor cursor = db.query("person", null, null, null, null, null, null);
		while (cursor.moveToNext()) {
			String _id = cursor.getString(0);
			String name = cursor.getString(1);
			String salary = cursor.getString(2);
			String phone = cursor.getString(3);
			Person person = new Person(_id, name, phone, salary);
			personList.add(person);
		}
	}

}