Android中结合OrmLite for android组件对SQLite的CRUD(增删改查)操作实例

下载链接:http://ormlite.com/releases/

本博客文章中曾经提到过Ormlite的第三方组件包,Ormlite 是一种ORM工具,并且是一种轻量级别的工具。我们可以使用它来对Android中内嵌的sqlite数据库进行相关的操作。Android 的应用程序应使用 Ormlite for android 版本来进行相关的开发。Ormlite是对android提供的sqlite部分的API进行了封装。提供了更加方便的接口来供使用。

      本文以一个学生的信息实例程序来展示如何使用ormlite for android的第三方组件来开发Sqlite的C[增加],R[查询],U[更新],D[查询]应用程序,以便更方便的对sqlite数据库的操作。我们先看下程序的结构图:

【1】.程序结构图如下:

其中包com.andyidea.bean下Student.java为实体类,包com.andyidea.db下DatabaseHelper.java为数据库辅助类,包com.andyidea.ormsqlite下的MainActivity.java和StudentListActivity.java是界面信息类。同时我们别忘了在根目录下创建一个lib的文件夹,把第三方组件包ormlite-android-4.31.jar ,ormlite-core-4.31.jar,ormlite-jdbc-4.31.jar放到lib文件夹下,然后在项目中引用这三个包就OK了。

【2】布局文件源码如下:

main.xml源码:

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     android:padding="5dip">  
  7.     <TextView    
  8.     android:layout_width="fill_parent"  android:layout_height="wrap_content"  
  9.     android:gravity="center" android:text="ORMLite-AddPage"/>  
  10.     <LinearLayout  
  11.        android:layout_width="fill_parent" android:layout_height="wrap_content"  
  12.        android:orientation="horizontal" android:padding="1dip" android:gravity="center_vertical">  
  13.        <TextView   
  14.           android:layout_width="wrap_content"  
  15.           android:layout_height="wrap_content"  
  16.           android:text="学号: "/>  
  17.        <EditText  
  18.           android:id="@+id/stuno"  
  19.           android:layout_width="fill_parent"  
  20.           android:layout_height="wrap_content"/>  
  21.     </LinearLayout>  
  22.     <LinearLayout  
  23.        android:layout_width="fill_parent" android:layout_height="wrap_content"  
  24.        android:orientation="horizontal" android:padding="1dip" android:gravity="center_vertical">  
  25.        <TextView   
  26.           android:layout_width="wrap_content"  
  27.           android:layout_height="wrap_content"  
  28.           android:text="姓名: "/>  
  29.        <EditText  
  30.           android:id="@+id/name"  
  31.           android:layout_width="fill_parent"  
  32.           android:layout_height="wrap_content"/>  
  33.     </LinearLayout>  
  34.     <LinearLayout  
  35.        android:layout_width="fill_parent" android:layout_height="wrap_content"  
  36.        android:orientation="horizontal" android:padding="1dip" android:gravity="center_vertical">  
  37.        <TextView   
  38.           android:layout_width="wrap_content"  
  39.           android:layout_height="wrap_content"  
  40.           android:text="年龄: "/>  
  41.        <EditText  
  42.           android:id="@+id/age"  
  43.           android:layout_width="fill_parent"  
  44.           android:layout_height="wrap_content"/>  
  45.     </LinearLayout>  
  46.     <LinearLayout  
  47.        android:layout_width="fill_parent" android:layout_height="wrap_content"  
  48.        android:orientation="horizontal" android:padding="1dip" android:gravity="center_vertical">  
  49.        <TextView   
  50.           android:layout_width="wrap_content"  
  51.           android:layout_height="wrap_content"  
  52.           android:text="性别: "/>  
  53.        <EditText  
  54.           android:id="@+id/sex"  
  55.           android:layout_width="fill_parent"  
  56.           android:layout_height="wrap_content"/>  
  57.     </LinearLayout>  
  58.     <LinearLayout  
  59.        android:layout_width="fill_parent" android:layout_height="wrap_content"  
  60.        android:orientation="horizontal" android:padding="1dip" android:gravity="center_vertical">  
  61.        <TextView   
  62.           android:layout_width="wrap_content"  
  63.           android:layout_height="wrap_content"  
  64.           android:text="分数: "/>  
  65.        <EditText  
  66.           android:id="@+id/score"  
  67.           android:layout_width="fill_parent"  
  68.           android:layout_height="wrap_content"/>  
  69.     </LinearLayout>  
  70.     <LinearLayout  
  71.        android:layout_width="fill_parent" android:layout_height="wrap_content"  
  72.        android:orientation="horizontal" android:padding="1dip" android:gravity="center_vertical">  
  73.        <TextView   
  74.           android:layout_width="wrap_content"  
  75.           android:layout_height="wrap_content"  
  76.           android:text="地址: "/>  
  77.        <EditText  
  78.           android:id="@+id/address"  
  79.           android:layout_width="fill_parent"  
  80.           android:layout_height="wrap_content"/>  
  81.     </LinearLayout>  
  82.       
  83. </LinearLayout>  
students.xml源码:

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.   xmlns:android="http://schemas.android.com/apk/res/android"  
  4.   android:orientation="vertical"  
  5.   android:layout_width="fill_parent"  
  6.   android:layout_height="fill_parent">  
  7.   <TextView    
  8.     android:layout_width="fill_parent"   
  9.     android:layout_height="wrap_content"  
  10.     android:gravity="center"  
  11.     android:text="ORMLite-Students"/>  
  12.   <ListView  
  13.     android:id="@+id/stulist"  
  14.     android:layout_width="fill_parent"  
  15.     android:layout_height="fill_parent"/>  
  16. </LinearLayout>  
studentitem.xml源码:

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.   xmlns:android="http://schemas.android.com/apk/res/android"  
  4.   android:orientation="horizontal"  
  5.   android:layout_width="fill_parent"  
  6.   android:layout_height="fill_parent">  
  7.   <TextView  
  8.      android:id="@+id/itemno"  
  9.      android:layout_width="fill_parent"  
  10.      android:layout_height="wrap_content"  
  11.      android:layout_weight="1"  
  12.      android:text="学号"  
  13.      android:gravity="center"/>  
  14.   <TextView  
  15.      android:id="@+id/itemname"  
  16.      android:layout_width="fill_parent"  
  17.      android:layout_height="wrap_content"  
  18.      android:layout_weight="1"  
  19.      android:text="姓名"  
  20.      android:gravity="center"/>  
  21.   <TextView  
  22.      android:id="@+id/itemscore"  
  23.      android:layout_width="fill_parent"  
  24.      android:layout_height="wrap_content"  
  25.      android:layout_weight="1"  
  26.      android:text="分数"  
  27.      android:gravity="center"/>  
  28. </LinearLayout>  
