0

I have stored three values into the database and i want to make search on button click, after clicking on search button it will be move on search screen and there is only search box is presented.

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;
    }
}
Valentin Despa
  • 40,712
  • 18
  • 80
  • 106
Nilesh Sasane
  • 85
  • 1
  • 1
  • 7
  • and this is the log cat Error E/MessageQueue-JNI(19662): Exception in MessageQueue callback: handleReceiveCallback E/InputEventSender(19662): Exception dispatching finished signal. E/MessageQueue-JNI(19662): Exception in MessageQueue callback: handleReceiveCallback E/MessageQueue-JNI(19662): java.lang.ClassCastException: java.util.ArrayList cannot be cast to android.widget.Filterable E/MessageQueue-JNI(19662): at com.androidadvance.screen.SearchRecord$1.onTextChanged(SearchRecord.java:112) – Nilesh Sasane Aug 14 '13 at 07:40
  • Post only the portion of code that is important... It will be hard to take out time to understand the whole code – Aman Gautam Aug 14 '13 at 07:52
  • 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); } }); – Nilesh Sasane Aug 14 '13 at 08:19
  • In that it gives error to ((Filterable) _candidatelist).getFilter().filter(s.toString()); ArrayList Cannot be cast to android.widget.Filterable – Nilesh Sasane Aug 14 '13 at 08:21

1 Answers1

0

ArrayList is not Filterable. It says in the Filterable documentation :

Defines a filterable behavior. A filterable class can have its data constrained by a filter. Filterable classes are usually Adapter implementations.

I think you should replace your ArrayList by an ArrayAdapter

Rémi F
  • 1,327
  • 12
  • 25
  • Thank you, can you please suggest me a link for such kind of example, i have got lots of example with hard coded list contents. – Nilesh Sasane Aug 19 '13 at 03:47
  • Please have a look at the first part here http://www.cannonade.net/blog.php?id=1488 and also this SO answer http://stackoverflow.com/questions/10532194/filter-listview-with-arrayadapter/10532898#10532898 – Rémi F Aug 19 '13 at 06:56
  • Welcome to Stackoverflow! If you find a response is helpful, please up vote it. If the response successfully answers your question, please click the green check mark next to it to accept the answer. Also please look at stackoverflow.com/questions/how-to-ask for advice on how to write a good question – Rémi F Aug 20 '13 at 19:25