过滤的列表视图未显示正确的数据

时间:2017-01-23 13:16:18

标签: android listview android-sqlite

##这是我的代码。我使用SQLite数据库和json创建了过滤的listview。但是当我搜索数据时,例如,如果名字是Shreya Patil,那么它只显示我的名字shreya的结果而不是她的姓氏。如果我正在键入patil结果是什么。请帮助.. ##

以下是活动类的摘录:

public class DirectoryActivity extends BaseActivity {

    private SQLiteDbAdapter dbHelper;
    private SimpleCursorAdapter dataAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_directory_home_profile);

        dbHelper = new SQLiteDbAdapter(this);

        dbHelper.open();
        //Clean all data
        dbHelper.deleteAllData();
        displayListView();
       getPolicianInfo();


    }

    private void displayListView() {

        Cursor cursor = dbHelper.fetchAllData();
        Log.e("Getting all data", "data");

        // The desired columns to be bound
        String[] columns = new String[] {
                SQLiteDbAdapter.USER_ID,
                SQLiteDbAdapter.POLITICIAN_FIRST_NAME,
                SQLiteDbAdapter.POLITICIAN_DESIGNATION,
                SQLiteDbAdapter.POLITICIAN_CONTACT,
                SQLiteDbAdapter.POLITICIAN_IMAGE_URL,
                SQLiteDbAdapter.POLITICIAN_CITY,
                SQLiteDbAdapter.POLITICIAN_HOUSE,
        };

        // the XML defined views which the data will be bound to
        int[] to = new int[] {
                R.id.directory_item_name_tv_name,
                R.id.directory_item_name_tv_last_name,
               /* R.id.directory_item_name_tv_last_Test,*/
                R.id.directory_item_name_tv_designation,
                R.id.directory_item_name_tv_contact,
                R.id.directory_item_iv_picture,

        };

        // create the adapter using the cursor pointing to the desired data
        //as well as the layout information
        dataAdapter = new SimpleCursorAdapter(
                this, R.layout.list_item_directory_lv, cursor, columns,to, 0);

        ListView listView = (ListView) findViewById(R.id.directory_search_lv);
        listView.setTextFilterEnabled(true);

        // Assign adapter to ListView
        listView.setAdapter(dataAdapter);

        dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
            public Cursor runQuery(CharSequence constraint) {
                return dbHelper.fetchPoliticansByName(constraint.toString());
            }
        });


        EditText myFilter = (EditText) 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());
               DirectoryActivity.this.dataAdapter.getFilter().filter(s);

            }
        });

    }




    private void getPolicianInfo() {

        if (Util.isNetworkAvailable(this)) {
            try {
                API apis = RetrofitClient.getApiClient(Util.DOMAIN_NAME);


                Callback<JsonElement> responseListner = new Callback<JsonElement>() {
                    @Override
                    public void success(JsonElement responseSuccess, Response response) {
                        Log.e("responseSuccess", responseSuccess.toString());

                        if (responseSuccess != null) {

                            Log.e("responseSuccess success", responseSuccess.toString());
                            Log.e("response in success", response.toString());


                            try {
                                JSONObject object = new JSONObject(responseSuccess.toString());


                                {

                                    JSONArray jsonMainNode = object.getJSONArray("posts");
                                    int lengthJsonArr = jsonMainNode.length();

                                    for (int i = 0; i < lengthJsonArr; i++) {
                                        /****** Get Object for each JSON node.***********/
                                        JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);



                                        String user_id = jsonChildNode.getString("id");
                                        String politician_first_name = jsonChildNode.getString("name");
                                        String politician_designation = jsonChildNode.getString("designation");
                                        String politician_contact = jsonChildNode.getString("contact");
                                        String politician_image_url = jsonChildNode.getString("img_url");
                                        String politician_city = jsonChildNode.getString("city");
                                        String politician_house = jsonChildNode.getString("house");

                                        if (politician_designation.isEmpty())
                                        {
                                            politician_designation="NA";
                                            Log.e("Tag2",politician_designation);
                                        }

                                        if (politician_contact.isEmpty())
                                        {
                                            politician_contact="NA";
                                            Log.e("Tag3",politician_contact);
                                        }

                                        dbHelper.createPoliticianInfoData(user_id, politician_first_name,politician_designation,
                                                politician_contact, politician_image_url, politician_city, politician_house);

                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            Toast.makeText(getApplicationContext(), "Network Connection Failed", Toast.LENGTH_SHORT).show();
                            Log.e("response in success", response.toString());
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        Log.e("tag", error.toString());
                        Toast.makeText(getApplicationContext(), "Network Connection Failed from failure method", Toast.LENGTH_SHORT).show();
                    }
                };
                apis.getPolicianInfo(responseListner);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(getApplicationContext(), "Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
        }


    }
}

//这是数据库类

 public class SQLiteDbAdapter {

    public static final String KEY_ROWID = "_id";
    public static final String USER_ID = "id";
    public static final String POLITICIAN_FIRST_NAME = "name";
    public static final String POLITICIAN_DESIGNATION = "designation";
    public static String POLITICIAN_CONTACT = "contact";
    public static String POLITICIAN_IMAGE_URL = "img_url";
    public static String POLITICIAN_CITY = "city";
    public static String POLITICIAN_HOUSE = "house";
    private static final String TAG = "SQLiteDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    private static final String DATABASE_NAME = "World";
    private static final String SQLITE_TABLE = "Country";
    private static final int DATABASE_VERSION = 1;

    private final Context mCtx;

    private static final String DATABASE_CREATE =
            "CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
                    KEY_ROWID + " integer PRIMARY KEY autoincrement," +
                    USER_ID + "," +
                    POLITICIAN_FIRST_NAME + "," +
                    POLITICIAN_DESIGNATION + "," +
                    POLITICIAN_CONTACT + "," +
                    POLITICIAN_IMAGE_URL + "," +
                    POLITICIAN_CITY + "," +
                    POLITICIAN_HOUSE + "," +
                    " UNIQUE (" + KEY_ROWID +"));";

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }


        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.w(TAG, DATABASE_CREATE);
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
            onCreate(db);
        }
    }

    public SQLiteDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    public SQLiteDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        if (mDbHelper != null) {
            mDbHelper.close();
        }
    }

    public long createPoliticianInfoData(String user_id, String politician_first_name,
                              String politician_designation, String politician_contact,
                              String politician_image_url, String politician_city, String politician_house) {


        ContentValues initialValues = new ContentValues();
        initialValues.put(USER_ID, user_id);
        initialValues.put(POLITICIAN_FIRST_NAME, politician_first_name);
        initialValues.put(POLITICIAN_DESIGNATION, politician_designation);
        initialValues.put(POLITICIAN_CONTACT, politician_contact);
        initialValues.put(POLITICIAN_IMAGE_URL, politician_image_url);
        initialValues.put(POLITICIAN_CITY, politician_city);
        initialValues.put(POLITICIAN_HOUSE, politician_house);
        int cc=(int) mDb.insert(SQLITE_TABLE, null, initialValues);
        //Log.e("insert ", ""+cc);

        return cc;
    }

    public boolean deleteAllData() {

        int doneDelete = 0;
        doneDelete = mDb.delete(SQLITE_TABLE, null , null);
        Log.w(TAG, Integer.toString(doneDelete));
        return doneDelete > 0;

    }


    public Cursor fetchPoliticansByName(String inputText) throws SQLException {
        Log.w(TAG, inputText);
        Cursor mCursor = null;
        if (inputText == null  ||  inputText.length () == 0)  {
            mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
                            USER_ID, POLITICIAN_FIRST_NAME,POLITICIAN_DESIGNATION,
                    POLITICIAN_CONTACT,POLITICIAN_IMAGE_URL,POLITICIAN_CITY,POLITICIAN_HOUSE},
                    null, null, null, null, null);
        }
        else {
            mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
                            USER_ID, POLITICIAN_FIRST_NAME,POLITICIAN_DESIGNATION,
                    POLITICIAN_CONTACT,POLITICIAN_IMAGE_URL,POLITICIAN_CITY,POLITICIAN_HOUSE},
                    POLITICIAN_FIRST_NAME + " like '" + inputText + "%' OR "
                           /* + POLITICIAN_LAST_NAME + " like '"+inputText+"%' OR "*/
                            + POLITICIAN_DESIGNATION + " like '"+inputText+"%' OR "
                            + POLITICIAN_CITY + " like '"+inputText+"%' OR "
                            + POLITICIAN_HOUSE + " like '"+inputText+"%'",
                    null, null, null, null, null);

        }

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

    }



    public Cursor fetchAllData() {

        Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
                        USER_ID, POLITICIAN_FIRST_NAME,POLITICIAN_DESIGNATION,
                POLITICIAN_CONTACT,POLITICIAN_IMAGE_URL,POLITICIAN_CITY,POLITICIAN_HOUSE},
                null, null, null, null, null);
       Log.e("Cursor vallue display", "data"+mCursor);
        if (mCursor != null) {
            mCursor.moveToFirst();
            Log.e("Cursor vallue display", "datafgdfxg" +mCursor.getCount());
        }
        return mCursor;
    }

}