【3】包com.andyidea.bean下Student.java源码:

[html]  view plain copy
  1. package com.andyidea.bean;  
  2.   
  3. import java.io.Serializable;  
  4. import com.j256.ormlite.field.DatabaseField;  
  5.   
  6. public class Student implements Serializable {  
  7.   
  8.     private static final long serialVersionUID = -5683263669918171030L;  
  9.       
  10.     @DatabaseField(id=true)  
  11.     private String stuNO;  
  12.     @DatabaseField  
  13.     private String name;  
  14.     @DatabaseField  
  15.     private int age;  
  16.     @DatabaseField  
  17.     private String sex;  
  18.     @DatabaseField  
  19.     private double score;  
  20.     @DatabaseField  
  21.     private String address;  
  22.       
  23.     public String getStuNO() {  
  24.         return stuNO;  
  25.     }  
  26.     public void setStuNO(String stuNO) {  
  27.         this.stuNO = stuNO;  
  28.     }  
  29.       
  30.     public String getName() {  
  31.         return name;  
  32.     }  
  33.     public void setName(String name) {  
  34.         this.name = name;  
  35.     }  
  36.       
  37.     public int getAge() {  
  38.         return age;  
  39.     }  
  40.     public void setAge(int age) {  
  41.         this.age = age;  
  42.     }  
  43.       
  44.     public String getSex() {  
  45.         return sex;  
  46.     }  
  47.     public void setSex(String sex) {  
  48.         this.sex = sex;  
  49.     }  
  50.       
  51.     public double getScore() {  
  52.         return score;  
  53.     }  
  54.     public void setScore(double score) {  
  55.         this.score = score;  
  56.     }  
  57.       
  58.     public String getAddress() {  
  59.         return address;  
  60.     }  
  61.     public void setAddress(String address) {  
  62.         this.address = address;  
  63.     }  
  64.       
  65. }  
【4】包com.andyidea.db下DatabaseHelper.java源码:

[html]  view plain copy
  1. package com.andyidea.db;  
  2.   
  3. import java.sql.SQLException;  
  4.   
  5. import android.content.Context;  
  6. import android.database.sqlite.SQLiteDatabase;  
  7. import android.util.Log;  
  8.   
  9. import com.andyidea.bean.Student;  
  10. import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;  
  11. import com.j256.ormlite.dao.Dao;  
  12. import com.j256.ormlite.support.ConnectionSource;  
  13. import com.j256.ormlite.table.TableUtils;  
  14.   
  15. public class DatabaseHelper extends OrmLiteSqliteOpenHelper {  
  16.       
  17.     private static final String DATABASE_NAME = "ormlite.db";  
  18.     private static final int DATABASE_VERSION = 1;  
  19.       
  20.     private Dao<Student,Integer> stuDao = null;  
  21.       
  22.     public DatabaseHelper(Context context){  
  23.         super(context, DATABASE_NAME, null, DATABASE_VERSION);  
  24.     }  
  25.   
  26.     /**  
  27.      * 创建SQLite数据库  
  28.      */  
  29.     @Override  
  30.     public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {  
  31.         try {  
  32.             TableUtils.createTable(connectionSource, Student.class);  
  33.         } catch (SQLException e) {  
  34.             Log.e(DatabaseHelper.class.getName(), "Unable to create datbases", e);  
  35.         }  
  36.     }  
  37.   
  38.     /**  
  39.      * 更新SQLite数据库  
  40.      */  
  41.     @Override  
  42.     public void onUpgrade(  
  43.             SQLiteDatabase sqliteDatabase,   
  44.             ConnectionSource connectionSource,   
  45.             int oldVer,  
  46.             int newVer) {  
  47.         try {  
  48.             TableUtils.dropTable(connectionSource, Student.class, true);  
  49.             onCreate(sqliteDatabase, connectionSource);  
  50.         } catch (SQLException e) {  
  51.             Log.e(DatabaseHelper.class.getName(),   
  52.                     "Unable to upgrade database from version " + oldVer + " to new "  
  53.                     + newVer, e);  
  54.         }  
  55.     }  
  56.       
  57.     public Dao<Student,Integer> getStudentDao() throws SQLException{  
  58.         if(stuDao == null){  
  59.             stuDao = getDao(Student.class);  
  60.         }  
  61.         return stuDao;  
  62.     }  
  63.   
  64. }  
【5】包com.andyidea.ormsqlite下源码:

MainActivity.java源码:

