无废话Android之listview入门,自定义的数据适配器、采用layoutInflater打气筒创建一个view对象、常用数据适配器ArrayAdapter、SimpleAdapter、使用ContentProvider(内容提供者)共享数据、短信的备份、插入一条记录到系统短信应用(3)
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] 采用layoutInflater打气筒创建一个view对象
上一节知道了ListView的工作原理,数据也展示出来了,但是TextView显示的非常难看,如果想美化一下,就先创建好一个布局出来,这个布局采用了两层LinearLayout嵌套,外层的水平方向,内 ...
- Android 采用Layout Inflater创建一个View对象
接着上文<Android ListViewview入门>,本文使用android的Inflater来实现 在layouyt文件夹中新建一个list_item.xml的文件,添加如下代码: ...
- [android] 插入一条记录到系统短信应用里
谷歌市场上有这些应用,模拟短信,原理就是把数据插入到短信应用的数据库里 获取ContentResolver对象,通过getContentResolver()方法 调用resolver对象的insert ...
- 无废话Android之activity的生命周期、activity的启动模式、activity横竖屏切换的生命周期、开启新的activity获取他的返回值、利用广播实现ip拨号、短信接收广播、短信监听器(6)
1.activity的生命周期 这七个方法定义了Activity的完整生命周期.实现这些方法可以帮助我们监视其中的三个嵌套生命周期循环: (1)Activity的完整生命周期 自第一次调用onCrea ...
- AX 插入一条记录提示表记录已经存在,但是该记录实际上是不存在的。
做测试的时候遇到一个情况"AX 插入一条记录提示表记录已经存在,但是该记录实际上是不存在的." 检查到该表(TABLE_ABC)所有的key都是AllowDuplicate的, 继 ...
- 一次插入多条记录 [mysql]
调用多次INSERT语句不就可以插入多条记录了吗?但使用这种方法要增加服务器的负荷,因为,执行每一次SQL服务器都要同样对SQL进行分析.优化等操作.幸好MySQL提供了另一种解决方案,就是使用一条I ...
- sql 中实现往表中插入一条记录并返回当前记录的ID
写一条存储过程,实现往User中插入一条记录并返回当前UserId(自增长id) --推荐写法 if(Exists(select * from sys.objects where name=N'Usp ...
- SQLServer 触发器 同时插入多条记录有关问题
由于 SQL Server 的触发器, 没有 FOR EACH ROW (ORACL中有)的选项, 有时候不正确的使用 inserted 与deleted 可能会有点麻烦. 下面来一个简单的例子 -- ...
- ACCESS-delphi向中插入一条记录报错,但ACCESS不会
问题:在DELPHI中向ACCESS中插入一条记录时,提示“插入错误”,但是取出SQL直接放在ACCESS中插入成功?答:原因是插入语句中的字段名是DELPHI的内部标示符.
随机推荐
- HDU 3549 网络最大流再试
http://acm.hdu.edu.cn/showproblem.php?pid=3549 同样的网络最大流 T了好几次原因是用了cout,改成printf就A了 还有HDU oj的编译器也不支持以 ...
- 深入mysql "on duplicate key update" 语法的分析
如果在INSERT语句末尾指定了on duplicate key update,并且插入行后会导致在一个UNIQUE索引或PRIMARY KEY中出现重复值,则在出现重复值的行执行UPDATE:如果不 ...
- apache poi 生成excel
ExcelBuilder.Java package com.coracle.yk.xmanager.util.poi; import com.coracle.yk.xframework.util.Bl ...
- mysql 日志文件mysql-bin文件清除方法,和mysql-bin相关文件的配置
默认情况下mysql会一直保留mysql-bin文件,这样到一定时候,磁盘可能会被撑满,这时候是否可以删除这些文件呢,是否可以安全删除,是个问题. 首先要说明一下,这些文件都是mysql的日志文件,如 ...
- curl api create domain
from: https://adam.younglogic.com/2013/09/keystone-v3-api-examples/ http://docs.openstack.org/develo ...
- bitnami-redmine 安装与插件使用
bitnami-redmine 公司要进行敏捷开发管理,选择Redmine作为管理工具. 而Redmine本身的需要的环境比较麻烦,需要安装mysql,ruby,redmine,apach. Bitn ...
- centos6.5 mysql开机启动
可参考:centos6.5 nginx开机启动 /etc/init.d/下添加mysqld文件,内容如下: #!/bin/sh # Copyright Abandoned TCX DataKonsul ...
- C++实现VPN工具之常用API函数
RAS是Remote Access Service的缩写,意为:远程访问服务,主要用来配置企业的远程用户对企业内部网络访问,包括拨号访问和vpn方式.微软的所有Windows平台中都有RAS客户机,它 ...
- ACM/ICPC 之 模拟 (HNUOJ 13391-换瓶模拟)
题意:汽水瓶有三个部分cap+plastic bottle+ label(瓶盖-瓶身-瓶底),给出数据:n为原瓶数,x,y,z为这三个部分可以用相应的数字换取新瓶子,求最大总瓶数. 模拟(暴力) // ...
- JSP公用COMMON文件
head.jsp: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" ...