1 个答案:

答案 0 :(得分:0)

是。在listl的aml布局文件中添加EditText。并在您的活动/片段..

lv = (ListView) findViewById(R.id.list_view);
    inputSearch = (EditText) findViewById(R.id.inputSearch);

// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name,    products);
lv.setAdapter(adapter);       
inputSearch.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
    // When user changed the Text
    MainActivity.this.adapter.getFilter().filter(cs);
}

@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

@Override
public void afterTextChanged(Editable arg0) {}
});

这里的基本操作是将OnTextChangeListener添加到编辑文本中,并在其回调方法中将过滤器应用于listview的适配器。

要过滤到自定义BaseAdapter,您需要实现Filterable接口。

class CustomAdapter extends BaseAdapter implements Filterable {

    public View getView(){
    ...
    }
    public Integer getCount()
    {
    ...
    }

    @Override
    public Filter getFilter() {

        Filter filter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                arrayListNames = (List<String>) results.values;
                notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();
                ArrayList<String> FilteredArrayNames = new ArrayList<String>();

                // perform your search here using the searchConstraint String.

                constraint = constraint.toString().toLowerCase();
                for (int i = 0; i < mDatabaseOfNames.size(); i++) {
                    String dataNames = mDatabaseOfNames.get(i);
                    if (dataNames.toLowerCase().startsWith(constraint.toString()))  {
                        FilteredArrayNames.add(dataNames);
                    }
                }

                results.count = FilteredArrayNames.size();
                results.values = FilteredArrayNames;
                Log.e("VALUES", results.values.toString());

                return results;
            }
        };

        return filter;
    }
}

在perfromFiltering()内部,您需要将搜索查询与数据库中的值进行实际比较。它会将其结果传递给publishResults()方法。