我正在尝试使用抽屉菜单创建一个应用程序,其中一个选项是打开带有选项卡的活动 . 在每个片段中我试图显示在数据库上看不到的listview . 我在主线程上有太多工作的问题 . 它被跳过66帧或更多 . 我应该在异步任务中进行此操作?请帮我找一个解决方案我该怎么办?
public class test1 extends Fragment{
private OpenHelper1 dbHelper;
private SimpleCursorAdapter dataAdapter;
public ListView listView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.trening_activity_main, container, false);
dbHelper = new OpenHelper1(this.getActivity());
dbHelper.open();
//Clean all data
dbHelper.deleteAllCountries();
//Add some data
dbHelper.insertSomeCountries();
//Generate ListView from SQLite Database
displayListView(rootView);
return rootView;
}
private void displayListView(View root) {
Cursor cursor = dbHelper.fetchAllCountries();
// The desired columns to be bound
String[] columns = new String[]{
OpenHelper1.KEY_NAME,
OpenHelper1.KEY_KIND
};
// the XML defined views which the data will be bound to
int[] to = new int[]{
R.id.name,
R.id.kind,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
getActivity(), R.layout.trening_activity1,
cursor,
columns,
to,
0);
listView = (ListView) root.findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String countryCode =
cursor.getString(cursor.getColumnIndexOrThrow("name"));
Toast.makeText(getActivity().getApplicationContext(),
countryCode, Toast.LENGTH_SHORT).show();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getActivity().getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("cwiczenie ", countryCode);
startActivity(i);
}
});
EditText myFilter = (EditText) root.findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchCountriesByName(constraint.toString());
}
});}
}
2 回答
您不能在主线程(或UI线程)中进行数据库操作 . 您必须使用AsyncTask在另一个线程中执行此操作 . 所以你自己已经有了答案 .
你应该使用
Loader
,确切地说CursorLoader
. 这将在后台线程中从数据库中获取数据 . 回调方法onLoadFinished
将提供光标,然后您可以使用该光标创建/更新SimpleCursorAdapter
.看看example on the Developer site