无废话Android之listview入门,自定义的数据适配器、采用layoutInflater打气筒创建一个view对象、常用数据适配器ArrayAdapter、SimpleAdapter、使用ContentProvider(内容提供者)共享数据、短信的备份、插入一条记录到系统短信应用(3)

2023-09-02,,

1.listview入门,自定义的数据适配器
<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=".ListViewActivity" > <ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</RelativeLayout> public class ListViewActivity extends Activity { private ListView lv;
public String tag = "ListViewActivity"; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
lv = (ListView) findViewById(R.id.lv);
lv.setAdapter(new MyAdapter());
} /**
* 自定义的数据适配器
*
* @author Administrator
*
*/
private class MyAdapter extends BaseAdapter { /**
* 控制listview里面有多个条目.
*/
@Override
public int getCount() {
return 15;
} /**
* 返回每个位置对应的view对象
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// 这个方法被调用了多少次?
Log.i(tag, "POSITION:" + position);
TextView tv = new TextView(ListViewActivity.this);
tv.setTextSize(30);
tv.setTextColor(Color.RED);
tv.setText("我是第" + position + "个条目");
return tv;
} @Override
public Object getItem(int position) {
return null;
} @Override
public long getItemId(int position) {
return 0;
} } } 2.采用layoutInflater打气筒创建一个view对象
在上面的基础上添加list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" > <TextView
android:id="@+id/tv_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000000" /> <TextView
android:id="@+id/tv_number"
android:layout_width="match_parent"
android:layout_height="wrap_content" /> </LinearLayout> /**
* 返回每个位置对应的view对象
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// 这个方法被调用了多少次?
Log.i(tag, "POSITION:" + position);
View view = View.inflate(getApplicationContext(),
R.layout.list_item, null);
TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
TextView tv_number = (TextView) view.findViewById(R.id.tv_number);
tv_name.setText("name:"+position);
tv_number.setText(position+"");
return view;
} .常用数据适配器ArrayAdapter
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
lv = (ListView) findViewById(R.id.lv);
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
R.id.tv_name, new String[] { "aaaa", "bbbb", "cccc", "ddddd" }));
} .常用数据适配器SimpleAdapter
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
lv = (ListView) findViewById(R.id.lv); List<Map<String, String>> data = new ArrayList<Map<String, String>>(); Map<String, String> item1 = new HashMap<String, String>();
item1.put("name", "zhangsna");
item1.put("number", "124245"); Map<String, String> item2 = new HashMap<String, String>();
item2.put("name", "lisi");
item2.put("number", "4545"); data.add(item1);
data.add(item2); lv.setAdapter(new SimpleAdapter(this, data, R.layout.list_item,
new String[] { "name", "number" }, new int[] { R.id.tv_name,
R.id.tv_number })); } .使用ContentProvider(内容提供者)共享数据
ContentProvider 在android中的作用是对外共享数据,也就是说你可以通过ContentProvider把应用中的数据共享给其他应用访问,其他应用可以通过ContentProvider 对你应用中的数据进行添删改查。
如果采用文件操作模式对外共享数据,数据的访问方式会因数据存储的方式而不同,导致数据的访问方式无法统一
使用ContentProvider对外共享数据的好处是统一了数据的访问方式。
定义一个类继承ContentProvider类
package com.itheima.contentprovider; 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 com.example.demo1.db.PersonSQLiteOpenHelper; public class PersonProvider extends ContentProvider { // 定义一个uri匹配器,用于匹配uri,如果匹配不成功返回-1
private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
private static final int INSERT = 1;
private static final int DELETE = 2;
private static final int UPDATE = 3;
private static final int QUERY = 4;
private static final int QUERYONE = 5;
private static final Uri URI = Uri.parse("content://person.db"); private PersonSQLiteOpenHelper helper; static {
// 添加一组匹配规则
// authority: the authority to match
// path: the path to match. * may be used as a wild card for any text,
// and # may be used as a wild card for numbers.
// code: the code that is returned when a URI is matched against the
// given components. Must be positive.
matcher.addURI("com.itheima.contentprovider.personprovider", "insert",
INSERT);
matcher.addURI("com.itheima.contentprovider.personprovider", "delete",
DELETE);
matcher.addURI("com.itheima.contentprovider.personprovider", "update",
UPDATE);
matcher.addURI("com.itheima.contentprovider.personprovider", "query",
QUERY);
matcher.addURI("com.itheima.contentprovider.personprovider", "query/#",
QUERYONE);
} @Override
public boolean onCreate() {
this.helper = new PersonSQLiteOpenHelper(getContext());
return false;
} @Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
if (matcher.match(uri) == QUERY) {
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.query("person", projection, selection,
selectionArgs, null, null, sortOrder);
// 注意这里的db和cursor不能关闭
return cursor;
} else if (matcher.match(uri) == QUERYONE) {
SQLiteDatabase db = helper.getReadableDatabase();
long id = ContentUris.parseId(uri);
Cursor cursor = db.query("person", projection, "id=?",
new String[] { id + "" }, null, null, sortOrder);
// 注意这里的db和cursor不能关闭
return cursor;
} else {
throw new IllegalArgumentException("非法uri");
}
} @Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
if (matcher.match(uri) == DELETE) {
SQLiteDatabase db = helper.getWritableDatabase();
// 注册内容观测者
getContext().getContentResolver().notifyChange(URI, null);
return db.delete("person", selection, selectionArgs);
} else {
throw new IllegalArgumentException("非法uri");
}
} @Override
public Uri insert(Uri uri, ContentValues values) {
if (matcher.match(uri) == INSERT) {
SQLiteDatabase db = helper.getWritableDatabase();
long id = db.insert("person", null, values);
getContext().getContentResolver().notifyChange(URI, null);
// 返回指定的Uri路劲对象
// content://cn.itcast.provider.custom.usersprovider/users/1
return ContentUris.withAppendedId(uri, id); } else {
throw new IllegalArgumentException("非法uri");
}
} @Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
if (matcher.match(uri) == UPDATE) {
SQLiteDatabase db = helper.getWritableDatabase();
getContext().getContentResolver().notifyChange(URI, null);
return db.update("person", values, selection, selectionArgs);
} else {
throw new IllegalArgumentException("非法uri");
}
} /**
* Implement this to handle requests for the MIME type of the data at the
* given URI. The returned MIME type should start with
* vnd.android.cursor.item for a single record, or vnd.android.cursor.dir/
* for multiple items. This method can be called from multiple threads, as
* described in Processes and Threads.
*/
@Override
public String getType(Uri uri) {
if (matcher.match(uri) == QUERY) {
return "vnd.android.cursor.dir/person";
} else if (matcher.match(uri) == QUERYONE) {
return "vnd.android.cursor.item/person";
} else {
return "";
}
} } 定义一个类继承SQLiteOpenHelper类
package com.example.demo1.db; import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper; public class PersonSQLiteOpenHelper extends SQLiteOpenHelper {
private static final String DBFILENAME = "person.db";
private static int db_version = 1; public PersonSQLiteOpenHelper(Context context) {
super(context, DBFILENAME, null, db_version);
} /**
* 当数据库第一次创建时调用
*/
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table person(id integer primary key autoincrement,name varchar(20),number varchar(20))";
db.execSQL(sql);
} /**
* 当数据库的版本号发生增加的时候调用
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println("数据库更改!");
String sql = "alter table person add account varchar(20)";
db.execSQL(sql);
} } 清单文件中注册内容提供者
<provider android:name="com.itheima.contentprovider.PersonProvider"
android:authorities="com.itheima.contentprovider.personprovider"
></provider> 第三方软件
public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} public void getAll(View view) {
ContentResolver resolver = this.getContentResolver();
Uri uri = Uri
.parse("content://com.itheima.contentprovider.personprovider/query");
Cursor cursor = resolver.query(uri, null, null, null, null);
StringBuffer sb = new StringBuffer();
while (cursor.moveToNext()) {
sb.append(cursor.getString(cursor.getColumnIndex("name")) + " -- "
+ cursor.getString(cursor.getColumnIndex("number")));
sb.append("\n");
}
TextView tv_info = (TextView) this.findViewById(R.id.tv_info);
tv_info.setText(sb.toString());
cursor.close();
} public void getOne(View view) {
ContentResolver resolver = this.getContentResolver();
// Uri uri = Uri
// .parse("content://com.itheima.contentprovider.personprovider/query");
// Cursor cursor = resolver.query(uri, null, "id=?",new String[]{"1"} ,
// null);
Uri uri = Uri.parse("content://com.itheima.contentprovider.personprovider/query/1");
Cursor cursor = resolver.query(uri, null, null, null, null);
StringBuffer sb = new StringBuffer();
if (cursor.moveToFirst()) {
sb.append(cursor.getString(cursor.getColumnIndex("name")) + " -- "
+ cursor.getString(cursor.getColumnIndex("number")));
sb.append("\n");
}
TextView tv_info = (TextView) this.findViewById(R.id.tv_info);
tv_info.setText(sb.toString());
cursor.close();
} public void insert(View view) {
ContentResolver resolver = this.getContentResolver();
Uri uri = Uri.parse("content://com.itheima.contentprovider.personprovider/insert");
ContentValues values = new ContentValues();
values.put("name", "reality");
values.put("number", "567");
Uri result = resolver.insert(uri, values);
System.out.println("result = " + result);
} public void update(View view) {
ContentResolver resolver = this.getContentResolver();
Uri uri = Uri
.parse("content://com.itheima.contentprovider.personprovider/update");
ContentValues values = new ContentValues();
values.put("name", "dog");
values.put("number", "110");
int result = resolver.update(uri, values, "id=?", new String[] { "1" });
System.out.println("result = " + result);
} public void delete(View view) {
ContentResolver resolver = this.getContentResolver();
Uri uri = Uri
.parse("content://com.itheima.contentprovider.personprovider/delete");
int result = resolver.delete(uri, "id=?", new String[] { "3" });
System.out.println("result = " + result);
} } .短信的备份
public class BackupsmsActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_backupsms);
} public void backupSMS(View view) {
Uri uri = Uri.parse("content://sms");
ContentResolver resolver = this.getContentResolver();
Cursor cursor = resolver.query(uri, new String[] { "date", "body",
"address", "type" }, null, null, null);
ArrayList<SmsInfo> infos = new ArrayList<SmsInfo>();
while (cursor.moveToNext()) {
long date = cursor.getLong(0);
String body = cursor.getString(1);
String address = cursor.getString(2);
int type = cursor.getInt(3);
SmsInfo smsInfo = new SmsInfo(date, body, address, type);
infos.add(smsInfo);
}
SmsUtil.save(this, infos);
}
} public class SmsUtil {
public static void save(Context context, ArrayList<SmsInfo> infos) {
XmlSerializer xmlSerializer = Xml.newSerializer();
File file = new File(Environment.getExternalStorageDirectory(),
"sms_bak.xml");//mnt/sdcard/sms_bak.xml
try {
FileOutputStream fos = new FileOutputStream(file);
xmlSerializer.setOutput(fos, "utf-8");
xmlSerializer.startDocument("utf-8", true); xmlSerializer.startTag(null, "smss"); for (SmsInfo info : infos) {
xmlSerializer.startTag(null, "sms");
xmlSerializer.attribute(null, "type", info.getType() + ""); xmlSerializer.startTag(null, "date");
xmlSerializer.text(info.getDate() + "");
xmlSerializer.endTag(null, "date"); xmlSerializer.startTag(null, "address");
xmlSerializer.text(info.getAddress());
xmlSerializer.endTag(null, "address"); xmlSerializer.startTag(null, "body");
xmlSerializer.text(info.getBody());
xmlSerializer.endTag(null, "body"); xmlSerializer.endTag(null, "sms");
}
xmlSerializer.endTag(null, "smss"); xmlSerializer.endDocument();
fos.close();
Toast.makeText(context, "保存成功", 0).show(); } catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "保存失败", 0).show();
} }
} public class SmsInfo {
private int id;
private long date;
private String body;
private String address;
private int type; public SmsInfo() {
super();
// TODO Auto-generated constructor stub
} public SmsInfo(int id, long date, String body, String address) {
super();
this.id = id;
this.date = date;
this.body = body;
this.address = address;
} public SmsInfo(long date, String body, String address, int type) {
super();
this.date = date;
this.body = body;
this.address = address;
this.type = type;
} public int getType() {
return type;
} public void setType(int type) {
this.type = type;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public long getDate() {
return date;
} public void setDate(long date) {
this.date = date;
} public String getBody() {
return body;
} public void setBody(String body) {
this.body = body;
} public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} } .插入一条记录到系统短信应用
public class InsertsmsActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insertsms);
new Thread() {
public void run() {
try {
Thread.sleep(10000);
Uri uri = Uri.parse("content://sms");
ContentResolver resolver = getContentResolver();
ContentValues values = new ContentValues();
values.put("address", "10086");
values.put("type", 1);
values.put("date", System.currentTimeMillis());
values.put("body", "您的余额还有100,000,000元!");
resolver.insert(uri, values);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }.start();
}
} <uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />

无废话Android之listview入门,自定义的数据适配器、采用layoutInflater打气筒创建一个view对象、常用数据适配器ArrayAdapter、SimpleAdapter、使用ContentProvider(内容提供者)共享数据、短信的备份、插入一条记录到系统短信应用(3)的相关教程结束。

《无废话Android之listview入门,自定义的数据适配器、采用layoutInflater打气筒创建一个view对象、常用数据适配器ArrayAdapter、SimpleAdapter、使用ContentProvider(内容提供者)共享数据、短信的备份、插入一条记录到系统短信应用(3).doc》

下载本文的Word格式文档,以方便收藏与打印。