嘗試這個代碼,
MainActivity.java:
public class MainActivity extends Activity {
private ArrayList<String> titles;
private ArrayList<String> urls;
private ArrayList<Bitmap> bitmaps;
private ContentResolver cr;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createLists();
}
protected void onResume(){
super.onResume();
getBH();
showHistoryBookmarks();
}
public void createLists(){
titles=new ArrayList<String>();
urls=new ArrayList<String>();
bitmaps=new ArrayList<Bitmap>();
}
public void getBH(){
Bitmap icon;
cr=getContentResolver();
String order= Browser.BookmarkColumns.DATE+" DESC";
String[] projection={Browser.BookmarkColumns.TITLE,Browser.BookmarkColumns.URL,Browser.BookmarkColumns.FAVICON};
//String selection=projection[0]+"=?";
//String args[]={"Google"};
Cursor rows=cr.query(Browser.BOOKMARKS_URI,projection, null,null,order);
if(rows.getCount()>0){
while(rows.moveToNext()) {
//read title
String title=rows.getString(rows.getColumnIndex(projection[0]));
//read url
String url=rows.getString(rows.getColumnIndex(projection[1]));
//read icon
byte[] bicon=rows.getBlob(rows.getColumnIndex(projection[2]));
if(bicon!=null){
//convert blob image data to Bitmap
icon=BitmapFactory.decodeByteArray(bicon,0,bicon.length);
}
else{
//default icon for history and bookmarks that do not icons
icon=BitmapFactory.decodeResource(getResources(),R.drawable.star2);
}
//add to lists
addToList(title,url,icon);
}
//close the cursor
rows.close();
}
}
public void getBrowserHist() {
Cursor mCur = managedQuery(Browser.BOOKMARKS_URI,
Browser.HISTORY_PROJECTION, null, null, null);
mCur.moveToFirst();
if (mCur.moveToFirst() && mCur.getCount() > 0) {
while (mCur.isAfterLast() == false) {
Log.v("titleIdx", mCur
.getString(Browser.HISTORY_PROJECTION_TITLE_INDEX));
Log.v("urlIdx", mCur
.getString(Browser.HISTORY_PROJECTION_URL_INDEX));
mCur.moveToNext();
}
}
}
public void addToList(String title,String url, Bitmap bitmap){
titles.add(title);
urls.add(url);
bitmaps.add(bitmap);
}
public void showHistoryBookmarks(){
ListView l=(ListView) findViewById(R.id.hb_list);
if(l!=null){
if(titles.size()>0){
ListAdapterModel aa=new ListAdapterModel(this,R.layout.listlayout,R.id.hbtitle,titles,urls,bitmaps);
l.setAdapter(aa);
}
else{
Toast.makeText(this, "This is no bookmark or history.", Toast.LENGTH_SHORT).show();
}
}
}
public void cleanHB(){
if(Browser.canClearHistory(cr)){
Browser.clearHistory(cr); //clear history data
createLists(); //recreate the lists
onResume(); //update the list
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
if(item.getItemId()==R.id.action_clean)
{
cleanHB();
}
return false;
}
}