【问题标题】:Alphabet Index in ListView with SimpleCursorAdapter very slow使用 SimpleCursorAdapter 的 ListView 中的字母索引非常慢
【发布时间】:2016-09-01 14:52:58
【问题描述】:

我正在尝试使用 SimpleCursorAdapter 在 ListView 中实现字母索引。 它正在工作,但速度很慢,当我试图上下滚动列表时,手机会被击中。我认为这是由于我缺乏知识而导致的编码方式。所以我需要知道这段代码有什么错误或有什么问题。另外,如果还有其他方法,请告诉我。

这是有上述问题的片段代码。

public class EnFragment extends Fragment {

    private TestAdapter dbHelper;
    private myCursorAdapter dataAdapter;

    public EnFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        dbHelper = new TestAdapter(getContext());
        dbHelper.createDatabase();
        dbHelper.open();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_en, container, false);
        setListView(view);
        return view;
    }

    private void setListView(View view) {
        Cursor cursor = dbHelper.getAllWord("enDic");

        String[] columns = new String[]{
                "word",
                "definition",
                "_id",
                "favourite"
        };

        int[] to = new int[]{
                R.id.txt_word,
                R.id.txt_def,
                R.id.txt_id
        };

        dataAdapter = new myCursorAdapter(
                getContext(), en_word_row,
                cursor,
                columns,
                to,
                0);

        Button btnSubmitEng = (Button) view.findViewById(R.id.btnSubmitEng);

        final ListView listView = (ListView) view.findViewById(R.id.listView);
        listView.setAdapter(dataAdapter);
        listView.setEmptyView(btnSubmitEng);
        listView.setFastScrollEnabled(true);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Cursor cursor = (Cursor) listView.getItemAtPosition(position);
                final String word = cursor.getString(cursor.getColumnIndexOrThrow("word"));
                Toast.makeText(getContext(), word, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void textSearch(String searchTxt){
        String newStr = searchTxt.replace(" ","");
        dataAdapter.getFilter().filter(newStr);

        dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
            public Cursor runQuery(CharSequence constraint) {
                return dbHelper.getWordByName("enDic",constraint.toString());
            }
        });
    }

    private class myCursorAdapter extends SimpleCursorAdapter implements SectionIndexer {

        private final AlphabetIndexer mAlphabetIndexer;

        public myCursorAdapter(Context context, int layout, 
                               Cursor c, String[] from, int[] to, int flags) {
            super(context, layout, c, from, to, flags);
            mAlphabetIndexer = new AlphabetIndexer(c, 1, "අBCDEFGHIJKLMNOPQRSTUVWXYZ");
        }

        public View newView(Context _context, Cursor _cursor, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            return inflater.inflate(en_word_row, parent, false);
        }

        @Override
        public void bindView(View view, Context context, final Cursor cursor) {
            super.bindView(view, context, cursor);

            final ImageButton imgFav = (ImageButton) view.findViewById(R.id.img_fav);
            final String _id = cursor.getString(cursor.getColumnIndex("_id"));
            final Integer fav = Integer
                    .valueOf(cursor.getString(cursor.getColumnIndex("favourite")));

            if (fav == 1)
                imgFav.setImageResource(R.drawable.fav_on);
            else
                imgFav.setImageResource(R.drawable.fav_off);

            imgFav.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dbHelper.isFavourite("enDic", _id)){
                        imgFav.setImageResource(R.drawable.fav_off);
                        dbHelper.favUpdate("enDic", _id,0);
                    }
                    else{
                        imgFav.setImageResource(R.drawable.fav_on);
                        dbHelper.favUpdate("enDic", _id,1);
                    }
                }
            });
        }

        @Override
        public Object[] getSections() {
            return mAlphabetIndexer.getSections();
        }

        @Override
        public int getPositionForSection(int sectionIndex) {
            return mAlphabetIndexer.getPositionForSection(sectionIndex);
        }

        @Override
        public int getSectionForPosition(int position) {
            return mAlphabetIndexer.getSectionForPosition(position);
        }
    }
}

fragment_en.xml(上述片段的布局)

