Search code examples
androidsqlcursorandroid-sqlite

Run query in android SQLite database


I've a database in android studio that has a table name EMP_TABLE with columns E_NAME, E_AGE and E_DEPT. My fragment layout has two editText fields, a button and a TextView field. I want to perform a query on that database such that when I enter the E_NAME attribute in 1st edittext field, E_AGE attribute in 2nd edittext field and press the button the corresponding attribute of E_AGE field appear in textView field. The query looks like SELECT E_AGE FROM EMP_TABLE WHERE E_NAME=a1 AND E_DEPT=a2. I'm not so familier with the cursor and the query, help me with this. This is what I did so far in my OnClick method. Any help will be appreciated.

actTextView1 = (AutoCompleteTextView) view.findViewById(R.id.acTextView1);
        actTextView2 = (AutoCompleteTextView) view.findViewById(R.id.acTextView2);


        result = (TextView) view.findViewById(R.id.resultField);

        calculateButton = (Button) view.findViewById(R.id.calBtn);

        calculateButton.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {

                DatabaseHelper myDBhelper = new DatabaseHelper(getActivity());

                String a1 = actTextView1.getText().toString();
                String a2 = actTextView2.getText().toString();

                c = myDBhelper.query("EMP_TABLE", null, null, null, null, null, null);

                if (c.moveToFirst()) {
                    do {
                        Toast.makeText(getActivity(), "Age is: " + c.getString(0), Toast.LENGTH_LONG).show();

                    } while (c.moveToNext());
                }

Solution

  • To insert:

    public void insertIntoTable(String E_NAME_VALUE, String E_AGE_VALUE,String E_DEPT_VALUE) {
                SQLiteDatabase db = this.getWritableDatabase();
    
                    ContentValues cv = new ContentValues();
                    cv.put(E_NAME, E_NAME_VALUE);
                    cv.put(E_AGE, E_AGE_VALUE);
                    cv.put(E_DEPT, E_DEPT_VALUE);
                    db.insert(EMP_TABLE , null, cv);
            }
    

    To Fetch stored value from database:

    public String fetchValueFromTable(String E_NAME_VALUE,String E_DEPT_VALUE) {
    String E_AGE_VALUE="" ;   
    SQLiteDatabase db = this.getWritableDatabase();
     SELECT E_AGE FROM EMP_TABLE WHERE E_NAME=a1 AND E_DEPT=a2
            String query = "SELECT * FROM " + EMP_TABLE + " WHERE " + E_NAME+ "='" + E_NAME_VALUE+ "' ANd "+ E_DEPT+ "='" + E_DEPT_VALUE;
            Cursor cursor = db.rawQuery(query, null);
     if (cursor.moveToFirst()) {
        E_AGE_VALUE=cursor.getString(cursor.getColumnIndex(E_AGE));
        }
         return E_AGE_VALUE;
        }