从自定义ListView中搜索特定记录

时间:2013-08-14 07:34:37

标签: android android-listview

我已经将三个值存储到数据库中,我想在点击按钮时进行搜索,点击搜索按钮后,它将在搜索屏幕上移动,并且只显示搜索框。

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {

    public static String DATABASENAME = "Aadhaar";
    public static String PRODUCTTABLE = "Enrolled";

    private ArrayList<CandidateModel> cartList = new ArrayList<CandidateModel>();
    Context c;

    public DatabaseHelper(Context context) {
        super(context, DATABASENAME, null, 33);
        c = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE if not exists Enrolled(id INTEGER PRIMARY KEY AUTOINCREMENT,"
                + "_id"
                + " TEXT ,"
                + "FirstName"
                + " TEXT,"
                + "LastName"
                + " TEXT)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS" + PRODUCTTABLE);
        onCreate(db);
    }

    public void addProduct(CandidateModel productitem) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("_id", productitem.idno);
        contentValues.put("FirstName", productitem.productname);
        contentValues.put("LastName", productitem.productprice);
        db.insert("Enrolled", null, contentValues);
        db.close();

    }

    // update

    public void updateProduct(CandidateModel productList) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("FirstName", productList.productname);

        contentValues.put("LastName", productList.productprice);
        db.update("Enrolled", contentValues, "_id=" + productList.idno, null);

        db.close();
    }

    public void emptyProduct() {
        try {
            SQLiteDatabase db = this.getWritableDatabase();
            db.execSQL("delete from Enrolled");
            db.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void removeProduct(String productid, String pname, String pprice) {
        try {
            // SQLiteDatabase db = this.getWritableDatabase();
            // db.execSQL("delete from producttable where productidno="
            // + productid);
            // db.close();

            String[] args = { productid };
            getWritableDatabase().delete("Enrolled", "_id=?", args);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ArrayList<CandidateModel> getProudcts() {

        cartList.clear();

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from Enrolled", null);
        if (cursor.getCount() != 0) {
            if (cursor.moveToFirst()) {
                do {
                    CandidateModel item = new CandidateModel();

                    item.idno = cursor.getString(cursor.getColumnIndex("_id"));

                    item.productname = cursor.getString(cursor
                            .getColumnIndex("FirstName"));

                    item.productprice = cursor.getString(cursor
                            .getColumnIndex("LastName"));

                    cartList.add(item);

                } while (cursor.moveToNext());
            }
        }
        cursor.close();
        db.close();
        return cartList;
    }
}

Aadhar.java

public class Aadhar extends Activity implements OnClickListener {

    private Button btn_add, btn_view, btn_search;

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

        btn_add = (Button) findViewById(R.id.btn_add);
        btn_view = (Button) findViewById(R.id.btn_view);
        btn_search = (Button) findViewById(R.id.btn_search);
        btn_add.setOnClickListener(this);
        btn_view.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_add:
            Intent addintent = new Intent(Aadhar.this, AddRecord.class);
            startActivity(addintent);
            break;

        case R.id.btn_view:
            Intent viewintent = new Intent(Aadhar.this, ViewRecord.class);
            startActivity(viewintent);
            break;

            case R.id.btn_search:
                Intent searchIntent = new Intent (Aadhar.this, SearchRecord.class);
                startActivity(searchIntent);
        default:
            break;
        }

    }
}

SearchRecord.java

 public class SearchRecord extends Activity implements OnClickListener {

    String TAG = "SearchRecord";

    private ListView lv;
    // Button searchButton;
    private EditText search;
    CandidateModel cm;
    DatabaseHelper db;
    public ArrayList<CandidateModel> _candidatelist = new ArrayList<CandidateModel>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_candidate);
Log.v(TAG, "Searching Candidates");

        lv = (ListView) findViewById(R.id.search_listview);
        search = (EditText) findViewById(R.id.edit_search);

        Log.v(TAG, "Going to enter into TextWatcher");

        lv.setTextFilterEnabled(true);

        search.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) {

                Log.v(TAG, "Entered into the Text Changed Method");

                ((Filterable) _candidatelist).getFilter().filter(s.toString());

                Log.v(TAG, "Finished Filtering");

                lv.setAdapter((android.widget.ListAdapter) _candidatelist);
            }
        });

}

CandidateModel.java

public class CandidateModel {

    public String getFirstname() {
        return fname;
    }

    public void setFirstname(String fname) {
        this.fname = fname;
    }

    public String getLastname() {
        return lname;
    }

    public void setLastname(String lname) {
        this.lname = lname;
    }

    public String idno="", fname="", lname="";

    public String getIdno() {
        return idno;
    }

    public void setIdno(String idno) {
        this.idno = idno;
    }

}

ViewRecord.java

public class ViewRecord extends Activity {

