无废话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;
}

3.常用数据适配器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" }));
}

4.常用数据适配器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 }));

    }

5.使用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);
    }

}

6.短信的备份
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;
    }

}

7.插入一条记录到系统短信应用
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" />
时间: 2024-12-07 01:58:19

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

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

谷歌市场上有这些应用,模拟短信,原理就是把数据插入到短信应用的数据库里 获取ContentResolver对象,通过getContentResolver()方法 调用resolver对象的insert(uri,values)方法,参数:Uri对象,ContentValues对象 调用ContentValues对象的put(key,value)方法,key就是上一节的字段,val值,date是时间戳,调用系统的时间System.currentTimeMillies()方法 使用线程来实现过几秒后再

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

1.activity的生命周期 这七个方法定义了Activity的完整生命周期.实现这些方法可以帮助我们监视其中的三个嵌套生命周期循环: (1)Activity的完整生命周期 自第一次调用onCreate()开始,直到调用onDestory()为止.Activity在onCreate()中设置所有“全局”状态以完成初始化. 而在onDestory()中释放所有系统资源.例如,如果Activity有一个线程在后台运行从网络下载数据,它会在onCreate()创建线程, 而在onDestory()销

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

做测试的时候遇到一个情况"AX 插入一条记录提示表记录已经存在,但是该记录实际上是不存在的." 检查到该表(TABLE_ABC)所有的key都是AllowDuplicate的, 继续检查表属性发现 createdRecIdxIdx设置为Yes, 启用了RecId作为唯一键. 因此推测 应该是该表的recid 的nextvalue 数据不对了. 想办法刷新 recid . 在sql 后台 1. 计算 Table_ABC目前最大的RecId declare @maxRecId int64

插入一条记录并获取自增的id

Connection connection = (Connection) dbcp.getConn(); int affectRows = qr.update(connection, sql,params); BigInteger id = BigInteger.ZERO ; id = qr.query(connection, "SELECT LAST_INSERT_ID()", new ScalarHandler(1)); //获取新增记录的自增主键 这个是通过dbutils来获取的

SQL 一次插入多条记录

本文介绍如何快速插入多条数据到数据表中,以满足sql语句学习或项目测试的需要. 本文非原创,是对移步原文的重新整理. 如有以下表格,如图: 1,原始添加记录的方式,sql语句如下: 1 insert into City(Code,CityCName) values('TS','唐山'); 2,使用Union执行插如操作,sql语句如下: 1 insert into City(Code,CityCName) 2 select 'ZZ','郑州' 3 union 4 select 'HD','邯郸'

18.一次性插入多条记录

use MySchool --一次性插入多条记录-- insert into grade values(4,'工具') insert into Grade (GradeName) select 'aaa' union all --只有全部写了union all才不会去除重复记录 select 'aaa' union all select 'aaa' union all select 'aaa' union all select 'bb' union all select 'bb' --union

C# access数据库软件使用事务插入多条记录

C# access数据库软件使用事务插入多条记录 protected void Button1_Click(object sender, EventArgs e) { /*=============测试通过===============*/ OleDbConnection con = new OleDbConnection(“Provider=Microsoft.Jet.OleDb.4.0;Da ta Source=C:/Inetpub/wwwroot/DotNetArticle/App_Dat

一次插入多条记录 [mysql]

调用多次INSERT语句不就可以插入多条记录了吗?但使用这种方法要增加服务器的负荷,因为,执行每一次SQL服务器都要同样对SQL进行分析.优化等操作.幸好MySQL提供了另一种解决方案,就是使用一条INSERT语句来插入多条记录.这并不是标准的SQL语法,因此只能在MySQL中使用. INSERT INTO users(name, age)  VALUES('姚明', 25), ('比尔.盖茨', 50), ('火星人', 600); 上面的INSERT 语句向users表中连续插入了3条记录.

一条insert语句批量插入多条记录 AND 多条件游标更新 变CASE WHEN更新法提高速度

一条insert语句批量插入多条记录 常见的insert语句,向数据库中,一条语句只能插入一条数据: insert into persons (id_p, lastname , firstName, city ) values(204,'haha' , 'deng' , 'shenzhen'); (如上,仅插入了一条记录) 怎样一次insert插入多条记录呢? 使用示例: insert into persons (id_p, lastname , firstName, city ) values