[html]  view plain copy
  1. package com.andyidea.ormsqlite;  
  2.   
  3. import java.sql.SQLException;  
  4.   
  5. import com.andyidea.bean.Student;  
  6. import com.andyidea.db.DatabaseHelper;  
  7. import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;  
  8. import com.j256.ormlite.dao.Dao;  
  9.   
  10. import android.content.Intent;  
  11. import android.os.Bundle;  
  12. import android.view.Menu;  
  13. import android.view.MenuItem;  
  14. import android.widget.EditText;  
  15.   
  16. public class MainActivity extends OrmLiteBaseActivity<DatabaseHelper> {  
  17.       
  18.     private EditText stuNO;  
  19.     private EditText stuName;  
  20.     private EditText stuAge;  
  21.     private EditText stuSex;  
  22.     private EditText stuScore;  
  23.     private EditText stuAddress;  
  24.       
  25.     private Student mStudent;  
  26.     private Dao<Student,Integer> stuDao;  
  27.       
  28.     private final int MENU_ADD = Menu.FIRST;  
  29.     private final int MENU_VIEWALL = Menu.FIRST+1;  
  30.     private final int MENU_EDIT = Menu.FIRST+2;  
  31.       
  32.     private Bundle mBundle = new Bundle();  
  33.       
  34.     /** Called when the activity is first created. */  
  35.     @Override  
  36.     public void onCreate(Bundle savedInstanceState) {  
  37.         super.onCreate(savedInstanceState);  
  38.         setContentView(R.layout.main);  
  39.           
  40.         initializeViews();  
  41.     }  
  42.       
  43.     /**  
  44.      * 初始化UI界面  
  45.      */  
  46.     private void initializeViews(){  
  47.         stuNO = (EditText)findViewById(R.id.stuno);  
  48.         stuName = (EditText)findViewById(R.id.name);  
  49.         stuAge = (EditText)findViewById(R.id.age);  
  50.         stuSex = (EditText)findViewById(R.id.sex);  
  51.         stuScore = (EditText)findViewById(R.id.score);  
  52.         stuAddress = (EditText)findViewById(R.id.address);  
  53.           
  54.         mBundle = getIntent().getExtras();  
  55.         if(mBundle!=null && mBundle.getString("action").equals("viewone")){  
  56.             mStudent = (Student)getIntent().getSerializableExtra("entity");  
  57.             setStudentUIData(mStudent);  
  58.         }  
  59.           
  60.         if(mBundle!=null && mBundle.getString("action").equals("edit")){  
  61.             mStudent = (Student)getIntent().getSerializableExtra("entity");  
  62.             setStudentUIData(mStudent);  
  63.         }  
  64.     }  
  65.       
  66.     @Override  
  67.     public boolean onPrepareOptionsMenu(Menu menu) {  
  68.         if(mBundle!=null && mBundle.getString("action").equals("viewone"))  
  69.             return false;  
  70.         else  
  71.             return super.onPrepareOptionsMenu(menu);  
  72.           
  73.     }  
  74.   
  75.     @Override  
  76.     public boolean onCreateOptionsMenu(Menu menu) {  
  77.         if(mBundle!=null && mBundle.getString("action").equals("edit")){  
  78.             menu.add(1,MENU_EDIT,0,"保存");  
  79.         }else{  
  80.             menu.add(0,MENU_ADD,0,"增加");  
  81.             menu.add(0,MENU_VIEWALL,0,"查看");  
  82.         }  
  83.         return super.onCreateOptionsMenu(menu);  
  84.     }  
  85.   
  86.     @Override  
  87.     public boolean onOptionsItemSelected(MenuItem item) {  
  88.         switch (item.getItemId()) {  
  89.         case MENU_ADD:  
  90.             try {  
  91.                 stuDao = getHelper().getStudentDao();  
  92.                 getStudentData();  
  93.                 if(mStudent != null){  
  94.                     //创建记录项  
  95.                     stuDao.create(mStudent);  
  96.                 }  
  97.             } catch (SQLException e) {  
  98.                 e.printStackTrace();  
  99.             }  
  100.             break;  
  101.         case MENU_VIEWALL:  
  102.             Intent intent = new Intent();  
  103.             intent.setClass(MainActivity.this, StudentListActivity.class);  
  104.             startActivity(intent);  
  105.             break;  
  106.         case MENU_EDIT:  
  107.             try {  
  108.                 getStudentData();  
  109.                 stuDao = getHelper().getStudentDao();  
  110.                 if(mStudent != null){  
  111.                     //更新某记录项  
  112.                     stuDao.update(mStudent);  
  113.                 }  
  114.             } catch (SQLException e) {  
  115.                 e.printStackTrace();  
  116.             }  
  117.             break;  
  118.         default:  
  119.             break;  
  120.         }  
  121.         return super.onOptionsItemSelected(item);  
  122.     }  
  123.   
  124.     /**  
  125.      * 获取界面值(实体信息)  
  126.      */  
  127.     private void getStudentData(){  
  128.         mStudent = new Student();  
  129.         mStudent.setStuNO(stuNO.getText().toString());  
  130.         mStudent.setName(stuName.getText().toString());  
  131.         mStudent.setAge(Integer.parseInt(stuAge.getText().toString()));  
  132.         mStudent.setSex(stuSex.getText().toString());  
  133.         mStudent.setScore(Double.parseDouble(stuScore.getText().toString()));  
  134.         mStudent.setAddress(stuAddress.getText().toString());  
  135.     }  
  136.       
  137.     /**  
  138.      * 赋值给UI界面  
  139.      * @param student  
  140.      */  
  141.     private void setStudentUIData(Student student){  
  142.         stuNO.setText(student.getStuNO());  
  143.         stuName.setText(student.getName());  
  144.         stuAge.setText(String.valueOf(student.getAge()));  
  145.         stuSex.setText(student.getSex());  
  146.         stuScore.setText(String.valueOf(student.getScore()));  
  147.         stuAddress.setText(student.getAddress());  
  148.     }  
  149. }  
StudentListActivity.java源码:

[html]  view plain copy
  1. package com.andyidea.ormsqlite;  
  2.   
  3. import java.sql.SQLException;  
  4. import java.util.List;  
  5.   
  6. import android.app.AlertDialog;  
  7. import android.content.Context;  
  8. import android.content.DialogInterface;  
  9. import android.content.Intent;  
  10. import android.os.Bundle;  
  11. import android.view.ContextMenu;  
  12. import android.view.ContextMenu.ContextMenuInfo;  
  13. import android.view.LayoutInflater;  
  14. import android.view.Menu;  
  15. import android.view.MenuItem;  
  16. import android.view.View;  
  17. import android.view.ViewGroup;  
  18. import android.widget.AdapterView.AdapterContextMenuInfo;  
  19. import android.widget.BaseAdapter;  
  20. import android.widget.ListView;  
  21. import android.widget.TextView;  
  22.   
  23. import com.andyidea.bean.Student;  
  24. import com.andyidea.db.DatabaseHelper;  
  25. import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;  
  26. import com.j256.ormlite.dao.Dao;  
  27.   
  28. public class StudentListActivity extends OrmLiteBaseActivity<DatabaseHelper> {  
  29.       
  30.     private Context mContext;  
  31.     private ListView lvStudents;  
  32.     private Dao<Student,Integer> stuDao;  
  33.     private List<Student> students;  
  34.     private StudentsAdapter adapter;  
  35.     private Student mStudent;  
  36.       
  37.     private final int MENU_VIEW = Menu.FIRST;  
  38.     private final int MENU_EDIT = Menu.FIRST+1;  
  39.     private final int MENU_DELETE = Menu.FIRST+2;  
  40.       
  41.     private int position;  
  42.       
  43.     @Override  
  44.     public void onCreate(Bundle savedInstanceState) {  
  45.         super.onCreate(savedInstanceState);  
  46.         setContentView(R.layout.students);  
  47.         mContext = getApplicationContext();  
  48.           
  49.         lvStudents = (ListView)findViewById(R.id.stulist);  
  50.         registerForContextMenu(lvStudents);  //注册上下文菜单  
  51.           
  52.         queryListViewItem();  
  53.       
  54.         adapter = new StudentsAdapter(students);  
  55.         lvStudents.setAdapter(adapter);  
  56.           
  57.     }  
  58.   
  59.     @Override  
  60.     public void onCreateContextMenu(ContextMenu menu, View v,  
  61.             ContextMenuInfo menuInfo) {  
  62.         if(v == lvStudents)  
  63.             position = ((AdapterContextMenuInfo)menuInfo).position;  
  64.           
  65.         menu.add(0,MENU_VIEW, 0, "查看");  
  66.         menu.add(0,MENU_EDIT, 0, "编辑");  
  67.         menu.add(0,MENU_DELETE,0,"删除");  
  68.         super.onCreateContextMenu(menu, v, menuInfo);  
  69.     }  
  70.       
  71.     @Override  
  72.     public boolean onContextItemSelected(MenuItem item) {  
  73.         switch (item.getItemId()) {  
  74.         case MENU_VIEW:  
  75.             viewListViewItem(position);  
  76.             break;  
  77.         case MENU_EDIT:  
  78.             editListViewItem(position);  
  79.             break;  
  80.         case MENU_DELETE:  
  81.             deleteListViewItem(position);  
  82.             break;  
  83.         default:  
  84.             break;  
  85.         }  
  86.         return super.onContextItemSelected(item);  
  87.     }  
  88.       
  89.     /**  
  90.      * 查询记录项  
  91.      */  
  92.     private void queryListViewItem(){  
  93.         try {  
  94.             stuDao = getHelper().getStudentDao();  
  95.             //查询所有的记录项  
  96.             students = stuDao.queryForAll();  
  97.         } catch (SQLException e) {  
  98.             e.printStackTrace();  
  99.         }  
  100.     }  
  101.       
  102.     /**  
  103.      * 查看记录项  
  104.      * @param position  
  105.      */  
  106.     private void viewListViewItem(int position){  
  107.         mStudent = students.get(position);  
  108.         Intent intent = new Intent();  
  109.         intent.setClass(mContext, MainActivity.class);  
  110.         intent.putExtra("action", "viewone");  
  111.         intent.putExtra("entity", mStudent);  
  112.         startActivity(intent);  
  113.     }  
  114.       
  115.     /**  
  116.      * 编辑记录项  
  117.      */  
  118.     private void editListViewItem(int position){  
  119.         mStudent = students.get(position);  
  120.         Intent intent = new Intent();  
  121.         intent.setClass(mContext, MainActivity.class);  
  122.         intent.putExtra("action", "edit");  
  123.         intent.putExtra("entity", mStudent);  
  124.         startActivity(intent);  
  125.     }  
  126.       
  127.     /**  
  128.      * 删除记录项  
  129.      * @param position  
  130.      */  
  131.     private void deleteListViewItem(int position){  
  132.         final int pos = position;  
  133.         AlertDialog.Builder builder2 = new AlertDialog.Builder(StudentListActivity.this);  
  134.         builder2.setIcon(android.R.drawable.ic_dialog_alert)  
  135.                 .setTitle("警告")  
  136.                 .setMessage("确定要删除该记录");  
  137.         builder2.setPositiveButton("确定", new DialogInterface.OnClickListener() {  
  138.               
  139.             @Override  
  140.             public void onClick(DialogInterface dialog, int which) {  
  141.                 Student mDelStudent = (Student)lvStudents.getAdapter().getItem(pos);  
  142.                 try {  
  143.                     stuDao.delete(mDelStudent); //删除记录  
  144.                     queryListViewItem();  
  145.                 } catch (SQLException e) {  
  146.                     e.printStackTrace();  
  147.                 }  
  148.                   
  149.             }  
  150.         });  
  151.         builder2.setNegativeButton("取消", new DialogInterface.OnClickListener() {  
  152.               
  153.             @Override  
  154.             public void onClick(DialogInterface dialog, int which) {  
  155.                 dialog.dismiss();  
  156.             }  
  157.         });  
  158.         builder2.show();  
  159.     }  
  160.       
  161.     class StudentsAdapter extends BaseAdapter{  
  162.           
  163.         private List<Student> listStu;  
  164.           
  165.         public StudentsAdapter(List<Student> students){  
  166.             super();  
  167.             this.listStu = students;  
  168.         }  
  169.   
  170.         @Override  
  171.         public int getCount() {  
  172.             return listStu.size();  
  173.         }  
  174.   
  175.         @Override  
  176.         public Student getItem(int position) {  
  177.             return listStu.get(position);  
  178.         }  
  179.   
  180.         @Override  
  181.         public long getItemId(int position) {  
  182.             return position;  
  183.         }  
  184.   
  185.         @Override  
  186.         public View getView(int position, View convertView, ViewGroup parent) {  
  187.             ViewHolder holder;  
  188.             if(convertView == null){  
  189.                 LayoutInflater mInflater = (LayoutInflater) mContext  
  190.                         .getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  191.                 convertView = mInflater.inflate(R.layout.studentitem, null);  
  192.                 holder = new ViewHolder();  
  193.                 holder.tvNO = (TextView)convertView.findViewById(R.id.itemno);  
  194.                 holder.tvName = (TextView)convertView.findViewById(R.id.itemname);  
  195.                 holder.tvScore = (TextView)convertView.findViewById(R.id.itemscore);  
  196.                 convertView.setTag(holder);  
  197.             }else{  
  198.                 holder = (ViewHolder)convertView.getTag();  
  199.             }  
  200.               
  201.             Student objStu = listStu.get(position);  
  202.             holder.tvNO.setText(objStu.getStuNO());  
  203.             holder.tvName.setText(objStu.getName());  
  204.             holder.tvScore.setText(String.valueOf(objStu.getScore()));  
  205.               
  206.             return convertView;  
  207.         }  
  208.           
  209.     }  
  210.       
  211.     static class ViewHolder{  
  212.         TextView tvNO;  
  213.         TextView tvName;  
  214.         TextView tvScore;  
  215.     }  
  216.   
  217. }  
【6】成功运行程序的截图效果:



发布了33 篇原创文章 · 获赞 20 · 访问量 8万+