    private ListView listview;
    // private EditText search;
    String TAG = "ViewRecord";
    TextView totalrecords;
    DatabaseHelper db;
    public ArrayList<CandidateModel> _candidatelist = new ArrayList<CandidateModel>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_candidates);
        totalrecords = (TextView) findViewById(R.id.totalrecords);
        listview = (ListView) findViewById(R.id.listview);
    }

    @Override
    protected void onResume() {
        super.onResume();

        _candidatelist.clear();

        db = new DatabaseHelper(getApplicationContext());
        db.getWritableDatabase();
        ArrayList<CandidateModel> cand_list = db.getCandidates();

        for (int i = 0; i < cand_list.size(); i++) {

            String tidno = cand_list.get(i).getIdno();

            System.out.println("tidno>>>>>" + tidno);
            String tname = cand_list.get(i).getFirstname();
            String tprice = cand_list.get(i).getLastname();

            CandidateModel _CandidateModel = new CandidateModel();

            _CandidateModel.setIdno(tidno);
            _CandidateModel.setFirstname(tname);
            _CandidateModel.setLastname(tprice);

            _candidatelist.add(_CandidateModel);
        }
        totalrecords.setText("Total Enrollments :-" + _candidatelist.size());
        listview.setAdapter(new ListAdapter(this));
        db.close();

    }

    public class ListAdapter extends BaseAdapter {
        LayoutInflater inflater;
        ViewHolder viewHolder;

        public ListAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return _candidatelist.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {

                convertView = inflater.inflate(R.layout.listview_row, null);
                viewHolder = new ViewHolder();

                viewHolder._id = (TextView) convertView
                        .findViewById(R.id.txtdisplaypname);
                viewHolder.fname = (TextView) convertView
                        .findViewById(R.id.txtdisplaypprice);

                viewHolder.lname = (TextView) convertView
                        .findViewById(R.id.txtdisplaypid);
                convertView.setTag(viewHolder);

            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder._id.setText(_candidatelist.get(position).getFirstname()
                    .trim());
            viewHolder.fname.setText(_candidatelist.get(position).getLastname()
                    .trim());

            viewHolder.lname.setText(_candidatelist.get(position).getIdno()
                    .trim());

            final int temp = position;
            (convertView.findViewById(R.id.btn_update))
                    .setOnClickListener(new OnClickListener() {

                        public void onClick(View arg0) {

                            String _id = String.valueOf(_candidatelist
                                    .get(temp).getIdno());
                            String _fname = _candidatelist.get(temp)
                                    .getFirstname();
                            String _lname = _candidatelist.get(temp)
                                    .getLastname();
                            Intent intent = new Intent(ViewRecord.this,
                                    AddUpdateValues.class);

                            Bundle bundle = new Bundle();
                            bundle.putString("id", _id);
                            bundle.putString("name", _fname);
                            bundle.putString("price", _lname);
                            intent.putExtras(bundle);
                            startActivity(intent);

                        }
                    });

            (convertView.findViewById(R.id.btn_delete))
                    .setOnClickListener(new OnClickListener() {

                        public void onClick(View arg0) {

                            AlertDialog.Builder alertbox = new AlertDialog.Builder(
                                    ViewRecord.this);
                            alertbox.setCancelable(true);
                            alertbox.setMessage("Are you sure you want to delete ?");
                            alertbox.setPositiveButton("Yes",
                                    new DialogInterface.OnClickListener() {

                                        public void onClick(
                                                DialogInterface arg0, int arg1) {

                                            Log.i(">>>TEMP>>>", temp + "");
                                            Log.i(">>>getIdno>>>>>>",
                                                    _candidatelist.get(temp)
                                                            .getIdno().trim()
                                                            + "");
                                            System.out
                                                    .println(">>>getIdno>>>>>>"
                                                            + _candidatelist
                                                                    .get(temp)
                                                                    .getIdno()
                                                                    .trim());
                                            db.removeCandidate(
                                                    _candidatelist.get(temp)
                                                            .getIdno().trim(),
                                                    "", "");

                                            ViewRecord.this.onResume();

                                            Toast.makeText(
                                                    getApplicationContext(),
                                                    "Record Deleted...",
                                                    Toast.LENGTH_SHORT).show();
                                        }
                                    });
                            alertbox.setNegativeButton("No",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface arg0, int arg1) {
                                        }
                                    });
                            alertbox.show();
                        }
                    });
            return convertView;
        }
    }

    public class ViewHolder {
        TextView _id;
        TextView fname;
        TextView lname;
    }
}

1 个答案:

答案 0 :(得分:0)

ArrayList不是Filterable。它在Filterable documentation

中说
  

定义可过滤行为。可过滤的类可以拥有其数据   由过滤器约束。可过滤的类通常是Adapter   的实施方式。

我认为您应该用ArrayAdapter

替换ArrayList