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)的更多相关文章

  1. [android] 采用layoutInflater打气筒创建一个view对象

    上一节知道了ListView的工作原理,数据也展示出来了,但是TextView显示的非常难看,如果想美化一下,就先创建好一个布局出来,这个布局采用了两层LinearLayout嵌套,外层的水平方向,内 ...

  2. Android 采用Layout Inflater创建一个View对象

    接着上文<Android ListViewview入门>,本文使用android的Inflater来实现 在layouyt文件夹中新建一个list_item.xml的文件,添加如下代码: ...

  3. [android] 插入一条记录到系统短信应用里

    谷歌市场上有这些应用,模拟短信,原理就是把数据插入到短信应用的数据库里 获取ContentResolver对象,通过getContentResolver()方法 调用resolver对象的insert ...

  4. 无废话Android之activity的生命周期、activity的启动模式、activity横竖屏切换的生命周期、开启新的activity获取他的返回值、利用广播实现ip拨号、短信接收广播、短信监听器(6)

    1.activity的生命周期 这七个方法定义了Activity的完整生命周期.实现这些方法可以帮助我们监视其中的三个嵌套生命周期循环: (1)Activity的完整生命周期 自第一次调用onCrea ...

  5. AX 插入一条记录提示表记录已经存在,但是该记录实际上是不存在的。

    做测试的时候遇到一个情况"AX 插入一条记录提示表记录已经存在,但是该记录实际上是不存在的." 检查到该表(TABLE_ABC)所有的key都是AllowDuplicate的, 继 ...

  6. 一次插入多条记录 [mysql]

    调用多次INSERT语句不就可以插入多条记录了吗?但使用这种方法要增加服务器的负荷,因为,执行每一次SQL服务器都要同样对SQL进行分析.优化等操作.幸好MySQL提供了另一种解决方案,就是使用一条I ...

  7. sql 中实现往表中插入一条记录并返回当前记录的ID

    写一条存储过程,实现往User中插入一条记录并返回当前UserId(自增长id) --推荐写法 if(Exists(select * from sys.objects where name=N'Usp ...

  8. SQLServer 触发器 同时插入多条记录有关问题

    由于 SQL Server 的触发器, 没有 FOR EACH ROW (ORACL中有)的选项, 有时候不正确的使用 inserted 与deleted 可能会有点麻烦. 下面来一个简单的例子 -- ...

  9. ACCESS-delphi向中插入一条记录报错,但ACCESS不会

    问题:在DELPHI中向ACCESS中插入一条记录时,提示“插入错误”,但是取出SQL直接放在ACCESS中插入成功?答:原因是插入语句中的字段名是DELPHI的内部标示符.

随机推荐

  1. javascript中数组concat()join()split()

    concat() 方法用于连接两个或多个数组. 该方法不会改变现有的数组,而仅仅会返回被连接数组的一个副本. 所以 <script type="text/javascript" ...

  2. linux中chmod更改文件权限命令

    1. 命令格式: chmod [-cfvR] [--help] [--version] mode file 2. 命令功能: 用于改变文件或目录的访问权限,用它控制文件或目录的访问权限. 3. 命令参 ...

  3. OpenCv高斯,中值,均值,双边滤波

    #include "cv.h" #include "highgui.h" #include <iostream> using namespace s ...

  4. Ngrok搭建服务器

    一.ngrok简介及作用 ngrok 是一款用go语言开发的开源软件,它是一个反向代理,通过在公共的端点和本地运行的 Web 服务器之间建立一个安全的通道.下图简述了ngrok的原理. ngrok 可 ...

  5. 思科 vlan 相关操作

    添加或者修改VLAN Switch(config)# vlan vlan-id Switch(config-vlan)# name vlan-name 删除VLAN Switch(config)# n ...

  6. Codeforces 710 D. Two Arithmetic Progressions

    Description \(x=a_1k+b_1=a_2l+b_2,L\leqslant x \leqslant R\) 求满足这样条件的 \(x\) 的个数. Sol 扩展欧几里得+中国剩余定理. ...

  7. 7 HandlerSet 处理程序链表类——Live555源码阅读(一)基本组件类

    这是Live555源码阅读的第一部分,包括了时间类,延时队列类,处理程序描述类,哈希表类这四个大类. 本文由乌合之众 lym瞎编,欢迎转载 my.oschina.net/oloroso Handler ...

  8. ccs3中icon转换为字体的方法

    小图标转换为字体有几大优点 文件小,一般50k以内 避免了加载多个icons,减少了加载次数,有利于页面优化. 兼容性很好,可以随便放大缩小,都能正常显示. 维护起来也很简单,只用找到这个字体文件(比 ...

  9. SQL Server被锁的表以及解锁

    select   request_session_id   spid,OBJECT_NAME(resource_associated_entity_id) tableName   from   sys ...

  10. poj 2153

    题意:题目还是很简单的,就是求Li Ming 在班上的排名,而且成绩是相加的. 思路:用map就行.不然好像用qsort+二分也可以,不过我在那里碰到了一些状况,然后就没用这种方法了,简单的map就可 ...