下载链接:http://ormlite.com/releases/

本博客文章中曾经提到过Ormlite的第三方组件包,Ormlite 是一种ORM工具,并且是一种轻量级别的工具。我们可以使用它来对Android中内嵌的sqlite数据库进行相关的操作。Android 的应用程序应使用 Ormlite for android 版本来进行相关的开发。Ormlite是对android提供的sqlite部分的API进行了封装。提供了更加方便的接口来供使用。

      本文以一个学生的信息实例程序来展示如何使用ormlite for android的第三方组件来开发Sqlite的C[增加],R[查询],U[更新],D[查询]应用程序,以便更方便的对sqlite数据库的操作。我们先看下程序的结构图:

【1】.程序结构图如下:

其中包com.andyidea.bean下Student.java为实体类,包com.andyidea.db下DatabaseHelper.java为数据库辅助类,包com.andyidea.ormsqlite下的MainActivity.java和StudentListActivity.java是界面信息类。同时我们别忘了在根目录下创建一个lib的文件夹,把第三方组件包ormlite-android-4.31.jar ,ormlite-core-4.31.jar,ormlite-jdbc-4.31.jar放到lib文件夹下,然后在项目中引用这三个包就OK了。

【2】布局文件源码如下:

main.xml源码:

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     android:padding="5dip">  
  7.     <TextView    
  8.     android:layout_width="fill_parent"  android:layout_height="wrap_content"  
  9.     android:gravity="center" android:text="ORMLite-AddPage"/>  
  10.     <LinearLayout  
  11.        android:layout_width="fill_parent" android:layout_height="wrap_content"  
  12.        android:orientation="horizontal" android:padding="1dip" android:gravity="center_vertical">  
  13.        <TextView   
  14.           android:layout_width="wrap_content"  
  15.           android:layout_height="wrap_content"  
  16.           android:text="学号: "/>  
  17.        <EditText  
  18.           android:id="@+id/stuno"  
  19.           android:layout_width="fill_parent"  
  20.           android:layout_height="wrap_content"/>  
  21.     </LinearLayout>  
  22.     <LinearLayout  
  23.        android:layout_width="fill_parent" android:layout_height="wrap_content"  
  24.        android:orientation="horizontal" android:padding="1dip" android:gravity="center_vertical">  
  25.        <TextView   
  26.           android:layout_width="wrap_content"  
  27.           android:layout_height="wrap_content"  
  28.           android:text="姓名: "/>  
  29.        <EditText  
  30.           android:id="@+id/name"  
  31.           android:layout_width="fill_parent"  
  32.           android:layout_height="wrap_content"/>  
  33.     </LinearLayout>  
  34.     <LinearLayout  
  35.        android:layout_width="fill_parent" android:layout_height="wrap_content"  
  36.        android:orientation="horizontal" android:padding="1dip" android:gravity="center_vertical">  
  37.        <TextView   
  38.           android:layout_width="wrap_content"  
  39.           android:layout_height="wrap_content"  
  40.           android:text="年龄: "/>  
  41.        <EditText  
  42.           android:id="@+id/age"  
  43.           android:layout_width="fill_parent"  
  44.           android:layout_height="wrap_content"/>  
  45.     </LinearLayout>  
  46.     <LinearLayout  
  47.        android:layout_width="fill_parent" android:layout_height="wrap_content"  
  48.        android:orientation="horizontal" android:padding="1dip" android:gravity="center_vertical">  
  49.        <TextView   
  50.           android:layout_width="wrap_content"  
  51.           android:layout_height="wrap_content"  
  52.           android:text="性别: "/>  
  53.        <EditText  
  54.           android:id="@+id/sex"  
  55.           android:layout_width="fill_parent"  
  56.           android:layout_height="wrap_content"/>  
  57.     </LinearLayout>  
  58.     <LinearLayout  
  59.        android:layout_width="fill_parent" android:layout_height="wrap_content"  
  60.        android:orientation="horizontal" android:padding="1dip" android:gravity="center_vertical">  
  61.        <TextView   
  62.           android:layout_width="wrap_content"  
  63.           android:layout_height="wrap_content"  
  64.           android:text="分数: "/>  
  65.        <EditText  
  66.           android:id="@+id/score"  
  67.           android:layout_width="fill_parent"  
  68.           android:layout_height="wrap_content"/>  
  69.     </LinearLayout>  
  70.     <LinearLayout  
  71.        android:layout_width="fill_parent" android:layout_height="wrap_content"  
  72.        android:orientation="horizontal" android:padding="1dip" android:gravity="center_vertical">  
  73.        <TextView   
  74.           android:layout_width="wrap_content"  
  75.           android:layout_height="wrap_content"  
  76.           android:text="地址: "/>  
  77.        <EditText  
  78.           android:id="@+id/address"  
  79.           android:layout_width="fill_parent"  
  80.           android:layout_height="wrap_content"/>  
  81.     </LinearLayout>  
  82.       
  83. </LinearLayout>  
students.xml源码:

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.   xmlns:android="http://schemas.android.com/apk/res/android"  
  4.   android:orientation="vertical"  
  5.   android:layout_width="fill_parent"  
  6.   android:layout_height="fill_parent">  
  7.   <TextView    
  8.     android:layout_width="fill_parent"   
  9.     android:layout_height="wrap_content"  
  10.     android:gravity="center"  
  11.     android:text="ORMLite-Students"/>  
  12.   <ListView  
  13.     android:id="@+id/stulist"  
  14.     android:layout_width="fill_parent"  
  15.     android:layout_height="fill_parent"/>  
  16. </LinearLayout>  
studentitem.xml源码:

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.   xmlns:android="http://schemas.android.com/apk/res/android"  
  4.   android:orientation="horizontal"  
  5.   android:layout_width="fill_parent"  
  6.   android:layout_height="fill_parent">  
  7.   <TextView  
  8.      android:id="@+id/itemno"  
  9.      android:layout_width="fill_parent"  
  10.      android:layout_height="wrap_content"  
  11.      android:layout_weight="1"  
  12.      android:text="学号"  
  13.      android:gravity="center"/>  
  14.   <TextView  
  15.      android:id="@+id/itemname"  
  16.      android:layout_width="fill_parent"  
  17.      android:layout_height="wrap_content"  
  18.      android:layout_weight="1"  
  19.      android:text="姓名"  
  20.      android:gravity="center"/>  
  21.   <TextView  
  22.      android:id="@+id/itemscore"  
  23.      android:layout_width="fill_parent"  
  24.      android:layout_height="wrap_content"  
  25.      android:layout_weight="1"  
  26.      android:text="分数"  
  27.      android:gravity="center"/>  
  28. </LinearLayout>  