<LinearLayout 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="com.sldroid.mecdic_v21.fragment.EnFragment"
    android:orientation="vertical">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@android:color/transparent"
        android:listSelector="@android:color/transparent"
        android:scrollbarStyle="outsideOverlay"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Submit new word"
        android:layout_marginTop="55dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:id="@+id/btnSubmitEng"/>

</LinearLayout>

zh_word_row.xml

<LinearLayout
    android:id="@+id/cardView"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:descendantFocusability="blocksDescendants">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:baselineAligned="false"
        android:paddingLeft="20dp"
        android:paddingRight="20dp">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_weight="3"
            android:paddingTop="10dp"
            android:paddingBottom="10dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="25dp"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/txt_word"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Word"
                    android:textSize="18dp"
                    android:textColor="#424242"/>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/txt_def"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="definition"
                    android:textSize="10dp"
                    android:paddingTop="5dp"
                    android:paddingLeft="10dp"
                    android:textColor="#FF757575"
                    android:lines="1"/>

            </LinearLayout>

            <TextView
                android:id="@+id/txt_id"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:visibility="invisible"/>

        </LinearLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_weight="0.5">

            <ImageButton
                android:id="@+id/img_fav"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/fav_off"
                android:scaleType="centerInside"
                android:layout_gravity="center"
                android:layout_centerVertical="true"
                android:layout_centerHorizontal="true"
                style="@style/Base.Widget.AppCompat.Button.Borderless"/>

        </RelativeLayout>
    </LinearLayout>
</LinearLayout>

TestAdapter的方法

public Cursor getAllWord(String table)
{
    Cursor mCursor = mDb.query(table, new String[] {"_id","word","definition","favourite"},
            null, null, null,null, " word COLLATE NOCASE");

    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

public Cursor getWordByName(String table, String inputText) throws SQLException {
    Cursor mCursor = null;
    if (inputText == null  ||  inputText.length () == 0)  {
        mCursor = mDb.query(table, new String[] {"_id","word","definition","favourite"},
                null, null, null,null, " word COLLATE NOCASE");

    }
    else {
        mCursor = mDb.query(true, table, new String[] {"_id","word","definition","favourite"},
                "word" + " like '" + inputText + "%'", null,
                null, null, " word COLLATE NOCASE",null);
    }
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

【问题讨论】:

  • 您正在主线程中完成所有工作,您应该使用异步任务进行数据库调用。 developer.android.com/reference/android/os/AsyncTask.html
  • @AgustinSivoplás 我已经将 AsyncTask 用于 Internet 服务。但我不知道 AsyncTask 如何用于数据库调用。所以请你提供一些例子。

标签: android listview simplecursoradapter


【解决方案1】:

GetAllWord 和 getWordByName 应该在 doInBackground 方法中调用,并且在 postExecute 中你应该更新你的适配器。

private class GetAllWord extends AsyncTask<Object, Object, Cursor> {

    @Override
    protected Cursor doInBackground(Object... params) {
        return GetAllWord("your text");
    }

    @Override
    protected void onPostExecute(Cursor result) {
        if (result != null) {
            //update the adapter with the result
        }
    }
}

【讨论】:

  • 我创建了 GetAllWord AsyncTask。但我不知道我在哪里以及如何使用“new GetAllWord().excute();”命令..你能帮帮我吗?
  • 是的,您必须将“您的文本”作为参数传递。当你想执行时调用,例如在按钮的 OnClickListener 中。
  • 在我的片段中,我创建了 Cursor 变量和 dbHelper.getAllWord("enDic");分配给以前创建的光标,然后我创建了 myCursorAdapter 对象,它使用了光标变量。我的问题是我如何将 AsyncTask 用于 myCursorAdapter ?
  • 在 onCreateView 和 onPostExecute 方法中调用异步任务,用结果更新 myCursorAdapter。
  • 我将 myCursorAdapter 设置为 AsyncTask 的结果变量类型,然后在 doInBackground 方法中创建 myCursorAdapter 对象并返回适配器。之后我使用了“listView.setAdapter(result);” onPostExecute 方法中的代码。这是正确的吗?它可以工作,但 listView 在应用程序加载后有更多时间更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 2016-11-10
  • 1970-01-01
  • 2019-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多