Android Studio, how to retrieve data from Sqlite database and display it into textview?

Viewed 64008

I created an SQLite Database in my app, and I insert the data into it. And now I want to retrieve data from it but I want just insert one data and retrieve it then display it into a TextView.

public class Db_sqlit extends SQLiteOpenHelper{

    String TABLE_NAME = "BallsTable";

    public final static String name = "db_data";

    public Db_sqlit(Context context) {
        super(context, name, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table "+TABLE_NAME+" (id INTEGER PRIMARY KEY AUTOINCREMENT, ball TEXT)");

    }

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

    public boolean insertData(String balls){
      SQLiteDatabase db = this.getWritableDatabase();
      ContentValues contentValues = new ContentValues();

      contentValues.put("ball",balls);

      long result = db.insert(TABLE_NAME,null,contentValues);
      if(result == -1){
          return false;
      }
      else
          return true;
    }

    public void list_balls(TextView textView) {

        Cursor res = this.getReadableDatabase().rawQuery("select ball from "+TABLE_NAME+"",null);
        textView.setText("");
        while (res.moveToNext()){
            textView.append(res.getString(1));
        }  
    }
}
3 Answers

Then I have implement the code in main java class where I want to show using cursor.moveToNext()

searchButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Cursor result = databaseSQLite2.searchData(searchET.getText().toString());
            while (result.moveToNext()){
                searchresultTV.setText(result.getString(2));
            }
        }
    });

For fetching data from sqlite I have done this method in DatabaseHelper class

public Cursor searchData(String id){
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    //String qry = "SELECT * FROM "+TABLE_NAME+" WHERE ID="+id;
    Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE ID="+id,null);
    return cursor;
}
Related