【3】包com.andyidea.bean下Student.java源码:

[html]  view plain copy
  1. package com.andyidea.bean;  
  2.   
  3. import java.io.Serializable;  
  4. import com.j256.ormlite.field.DatabaseField;  
  5.   
  6. public class Student implements Serializable {  
  7.   
  8.     private static final long serialVersionUID = -5683263669918171030L;  
  9.       
  10.     @DatabaseField(id=true)  
  11.     private String stuNO;  
  12.     @DatabaseField  
  13.     private String name;  
  14.     @DatabaseField  
  15.     private int age;  
  16.     @DatabaseField  
  17.     private String sex;  
  18.     @DatabaseField  
  19.     private double score;  
  20.     @DatabaseField  
  21.     private String address;  
  22.       
  23.     public String getStuNO() {  
  24.         return stuNO;  
  25.     }  
  26.     public void setStuNO(String stuNO) {  
  27.         this.stuNO = stuNO;  
  28.     }  
  29.       
  30.     public String getName() {  
  31.         return name;  
  32.     }  
  33.     public void setName(String name) {  
  34.         this.name = name;  
  35.     }  
  36.       
  37.     public int getAge() {  
  38.         return age;  
  39.     }  
  40.     public void setAge(int age) {  
  41.         this.age = age;  
  42.     }  
  43.       
  44.     public String getSex() {  
  45.         return sex;  
  46.     }  
  47.     public void setSex(String sex) {  
  48.         this.sex = sex;  
  49.     }  
  50.       
  51.     public double getScore() {  
  52.         return score;  
  53.     }  
  54.     public void setScore(double score) {  
  55.         this.score = score;  
  56.     }  
  57.       
  58.     public String getAddress() {  
  59.         return address;  
  60.     }  
  61.     public void setAddress(String address) {  
  62.         this.address = address;  
  63.     }  
  64.       
  65. }  
【4】包com.andyidea.db下DatabaseHelper.java源码:

[html]  view plain copy
  1. package com.andyidea.db;  
  2.   
  3. import java.sql.SQLException;  
  4.   
  5. import android.content.Context;  
  6. import android.database.sqlite.SQLiteDatabase;  
  7. import android.util.Log;  
  8.   
  9. import com.andyidea.bean.Student;  
  10. import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;  
  11. import com.j256.ormlite.dao.Dao;  
  12. import com.j256.ormlite.support.ConnectionSource;  
  13. import com.j256.ormlite.table.TableUtils;  
  14.   
  15. public class DatabaseHelper extends OrmLiteSqliteOpenHelper {  
  16.       
  17.     private static final String DATABASE_NAME = "ormlite.db";  
  18.     private static final int DATABASE_VERSION = 1;  
  19.       
  20.     private Dao<Student,Integer> stuDao = null;  
  21.       
  22.     public DatabaseHelper(Context context){  
  23.         super(context, DATABASE_NAME, null, DATABASE_VERSION);  
  24.     }  
  25.   
  26.     /**  
  27.      * 创建SQLite数据库  
  28.      */  
  29.     @Override  
  30.     public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {  
  31.         try {  
  32.             TableUtils.createTable(connectionSource, Student.class);  
  33.         } catch (SQLException e) {  
  34.             Log.e(DatabaseHelper.class.getName(), "Unable to create datbases", e);  
  35.         }  
  36.     }  
  37.   
  38.     /**  
  39.      * 更新SQLite数据库  
  40.      */  
  41.     @Override  
  42.     public void onUpgrade(  
  43.             SQLiteDatabase sqliteDatabase,   
  44.             ConnectionSource connectionSource,   
  45.             int oldVer,  
  46.             int newVer) {  
  47.         try {  
  48.             TableUtils.dropTable(connectionSource, Student.class, true);  
  49.             onCreate(sqliteDatabase, connectionSource);  
  50.         } catch (SQLException e) {  
  51.             Log.e(DatabaseHelper.class.getName(),   
  52.                     "Unable to upgrade database from version " + oldVer + " to new "  
  53.                     + newVer, e);  
  54.         }  
  55.     }  
  56.       
  57.     public Dao<Student,Integer> getStudentDao() throws SQLException{  
  58.         if(stuDao == null){  
  59.             stuDao = getDao(Student.class);  
  60.         }  
  61.         return stuDao;  
  62.     }  
  63.   
  64. }  
【5】包com.andyidea.ormsqlite下源码:

MainActivity.java源码:

