本文主要是介绍利用CP查询数据,通过代理模式进行ListView展现数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
源码下载 点击打开链接
这个例子有2个小应用
第一个小应用就是创建数据库DataBase,然后Insert插入几条测试数据,然后对外提供CP接口
第二个小应用就是通过代理模式进行数据的获取,以及展现ListView界面
先看第一个应用的代码
首先是MyApplication进行数据库初始化操作,并且对外提供实例对象
package com.example.mydatabase;import android.app.Application;public class MyApplication extends Application{private static MyApplication myApplication;@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();MyApplication.myApplication = this;/*** 创建数据库--初始化数据库*/SqliteManager.getInstance();}/*** 对外提供一个方法,就是获取本类对象,环境*/public static MyApplication getMyApplication(){return myApplication;}
}
接下来进行数据库的创建工作MyDataBaseOpenHelper
package com.example.mydatabase;import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;public class MyDataBaseOpenHelper extends SQLiteOpenHelper {private static String name = "geek.db";public static String table = "student";private static String TAG = "MyDataBaseOpenHelper";public MyDataBaseOpenHelper(Context mContext) {super(mContext, name, null, 1);}/*** 创建数据库*/@Overridepublic void onCreate(SQLiteDatabase db) {creatTableForStu(db);}private void creatTableForStu(SQLiteDatabase db) {String sql = "create table if not exists " + table + "("+ BaseCloumn.ID + " integer primary key autoincrement,"+ BaseCloumn.NAME + " text," + BaseCloumn.AGE + " text)";Log.i(TAG, "sql-->>"+sql);db.execSQL(sql);}static class BaseCloumn {public static String ID = "id";public static String AGE = "age";public static String NAME = "name";}/*** 先不考虑*/@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stub}}
最后SqliteManager提供数据库的增删改查方法
package com.example.mydatabase;import com.example.mydatabase.MyDataBaseOpenHelper.BaseCloumn;import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;public class SqliteManager {private static SqliteManager manager;private MyDataBaseOpenHelper dataBaseOpenHelper;private SQLiteDatabase sqLiteDatabase;//单利设计模式public static SqliteManager getInstance(){if (null == manager) {manager = new SqliteManager();}return manager;}private SqliteManager(){super();/** 打开数据库*/openDataBase();}private void openDataBase() {if (null == dataBaseOpenHelper) {dataBaseOpenHelper = new MyDataBaseOpenHelper(MyApplication.getMyApplication());}if (null == sqLiteDatabase) {sqLiteDatabase = dataBaseOpenHelper.getWritableDatabase();}}public SQLiteDatabase getDataBase(){return sqLiteDatabase;}/*** 测试插入数据库的数据*/public void inserData(){for (int i = 0; i < 10; i++) {ContentValues values = new ContentValues();values.put(BaseCloumn.NAME, i+"");values.put(BaseCloumn.AGE, i+"");sqLiteDatabase.insertOrThrow(MyDataBaseOpenHelper.table, null, values);}}
}
package com.example.mydatabase;import java.net.URL;import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.provider.ContactsContract.Contacts.Data;
import android.util.Log;public class MyProvider extends ContentProvider{private static String TAG = "MyProvider";
private static String authority = "com.example.mydatabase.MyProvider";private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);static{//全表matcher.addURI(authority, MyDataBaseOpenHelper.table, 2);//idmatcher.addURI(authority, MyDataBaseOpenHelper.table+"/#", 3);}@Overridepublic Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {// TODO Auto-generated method stub/*** 查询会返回一个cursor* wher name=? and age=? [] []*/int matchCode = matcher.match(uri);Cursor cursor = null;if (matchCode == 2) {SQLiteDatabase dataBase = SqliteManager.getInstance().getDataBase();/*** 充分了解cp里面的自段意思* 以及充分了解数据库的增删改查的参数意思*/cursor = dataBase.query(MyDataBaseOpenHelper.table, projection, selection, selectionArgs, null, null, sortOrder);}else if (matchCode == 3) {/*** 通过id进行查询,所以得获取id*/long parseId = ContentUris.parseId(uri);SQLiteDatabase dataBase = SqliteManager.getInstance().getDataBase();cursor = dataBase.query(MyDataBaseOpenHelper.table, projection, "id="+parseId, null, null, null, sortOrder);}else {Log.e(TAG, "uri error");throw new RuntimeException("uri error");}return cursor;}@Overridepublic int delete(Uri uri, String selection, String[] selectionArgs) {// TODO Auto-generated method stubreturn 0;}@Overridepublic String getType(Uri uri) {// TODO Auto-generated method stubreturn null;}@Overridepublic Uri insert(Uri uri, ContentValues values) {// TODO Auto-generated method stubreturn null;}@Overridepublic boolean onCreate() {// TODO Auto-generated method stubreturn false;}@Overridepublic int update(Uri uri, ContentValues values, String selection,String[] selectionArgs) {// TODO Auto-generated method stubreturn 0;}}
然后在入口activity进行插入数据
MainActivity
package com.example.mydatabase;import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);SqliteManager.getInstance().inserData();}}
------------------接下来看第二个小应用-----------------
既然涉及到代理类那么先看接口MyInterface
package com.example.myproxydemo;public interface MyInterface {void queryData();
}
接下来看代理类MyProxy
package com.example.myproxydemo;public class MyProxy implements MyInterface{private ListViewManger listViewManger;@Overridepublic void queryData() {listViewManger.queryData();}MyProxy(ListViewManger listViewManger){this.listViewManger = listViewManger;}
}
接下来看ListViewManger
package com.example.myproxydemo;import java.util.ArrayList;import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.StaticLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;public class ListViewManger implements MyInterface{private static String remoteUri = "content://com.example.mydatabase.MyProvider/student";private ContentResolver contentResolver;private ListView mListView;private Context mContext;@Overridepublic void queryData() {/*** 第一步获取数据* 第二部,适配* 第三部设置适配器*/ArrayList<Sms> queryAllSms = queryAllSms();ListAdapter listAdapter = new MyAdapter(queryAllSms);mListView.setAdapter(listAdapter);}private ArrayList<Sms> queryAllSms() {// TODO Auto-generated method stubUri uri = Uri.parse(remoteUri);ArrayList<Sms> smsList = new ArrayList<Sms>();Cursor dataCursor = contentResolver.query(uri, null, null, null, null);while (dataCursor !=null && dataCursor.getCount()>0 && dataCursor.moveToNext()) {String age = dataCursor.getString(dataCursor.getColumnIndex("age"));String name = dataCursor.getString(dataCursor.getColumnIndex("name"));Sms sms = new Sms(name, age);smsList.add(sms);}return smsList;}ListViewManger(Context mContext,ContentResolver contentResolver,ListView mListView){super();this.mContext = mContext;this.contentResolver = contentResolver;this.mListView = mListView;}class MyAdapter extends BaseAdapter{ArrayList<Sms> smsList = null;public MyAdapter(ArrayList<Sms> queryAllSms) {smsList = queryAllSms;}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn smsList.size();}@Overridepublic Object getItem(int position) {// TODO Auto-generated method stubreturn smsList.get(position);}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {View view = View.inflate(mContext, R.layout.item, null);Sms sms = smsList.get(position);TextView age = (TextView) view.findViewById(R.id.age);TextView name = (TextView) view.findViewById(R.id.name);age.setText(sms.getAge());name.setText(sms.getName());return view;}}
}
最后看MainActivity主界面代码
package com.example.myproxydemo;import android.os.Bundle;
import android.app.Activity;
import android.content.ContentResolver;
import android.view.Menu;
import android.widget.ListView;
/*** 我去买车--我有一个行为就是买* 代理商:就是说4s店面,他验证你的 身份,验证通过,就允许你买车* 要求:10万块,* @author wyf**/
public class MainActivity extends Activity {ContentResolver contentResolver;ListView mListView;private ListViewManger listViewManger;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mListView = (ListView) findViewById(R.id.mListView);contentResolver = getContentResolver();listViewManger = new ListViewManger(this,contentResolver,mListView);MyProxy myProxy = new MyProxy(listViewManger);myProxy.queryData();}}
另外listview的item需要一个封装对象
package com.example.myproxydemo;public class Sms {private String name ;private String age ;public Sms(String name, String age) {super();this.name = name;this.age = age;}public Sms() {super();// TODO Auto-generated constructor stub}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAge() {return age;}public void setAge(String age) {this.age = age;}}
最后主界面只有一个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"tools:context=".MainActivity" ><ListViewandroid:id="@+id/mListView"android:layout_width="fill_parent"android:layout_height="fill_parent" /></RelativeLayout>
item.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"><TextViewandroid:id="@+id/age"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="TextView" /><TextViewandroid:id="@+id/name"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_alignParentTop="true"android:text="TextView" /></RelativeLayout>
这篇关于利用CP查询数据,通过代理模式进行ListView展现数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!