android sqlLite 及Adapter 自定义和Adapter 改变UI
程序员文章站
2023-12-29 12:05:04
...
Android 在运行时(run-time)集成了 SQLite,所以每个 Android 应用程序都可以使用 SQLite 数据库。对于熟悉 SQL 的开发人员来时,在 Android 开发中使用 SQLite 相当简单。但是,由于 JDBC 会消耗太多的系统资源,所以 JDBC 对于手机这种内存受限设备来说并不合适。因此,Android 提供了一些新的 API 来使用 SQLite 数据库,Android 开发中,程序员需要学使用这些 API。
数据库存储在 data/< 项目文件夹 >/databases/ 下。
另推荐一个网站 http://www.ibm.com/developerworks/cn/opensource/os-cn-sqlite/
上面这篇文章很不错!
我上网找了些资料! 大部分资料是继承SQLiteDatabase,这样相对来说比较麻烦!
下面是sqllite代码
public class SqlListeHelper { private final static String DATABASE_NAME = "test.db"; //数据库名 private final static String TABLE_NAME = "sec_pwd"; //表名 public final static String FIELD_ID = "_id"; //字段名 public final static String FIELD_TITLE = "sec_Title"; //字段名 SQLiteDatabase dba ; Context _context ; /** * android.content.Context 中提供了函数 , 注: Activity 是 Context 的子类 * openOrCreateDatabase () 来创建我们的数据库 *db = context .openOrCreateDatabase(String DATABASE_NAME , int Context. MODE_PRIVATE , null ); *String DATABASE_NAME 数据库的名字 *Int MODE 操作模式 Context.MODE_PRIVATE 等 *CursorFactory 指针工厂 ,本例中传入 null ,暂不用 * @param context */ public SqlListeHelper(Context context) { _context = context; this.dba = _context.openOrCreateDatabase(DATABASE_NAME,Context.MODE_PRIVATE, null); createTable(); //获取数据的存储路径 System.out.println("------path["+dba.getPath()+"]--------------"); } /** * 创建表 */ public void createTable() { // TODO Auto-generated method stub String sql = "Create table " + TABLE_NAME + "(" + FIELD_ID + " integer primary key autoincrement," + FIELD_TITLE + " text )"; System.out.println("--------onCreate---------" +sql); try { dba.execSQL(sql); //执行sql语句 无 返回结果 } catch (Exception e) { System.out.println("table already exists (表已存在)"); } } /** * 查询表数据 * @return */ public List select() { String sql = "select * from "+TABLE_NAME +" t where 1=1"; Cursor cursor = dba.rawQuery(sql, new String[]{}); int size = 0; List list= null; UserInfo user = null; if(cursor !=null) size = cursor.getCount(); //获取数据大小 list = new ArrayList(); //将指针移到第一条 cursor.moveToFirst(); //cursor.isAfterLast() 指是否到最后一条 while (!cursor.isAfterLast()){ user = new UserInfo(); user.setId(cursor.getInt(cursor.getColumnIndex(FIELD_ID))); user.setPwd(cursor.getString(cursor.getColumnIndex(FIELD_TITLE))); list.add(user); //移到下条数据 cursor.moveToNext(); } cursor.close(); return list; } public void insert(int id, String Title) { // new Object[]{id,Title}; 类似 key ,value Object[] params = new Object[]{id,Title}; String sql = "insert into " + TABLE_NAME + "("+FIELD_ID+","+FIELD_TITLE+") VALUES(?,?)"; System.out.println("addsql = " + sql); //执行sql语句 this.dba.execSQL(sql,params); } }
注意的是 cursor.getColumnIndex 其实类似字符串中的indexOf 作用 也就是获取字段位置
至于 cursor.getInt () 和 cursor.getString() 我想连
接过数据库的都知道!就不多解释!
大概的就写这两个比较代表性的方法,相对来说,查询比较麻烦点! 而添加与删除和修改差不多!就不多写了!
================== Adapter 的使用 ===============
---------------------------- Adapter 重写 start --------------------------------------------------------
要想更好的使用 Adapter 或者想在listview中更好的添加自己的UI ,用重写 Adapter 就更好不过了
如下代码:
//重写Adapter class MyArrayAdapter extends ArrayAdapter{ private Context _context; private List<UserInfo> item; public MyArrayAdapter(Context context, int textViewResourceId,List _item) { super(context, textViewResourceId); //To change body of overridden methods use File | Settings | File Templates. this.item = _item; this._context = context; } public void add(UserInfo user) { if(user == null) item = new ArrayList(); item.add(user); } @Override public int getCount() { try { if(item == null) return 0; else return item.size(); } catch (Exception e) { return 0; } } @Override public Object getItem(int position) { if(item != null) return item.get(position) ; else return null; } @Override public View getView(int position, View convertView, ViewGroup parent) { View _convertView = convertView; if (convertView == null) { LayoutInflater factory = LayoutInflater.from(_context); final View textEntryView = factory.inflate( R.layout.listview_item, null); _convertView = textEntryView; } UserInfo userInfo = item.get(position); if(userInfo != null){ TextView id_tv = (TextView)_convertView.findViewById(R.id.item_idet); if(id_tv != null) id_tv.setText(userInfo.getId()+""); TextView title_tv =(TextView) _convertView.findViewById(R.id.item_titileet); if(title_tv != null) title_tv.setText(userInfo.getPwd()); } return _convertView; } }
还有,就是在写activity的事实要继承ListActivity 因为这样更加方便使用 Adapter,
注意的是,有的人,习惯了直接用 findViewById(R.id.item_idet),而不是 _convertView.findViewById(R.id.item_idet)
,如果你这样操作,会导致错误产生!出现空!原因就在于你加载的Layout 的xml配置文件!
其他的都好理解,就是怎么使用List集合!
---------------------------- Adapter 重写 end --------------------------------------------------------
---------------------------- Adapter 改变UI start --------------------------------------------------------
我是用sqllite和此demo一起使用的!有数据才方便测试学习!还有在配置文件中,添加的主配置文件中要添加红线部分(内置ID) 如下图:
private SqlListeHelper helper; private static MyArrayAdapter myArrayAdapter = null; setContentView(R.layout.main); //new MyArrayAdapter(this, R.layout.main, getData()) 可以看重写 就知道原因 setListAdapter(new MyArrayAdapter(this, R.layout.main, getData())); myArrayAdapter = (MyArrayAdapter)getListAdapter(); //此处 myArrayAdapter 为全局 方便UI改变 if(myArrayAdapter != null) System.out.println("getCount["+myArrayAdapter.getCount()+"]"); private List<Map<String,Object>> getData(){ List<Map<String,Object>> list = new ArrayList<Map<String, Object>>(); List data = helper.select(); //查询sqllite表中数据 Map userMap = null; if(data == null) return null; return data; }
注意,UI改变的时候要用到Message ,以及handler不然会出现异常,导致系统崩溃!
如下!
Message ms = Message.obtain(updateUIHandler); ms.what = UPDATEUIADAPTER; ms.obj = u; ms.sendToTarget();
//下面最为关键的是 myArrayAdapter.notifyDataSetChanged(); 此行代码 为改变UI关键
Handler updateUIHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case UPDATEUIADAPTER: UserInfo user = (UserInfo)msg.obj; if(user != null && myArrayAdapter != null){ myArrayAdapter.add(user); myArrayAdapter =(MyArrayAdapter) getListAdapter(); myArrayAdapter.notifyDataSetChanged(); } break; default: break; } } } ;
---------------------------- Adapter 改变UI end --------------------------------------------------------
下面例子是我与sqllite一起使用的demo代码!sqllite中代码已经在上面贴出与大家分享!
public class MyActivity extends ListActivity { private final int UPDATEUIADAPTER = 1; private static EditText addEt = null; private static Button addbtn = null; private static Button querybtn = null; private static EditText queryet = null; private static Context _context ; private ListView listView = null; private SimpleAdapter adapter = null ; private static MyArrayAdapter myArrayAdapter = null; private SQLiteDatabase base ; private SqlListeHelper helper; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { _context = this; helper = new SqlListeHelper(_context); // base = helper.getWritableDatabase(); super.onCreate(savedInstanceState); setContentView(R.layout.main); listView = new ListView(_context); // setListAdapter(new MyArrayAdapter(this, R.layout.main, getData())); myArrayAdapter = (MyArrayAdapter)getListAdapter(); if(myArrayAdapter != null) System.out.println("getCount["+myArrayAdapter.getCount()+"]"); addEt = (EditText)findViewById(R.id.addet); queryet = (EditText)findViewById(R.id.queryet); addbtn = (Button)findViewById(R.id.addbtn); querybtn = (Button)findViewById(R.id.querybtn); addbtn.setOnClickListener(addBtnOnClickListener); querybtn.setOnClickListener(queryBtnOnClickListener); } private List<Map<String,Object>> getData(){ List<Map<String,Object>> list = new ArrayList<Map<String, Object>>(); List data = helper.select(); Map userMap = null; if(data == null) return null; return data; } View.OnClickListener addBtnOnClickListener = new View.OnClickListener(){ public void onClick(View view) { Toast.makeText(_context,"你好哈!",Toast.LENGTH_LONG).show(); if(addEt.getText().toString().equals("")) return; else{ String addStr = addEt.getText().toString(); UserInfo u = new UserInfo(); u.setPwd("hi![" + addStr + "]"); u.setId(Integer.parseInt(addStr.trim())); helper.insert(Integer.parseInt(addStr.trim()), "hi![" + addStr + "]"); Message ms = Message.obtain(updateUIHandler); ms.what = UPDATEUIADAPTER; ms.obj = u; ms.sendToTarget(); } } } ; Handler updateUIHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case UPDATEUIADAPTER: UserInfo user = (UserInfo)msg.obj; if(user != null && myArrayAdapter != null){ myArrayAdapter.add(user); myArrayAdapter =(MyArrayAdapter) getListAdapter(); myArrayAdapter.notifyDataSetChanged(); } break; default: break; } } } ; View.OnClickListener queryBtnOnClickListener = new View.OnClickListener(){ public void onClick(View view) { List list = helper.select(); System.out.println("count :"+list.size()); } }; //重写Adapter class MyArrayAdapter extends ArrayAdapter{ private Context _context; private List<UserInfo> item; public MyArrayAdapter(Context context, int textViewResourceId,List _item) { super(context, textViewResourceId); //To change body of overridden methods use File | Settings | File Templates. this.item = _item; this._context = context; } public void add(UserInfo user) { if(user == null) item = new ArrayList(); item.add(user); } @Override public int getCount() { try { if(item == null) return 0; else return item.size(); } catch (Exception e) { return 0; } } @Override public Object getItem(int position) { if(item != null) return item.get(position) ; else return null; } @Override public View getView(int position, View convertView, ViewGroup parent) { View _convertView = convertView; if (convertView == null) { LayoutInflater factory = LayoutInflater.from(_context); final View textEntryView = factory.inflate( R.layout.listview_item, null); _convertView = textEntryView; } UserInfo userInfo = item.get(position); if(userInfo != null){ TextView id_tv = (TextView)_convertView.findViewById(R.id.item_idet); if(id_tv != null) id_tv.setText(userInfo.getId()+""); TextView title_tv =(TextView) _convertView.findViewById(R.id.item_titileet); if(title_tv != null) title_tv.setText(userInfo.getPwd()); } return _convertView; } } }