[html]  view plain copy
  1. package com.andyidea.ormsqlite;  
  2.   
  3. import java.sql.SQLException;  
  4.   
  5. import com.andyidea.bean.Student;  
  6. import com.andyidea.db.DatabaseHelper;  
  7. import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;  
  8. import com.j256.ormlite.dao.Dao;  
  9.   
  10. import android.content.Intent;  
  11. import android.os.Bundle;  
  12. import android.view.Menu;  
  13. import android.view.MenuItem;  
  14. import android.widget.EditText;  
  15.   
  16. public class MainActivity extends OrmLiteBaseActivity<DatabaseHelper> {  
  17.       
  18.     private EditText stuNO;  
  19.     private EditText stuName;  
  20.     private EditText stuAge;  
  21.     private EditText stuSex;  
  22.     private EditText stuScore;  
  23.     private EditText stuAddress;  
  24.       
  25.     private Student mStudent;  
  26.     private Dao<Student,Integer> stuDao;  
  27.       
  28.     private final int MENU_ADD = Menu.FIRST;  
  29.     private final int MENU_VIEWALL = Menu.FIRST+1;  
  30.     private final int MENU_EDIT = Menu.FIRST+2;  
  31.       
  32.     private Bundle mBundle = new Bundle();  
  33.       
  34.     /** Called when the activity is first created. */  
  35.     @Override  
  36.     public void onCreate(Bundle savedInstanceState) {  
  37.         super.onCreate(savedInstanceState);  
  38.         setContentView(R.layout.main);  
  39.           
  40.         initializeViews();  
  41.     }  
  42.       
  43.     /**  
  44.      * 初始化UI界面  
  45.      */  
  46.     private void initializeViews(){  
  47.         stuNO = (EditText)findViewById(R.id.stuno);  
  48.         stuName = (EditText)findViewById(R.id.name);  
  49.         stuAge = (EditText)findViewById(R.id.age);  
  50.         stuSex = (EditText)findViewById(R.id.sex);  
  51.         stuScore = (EditText)findViewById(R.id.score);  
  52.         stuAddress = (EditText)findViewById(R.id.address);  
  53.           
  54.         mBundle = getIntent().getExtras();  
  55.         if(mBundle!=null && mBundle.getString("action").equals("viewone")){  
  56.             mStudent = (Student)getIntent().getSerializableExtra("entity");  
  57.             setStudentUIData(mStudent);  
  58.         }  
  59.           
  60.         if(mBundle!=null && mBundle.getString("action").equals("edit")){  
  61.             mStudent = (Student)getIntent().getSerializableExtra("entity");  
  62.             setStudentUIData(mStudent);  
  63.         }  
  64.     }  
  65.       
  66.     @Override  
  67.     public boolean onPrepareOptionsMenu(Menu menu) {  
  68.         if(mBundle!=null && mBundle.getString("action").equals("viewone"))  
  69.             return false;  
  70.         else  
  71.             return super.onPrepareOptionsMenu(menu);  
  72.           
  73.     }  
  74.   
  75.     @Override  
  76.     public boolean onCreateOptionsMenu(Menu menu) {  
  77.         if(mBundle!=null && mBundle.getString("action").equals("edit")){  
  78.             menu.add(1,MENU_EDIT,0,"保存");  
  79.         }else{  
  80.             menu.add(0,MENU_ADD,0,"增加");  
  81.             menu.add(0,MENU_VIEWALL,0,"查看");  
  82.         }  
  83.         return super.onCreateOptionsMenu(menu);  
  84.     }  
  85.   
  86.     @Override  
  87.     public boolean onOptionsItemSelected(MenuItem item) {  
  88.         switch (item.getItemId()) {  
  89.         case MENU_ADD:  
  90.             try {  
  91.                 stuDao = getHelper().getStudentDao();  
  92.                 getStudentData();  
  93.                 if(mStudent != null){  
  94.                     //创建记录项  
  95.                     stuDao.create(mStudent);  
  96.                 }  
  97.             } catch (SQLException e) {  
  98.                 e.printStackTrace();  
  99.             }  
  100.             break;  
  101.         case MENU_VIEWALL:  
  102.             Intent intent = new Intent();  
  103.             intent.setClass(MainActivity.this, StudentListActivity.class);  
  104.             startActivity(intent);  
  105.             break;  
  106.         case MENU_EDIT:  
  107.             try {  
  108.                 getStudentData();  
  109.                 stuDao = getHelper().getStudentDao();  
  110.                 if(mStudent != null){  
  111.                     //更新某记录项  
  112.                     stuDao.update(mStudent);  
  113.                 }  
  114.             } catch (SQLException e) {  
  115.                 e.printStackTrace();  
  116.             }  
  117.             break;  
  118.         default:  
  119.             break;  
  120.         }  
  121.         return super.onOptionsItemSelected(item);  
  122.     }  
  123.   
  124.     /**  
  125.      * 获取界面值(实体信息)  
  126.      */  
  127.     private void getStudentData(){  
  128.         mStudent = new Student();  
  129.         mStudent.setStuNO(stuNO.getText().toString());  
  130.         mStudent.setName(stuName.getText().toString());  
  131.         mStudent.setAge(Integer.parseInt(stuAge.getText().toString()));  
  132.         mStudent.setSex(stuSex.getText().toString());  
  133.         mStudent.setScore(Double.parseDouble(stuScore.getText().toString()));  
  134.         mStudent.setAddress(stuAddress.getText().toString());  
  135.     }  
  136.       
  137.     /**  
  138.      * 赋值给UI界面  
  139.      * @param student  
  140.      */  
  141.     private void setStudentUIData(Student student){  
  142.         stuNO.setText(student.getStuNO());  
  143.         stuName.setText(student.getName());  
  144.         stuAge.setText(String.valueOf(student.getAge()));  
  145.         stuSex.setText(student.getSex());  
  146.         stuScore.setText(String.valueOf(student.getScore()));  
  147.         stuAddress.setText(student.getAddress());  
  148.     }  
  149. }  
StudentListActivity.java源码:

