public class TabBooklist extends Fragment {
/* <DB> */
//variable use in DB->
int nCount=1;
SQLiteDatabase db;
BookListDBHelper helper;
ListView listview ;
BookListShowAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab_booklist, container, false);
/* (XML) <Book list> */
adapter = new BookListShowAdapter(getContext()) ;
listview = (ListView) rootView.findViewById (R.id.lv_book_list);
listview.setAdapter(adapter);
adapter.addItem(ContextCompat.getDrawable(getActivity(), R.drawable.ic_empty),
"name1", "author1", 110, 1200) ; //work
adapter.addItem(ContextCompat.getDrawable(getActivity(), R.drawable.ic_empty),
"name21", "author21", 210, 1003) ; //work
adapter.addItem(ContextCompat.getDrawable(getActivity(), R.drawable.ic_empty),
"name31", "author31", 101, 1020) ; //work
//refresh
Button btn_ref = (Button) rootView.findViewById(R.id.btn_refresh);
btn_ref.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) { //click to add
select();
}
});
return rootView;
}
//select
public void select() {
nCount = 1;
db = helper.getReadableDatabase();
Cursor c = db.query("booklist", null, null, null, null, null, null);
while (c.moveToNext()) {
int int_idBook = c.getInt(c.getColumnIndex("id_book"));
int int_idTree = c.getInt(c.getColumnIndex("id_tree"));
String str_title = c.getString(c.getColumnIndex("title"));
String str_author = c.getString(c.getColumnIndex("author"));
String str_imageLink = c.getString(c.getColumnIndex("image_link"));
int n_pageTotal = c.getInt(c.getColumnIndex("page_total"));
//add
adapter.addItem(ContextCompat.getDrawable(getActivity(), R.drawable.ic_empty),
str_title, str_author, 0, n_pageTotal); //not work
adapter.addItem(ContextCompat.getDrawable(getActivity(), R.drawable.ic_empty),
"name31", "author31", 101, 1020) ; //not work
nCount ++;
}
}
}
如果点击刷新按钮,然后将项目添加到列表视图,我想这样做。
adapter.addItem
中的onCreateView function
工作
但在select function
中,adapter.addItem 无法正常工作
(并且没有错误。)
数据在DB中。 (我用日志检查了一下)
为什么adapter.addItem
中的select function
无法正常工作,解决方案是什么?
答案 0 :(得分:1)
原因
adapter.addItem(ContextCompat.getDrawable(getActivity(), R.drawable.ic_empty),
"name1", "author1", 110, 1200) ; //work
adapter.addItem(ContextCompat.getDrawable(getActivity(), R.drawable.ic_empty),
"name21", "author21", 210, 1003) ; //work
adapter.addItem(ContextCompat.getDrawable(getActivity(), R.drawable.ic_empty),
"name31", "author31", 101, 1020) ; //work
在 onCreateView()中工作是因为 onCreateView()在呈现视图之前运行,允许ListView呈现项目。< / p>
但是,在 select()方法中,您要在
因为我不知道您的 BookListShowAdapter.addItem()方法是什么样的,所以我只能假设您没有调用 notifyDataSetChanged()。如果您调用此方法在 BookListShowAdapter.addItem()方法结束时的方法,您的适配器将告诉任何反映您的数据的视图以刷新自身(包括渲染)。