How to Retrieve Data from Sqlite Database in Android and Display It in Textview

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

Here is an example of how I achieved this.

In this example I will store, retrieve, update and delete a students name and age.


First create a class, I called mine

DBManager.java

public class DBManager {
private Context context;
private SQLiteDatabase database;
private SQLiteHelper dbHelper;

public DBManager(Context c) {
this.context = c;
}

public DBManager open() throws SQLException {
this.dbHelper = new SQLiteHelper(this.context);
this.database = this.dbHelper.getWritableDatabase();
return this;
}

public void close() {
this.dbHelper.close();
}

public void insert(String name, String desc) {
ContentValues contentValue = new ContentValues();
contentValue.put(SQLiteHelper.NAME, name);
contentValue.put(SQLiteHelper.AGE, desc);
this.database.insert(SQLiteHelper.TABLE_NAME_STUDENT, null, contentValue);
}


public Cursor fetch() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_STUDENT, new String[]{SQLiteHelper._ID, SQLiteHelper.NAME, SQLiteHelper.AGE}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}

public int update(long _id, String name, String desc) {
ContentValues contentValues = new ContentValues();
contentValues.put(SQLiteHelper.NAME, name);
contentValues.put(SQLiteHelper.AGE, desc);
return this.database.update(SQLiteHelper.TABLE_NAME_STUDENT, contentValues, "_id = " + _id, null);
}

public void delete(long _id) {
this.database.delete(SQLiteHelper.TABLE_NAME_STUDENT, "_id=" + _id, null);
}
}

Then create a SQLiteOpenHelper I called mine

SQLiteHelper.java

public class SQLiteHelper extends SQLiteOpenHelper {
public static final String AGE = "age";
private static final String CREATE_TABLE_STUDENT = " create table STUDENTS ( _id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL , age TEXT );";
private static final String DB_NAME = "STUDENTS.DB";
private static final int DB_VERSION = 1;
public static final String NAME = "name";
public static final String TABLE_NAME_STUDENT = "STUDENTS";
public static final String _ID = "_id";

public SQLiteHelper(Context context) {
super(context, DB_NAME, null, 1);
}

public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_STUDENT);
}

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

TO ADD:

In this example I take the text from EditText and when the button is clicked I check if the EditText is empty or not. If it is not empty and the student doesn't already exist I insert the students name and age into the database. I display a Toast, letting the user know of the status:

btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (edtName.getText().toString().trim().length() == 0) {
Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();
} else{
try {
if (edtAge.getText().toString().trim().length() != 0) {
String name = edtName.getText().toString().trim();
String age = edtAge.getText().toString().trim();
String query = "Select * From STUDENTS where name = '"+name+"'";
if(dbManager.fetch().getCount()>0){
Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
}else{
dbManager.insert(name, age);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
}

} else {
Toast.makeText(getApplicationContext(), "please provide student age!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});

TO UPDATE:


Here I take the Text in EditText and update the student when the button is clicked. You can also place the following in a try/catch to make sure it is updated successfully.

btnupdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = nameText.getText().toString();
String age = ageText.getText().toString();
dbManager.update(_id, name, age);
Toast.makeText(getApplicationContext(), "Updated successfully!", Toast.LENGTH_SHORT).show();
}
});

TO DELETE:

dbManager.delete(_id);
Toast.makeText(getApplicationContext(), "Deleted successfully!", Toast.LENGTH_SHORT).show();

TO GET:

Here I get the name of the student and display it in a TextView

DBManager dbManager = new DBManager(getActivity());
dbManager.open();

Cursor cursor = dbManager.fetch();
cursor.moveToFirst();
final TextView studentName = (TextView) getActivity().findViewById(R.id.nameOfStudent);
studentName.settext(cursor.getString(0));

How to retrieve data from sqlite database in android and display it in TextView

on button click, first open the database, fetch the data and close the data base like this

public class cytaty extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.galeria);

Button bLosuj = (Button) findViewById(R.id.button1);
bLosuj.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
myDatabaseHelper = new DatabaseHelper(cytaty.this);
myDatabaseHelper.openDataBase();

String text = myDatabaseHelper.getYourData(); //this is the method to query

myDatabaseHelper.close();
// set text to your TextView
}
});
}
}

and your getYourData() in database class would be like this

public String[] getAppCategoryDetail() {

final String TABLE_NAME = "name of table";

String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] data = null;

if (cursor.moveToFirst()) {
do {
// get the data into array, or class variable
} while (cursor.moveToNext());
}
cursor.close();
return data;
}

Retrieving single data from SQLite and display in TextView (Android Development)

I think you should try declaring bankbal as double rather than text.
Anyways if you want it to be text Try doing this

Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor!=null && cursor.getCount()>0)
{
cursor.moveToFirst()
do {
bankbalresult = cursor.getString(0);
} while (cursor.moveToNext());
}
}
return bankbalresult;
} }

// In the activity where you want it displayed you can do

 TextView tv = new TextView();
DBController info = new DBController(this);
info.open();
String data = info.getBankBal();
info.close();
tv.setText(data);


Related Topics



Leave a reply



Submit