[html]  view plain copy
  1. package com.andyidea.ormsqlite;  
  2.   
  3. import java.sql.SQLException;  
  4. import java.util.List;  
  5.   
  6. import android.app.AlertDialog;  
  7. import android.content.Context;  
  8. import android.content.DialogInterface;  
  9. import android.content.Intent;  
  10. import android.os.Bundle;  
  11. import android.view.ContextMenu;  
  12. import android.view.ContextMenu.ContextMenuInfo;  
  13. import android.view.LayoutInflater;  
  14. import android.view.Menu;  
  15. import android.view.MenuItem;  
  16. import android.view.View;  
  17. import android.view.ViewGroup;  
  18. import android.widget.AdapterView.AdapterContextMenuInfo;  
  19. import android.widget.BaseAdapter;  
  20. import android.widget.ListView;  
  21. import android.widget.TextView;  
  22.   
  23. import com.andyidea.bean.Student;  
  24. import com.andyidea.db.DatabaseHelper;  
  25. import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;  
  26. import com.j256.ormlite.dao.Dao;  
  27.   
  28. public class StudentListActivity extends OrmLiteBaseActivity<DatabaseHelper> {  
  29.       
  30.     private Context mContext;  
  31.     private ListView lvStudents;  
  32.     private Dao<Student,Integer> stuDao;  
  33.     private List<Student> students;  
  34.     private StudentsAdapter adapter;  
  35.     private Student mStudent;  
  36.       
  37.     private final int MENU_VIEW = Menu.FIRST;  
  38.     private final int MENU_EDIT = Menu.FIRST+1;  
  39.     private final int MENU_DELETE = Menu.FIRST+2;  
  40.       
  41.     private int position;  
  42.       
  43.     @Override  
  44.     public void onCreate(Bundle savedInstanceState) {  
  45.         super.onCreate(savedInstanceState);  
  46.         setContentView(R.layout.students);  
  47.         mContext = getApplicationContext();  
  48.           
  49.         lvStudents = (ListView)findViewById(R.id.stulist);  
  50.         registerForContextMenu(lvStudents);  //注册上下文菜单  
  51.           
  52.         queryListViewItem();  
  53.       
  54.         adapter = new StudentsAdapter(students);  
  55.         lvStudents.setAdapter(adapter);  
  56.           
  57.     }  
  58.   
  59.     @Override  
  60.     public void onCreateContextMenu(ContextMenu menu, View v,  
  61.             ContextMenuInfo menuInfo) {  
  62.         if(v == lvStudents)  
  63.             position = ((AdapterContextMenuInfo)menuInfo).position;  
  64.           
  65.         menu.add(0,MENU_VIEW, 0, "查看");  
  66.         menu.add(0,MENU_EDIT, 0, "编辑");  
  67.         menu.add(0,MENU_DELETE,0,"删除");  
  68.         super.onCreateContextMenu(menu, v, menuInfo);  
  69.     }  
  70.       
  71.     @Override  
  72.     public boolean onContextItemSelected(MenuItem item) {  
  73.         switch (item.getItemId()) {  
  74.         case MENU_VIEW:  
  75.             viewListViewItem(position);  
  76.             break;  
  77.         case MENU_EDIT:  
  78.             editListViewItem(position);  
  79.             break;  
  80.         case MENU_DELETE:  
  81.             deleteListViewItem(position);  
  82.             break;  
  83.         default:  
  84.             break;  
  85.         }  
  86.         return super.onContextItemSelected(item);  
  87.     }  
  88.       
  89.     /**  
  90.      * 查询记录项  
  91.      */  
  92.     private void queryListViewItem(){  
  93.         try {  
  94.             stuDao = getHelper().getStudentDao();  
  95.             //查询所有的记录项  
  96.             students = stuDao.queryForAll();  
  97.         } catch (SQLException e) {  
  98.             e.printStackTrace();  
  99.         }  
  100.     }  
  101.       
  102.     /**  
  103.      * 查看记录项  
  104.      * @param position  
  105.      */  
  106.     private void viewListViewItem(int position){  
  107.         mStudent = students.get(position);  
  108.         Intent intent = new Intent();  
  109.         intent.setClass(mContext, MainActivity.class);  
  110.         intent.putExtra("action", "viewone");  
  111.         intent.putExtra("entity", mStudent);  
  112.         startActivity(intent);  
  113.     }  
  114.       
  115.     /**  
  116.      * 编辑记录项  
  117.      */  
  118.     private void editListViewItem(int position){  
  119.         mStudent = students.get(position);  
  120.         Intent intent = new Intent();  
  121.         intent.setClass(mContext, MainActivity.class);  
  122.         intent.putExtra("action", "edit");  
  123.         intent.putExtra("entity", mStudent);  
  124.         startActivity(intent);  
  125.     }  
  126.       
  127.     /**  
  128.      * 删除记录项  
  129.      * @param position  
  130.      */  
  131.     private void deleteListViewItem(int position){  
  132.         final int pos = position;  
  133.         AlertDialog.Builder builder2 = new AlertDialog.Builder(StudentListActivity.this);  
  134.         builder2.setIcon(android.R.drawable.ic_dialog_alert)  
  135.                 .setTitle("警告")  
  136.                 .setMessage("确定要删除该记录");  
  137.         builder2.setPositiveButton("确定", new DialogInterface.OnClickListener() {  
  138.               
  139.             @Override  
  140.             public void onClick(DialogInterface dialog, int which) {  
  141.                 Student mDelStudent = (Student)lvStudents.getAdapter().getItem(pos);  
  142.                 try {  
  143.                     stuDao.delete(mDelStudent); //删除记录  
  144.                     queryListViewItem();  
  145.                 } catch (SQLException e) {  
  146.                     e.printStackTrace();  
  147.                 }  
  148.                   
  149.             }  
  150.         });  
  151.         builder2.setNegativeButton("取消", new DialogInterface.OnClickListener() {  
  152.               
  153.             @Override  
  154.             public void onClick(DialogInterface dialog, int which) {  
  155.                 dialog.dismiss();  
  156.             }  
  157.         });  
  158.         builder2.show();  
  159.     }  
  160.       
  161.     class StudentsAdapter extends BaseAdapter{  
  162.           
  163.         private List<Student> listStu;  
  164.           
  165.         public StudentsAdapter(List<Student> students){  
  166.             super();  
  167.             this.listStu = students;  
  168.         }  
  169.   
  170.         @Override  
  171.         public int getCount() {  
  172.             return listStu.size();  
  173.         }  
  174.   
  175.         @Override  
  176.         public Student getItem(int position) {  
  177.             return listStu.get(position);  
  178.         }  
  179.   
  180.         @Override  
  181.         public long getItemId(int position) {  
  182.             return position;  
  183.         }  
  184.   
  185.         @Override  
  186.         public View getView(int position, View convertView, ViewGroup parent) {  
  187.             ViewHolder holder;  
  188.             if(convertView == null){  
  189.                 LayoutInflater mInflater = (LayoutInflater) mContext  
  190.                         .getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  191.                 convertView = mInflater.inflate(R.layout.studentitem, null);  
  192.                 holder = new ViewHolder();  
  193.                 holder.tvNO = (TextView)convertView.findViewById(R.id.itemno);  
  194.                 holder.tvName = (TextView)convertView.findViewById(R.id.itemname);  
  195.                 holder.tvScore = (TextView)convertView.findViewById(R.id.itemscore);  
  196.                 convertView.setTag(holder);  
  197.             }else{  
  198.                 holder = (ViewHolder)convertView.getTag();  
  199.             }  
  200.               
  201.             Student objStu = listStu.get(position);  
  202.             holder.tvNO.setText(objStu.getStuNO());  
  203.             holder.tvName.setText(objStu.getName());  
  204.             holder.tvScore.setText(String.valueOf(objStu.getScore()));  
  205.               
  206.             return convertView;  
  207.         }  
  208.           
  209.     }  
  210.       
  211.     static class ViewHolder{  
  212.         TextView tvNO;  
  213.         TextView tvName;  
  214.         TextView tvScore;  
  215.     }  
  216.   
  217. }  
【6】成功运行程序的截图效果:



猜你喜欢

转载自blog.csdn.net/huangwenkui1990/article/details/39272355