在上一节,主要实现了按规则拦截电话,并将拦截信息存入数据库,这里就将数据中的拦截记录取出并显示在界面中以及点击清空按钮就可将全部的拦信息删除,如图所示:
主要思路:
1. 从数据库中取出数据,将其添充在adapter中
2. 为ListView绑定adapter
3. 为清空按钮添加监听器,实现清空数据库的表的功能。
这里用的是adapter是SimpleCursorAdapter,专门操作数据库的adapter,简单易实现,代码如下:
package com.example.callmanager;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class CallInfo extends Activity {
private Button btn_delete;
private ListView lv_show_callInfo;
private SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_callinfo);
btn_delete = (Button)findViewById(R.id.btn_delete_callInfo);
lv_show_callInfo = (ListView)findViewById(R.id.lv_show_callInfo);
btn_delete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
create_db();
delete_db();
showBlackList();
db.close();
}
});
create_db();
showBlackList();
db.close();
}
//打开数据库
public void create_db(){
//创建或打开数据库
db = SQLiteDatabase.openOrCreateDatabase(CallInfo.this.getFilesDir().toString()+"/list.db3", null);
//db.execSQL("DROP TABLE IF EXISTS blackList");
if(db == null){
Toast.makeText(CallInfo.this,"数据库创建不成功",Toast.LENGTH_LONG).show();
}
}
//删除
public void delete_db(){
db.execSQL("delete from callInfo;");
}
//从数据库中取出数据,并显示在ListView中
public void showBlackList(){
Cursor cursor = db.rawQuery("select * from callInfo",null);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(CallInfo.this,
R.layout.callinfo_item, cursor,
new String[]{"_id","name","number","callTimes"},
new int[]{R.id.tv_id,R.id.tv_name,R.id.tv_number,R.id.tv_time});
lv_show_callInfo.setAdapter(adapter);
}
}