Android click button to call boolean function to check if table exists - android

I am completely stuck. been banging my head against a brick wall all day!
I have a class:
public class Main extends Activity.
This has several buttons.
On 2 of the buttons I want to get the result of a boolean function that checks if a database table exists or not so that I can choose the next action.
final Button reminderButton = (Button) findViewById(R.id.reminders);
reminderButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
//This is where I want to get the result from the boolean function
// and then either provide a toast msg OR start a new activity
}
});
Below is the boolean function
public boolean isTableExists(SQLiteDatabase db, String tableName) {
if (tableName == null || db == null || !db.isOpen())
{
return false;
}
Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM sqlite_master WHERE type = ?
AND name = ?",new String[] { "table", tableName });
if (!cursor.moveToFirst())
{
return false;
}
int count = cursor.getInt(0);
cursor.close();
return count > 0;
}
For the life of me I cannot work out the syntax to put in my onclick (View v){}
I had tried
public void onClick(View v)
{
isTableExists(null, null);
}
but I dont think the null,null is correct, but what arguments go in there?
or am I on the wrong track completely?
Thanks for any advice

From your post i understand that you want to check whether Table exists or not.
This code will help you.
public boolean isTableExists(String tableName, boolean openDb) {
if(openDb) {
if(mDatabase == null || !mDatabase.isOpen()) {
mDatabase = getReadableDatabase();
}
if(!mDatabase.isReadOnly()) {
mDatabase.close();
mDatabase = getReadableDatabase();
}
}
Cursor cursor = mDatabase.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+tableName+"'", null);
if(cursor!=null) {
if(cursor.getCount()>0) {
cursor.close();
return true;
}
cursor.close();
}
return false;
}
Based on this boolean value You can do your action.

Related

Database output to EditText

i want to retrieve id from database where name = saqib into the EditText(textbox) in android, i have tried different ways but can't achieve my desired output instead of that the given output will be shown every time. output
onButtonClick:
final EditText i=(EditText)findViewById(R.id.id_etxt);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res= mydatabase.fet();
i.setText(res.toString());
}
});
Database.java class
public Cursor fet(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res=db.rawQuery("select ID from record where Name=?",new String[] {"saqib"});
return res;
}
Cursor res = mydatabase.fet();
if (res.getCount() > 0) {
res.moveToFirst();
i.setText(res.getString(0));
} else {
throw new SQLiteException("e");
}
Currently you set the whole Cursor as String in EditText, which is not right way to set ID.
You have to extract the ID from Cursor like below to use it in EditText:
public void onClick(View v) {
Cursor res = mydatabase.fet();
if(res != null && res.moveToFirst()) {
String id = Integer.toString(res.getInt(res.getColumnIndex("ID")));
i.setText(id);
}
}

Android sqlite check if table is empty

i'm working sqlite.i want to check if table is empty.i wrote some code but my code does not working perfect
this is a my DatabaseHelper code (function)
public boolean CheckGenderTableEmpty() {
boolean isEmpty = false;
String count = "SELECT * FROM Gender";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
if (mcursor.getCount() != 0) {
if (!mcursor.isClosed())
{
mcursor.close();
Log.e("is not empty", "is not empty");
isEmpty=true;
}
} else {
if (!mcursor.isClosed())
{
mcursor.close();
Log.e(" empty", "empty");
isEmpty=false;
}
}
return isEmpty;
}
as i said my code does not working perfect.first time my table is empty and i can't show log message about empty
and i call my function activity like this..
if(db_helper.CheckGenderTableEmpty()==true)
{
Toast.makeText(getApplicationContext(), "is not empty", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "empty", Toast.LENGTH_SHORT).show();
}
how i can check if database is empty in activity?
if anyone knows solution please help me
Use getCount() method of Cursor:
public boolean IsTableEmpty(Cursor cursor) {
return !(cursor.getCount() > 0);
}
The Android framework has a helper function for this in the DatabaseUtils class:
public boolean CheckGenderTableEmpty() {
return DatabaseUtils.queryNumEntries(db, "Gender") == 0;
}
you can go with something like
SQLiteDatabase db = table.getWritableDatabase();
String count = "SELECT count(*) FROM Gender";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
if(icount>0)
//do accordingly
else
//do accordingly
cursor.moveToFirst(); // Always one row returned.
Then check cursor.getInt (0) == 0
if(cursor.getInt (0) == 0) // Zero count means empty table.
Try this.

select from db in sqlite database

what is wrong with this code
when i run it the program don,t response
public Cursor checkauth(String username,String password)
{
Ecommerce=getReadableDatabase();
// Cursor curser =Ecommerce.rawQuery("select * from customer where username = ? and password =?", new String []{username,password});
//String [] details={"id","custname","gender"};
Cursor c = Ecommerce.rawQuery("select id from customer where username = ? AND password = ?" , new String[] {username,password });
//Cursor cursor = Ecommerce.query(true, "customer",details,"username = ? AND password = ?", new String[] { username, password },null, null, null, null, null);
while(c != null)
{
c.moveToFirst();
}
return c;
}
in activity
public void onClick(View arg0) {
// TODO Auto-generated method stub
user_name=username.getText().toString();
passwords=password.getText().toString();
Cursor c=data.checkauth(user_name, passwords);
while(!c.isAfterLast())
{
username.setText(String.valueOf(c.getInt(0)));
c.moveToNext();
}
}
![enter image description here][1]
You're blocking your UI thread.
This loop never completes:
while(c != null)
{
c.moveToFirst();
}
The while condition is always true. The loop doesn't seem to be doing anything useful, you can probably just leave a plain c.moveToFirst() there.
Try with this..
String selectQuery = "Write select query" ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
boolean result = false;
if (cursor.moveToFirst())
{
do
{
result = true;
} while (cursor.moveToNext());
}
else
{
result = false;
}
Even though this question is answered already, I'd like to suggest a simple improvement. What you're doing is kind of useless. Your goal is to know whether or not a user exists and what his or her id is.
public int checkAuth(String username, String password) {
String sql = "select id from customer where username = ? AND password = ?";
Ecommerce = getReadableDatabase(); //field names never start with uppercase
Cursor c;
try {
c = Ecommerce.rawQuery(sql, new String[] { username, password });
if (c.moveToFirst()) //if the cursor has any records, this returns true, else false
return c.getInt(0); //so if a user exists with given params, we can return an id
else
return -1; //if not, we return -1, which means: user/pass-combination not found
}
finally { //but after the whole method, we need to do some things:
if (c != null && !c.isClosed())
c.close(); //close the cursor
closeDatabase(); //and close the database
}
}
This way you keep your UI code separated from your database code. A cursor shouldn't appear in UI-code. Which above modifications, the UI code looks a lot cleaner
int i = data.checkAuth(username, password);
if (i == -1) {
//alert of some kind
}
else
username.setText(String.valueOf(i));

Sqlite Check if Table is Empty [duplicate]

This question already has answers here:
How can i check to see if my sqlite table has data in it?
(13 answers)
Closed 4 years ago.
Well, I have a databse and it has lots of table. but generally tables are empty.
I want check if a database table is empty.
IF table is empty, program will fill it.
public static long queryNumEntries (SQLiteDatabase db, String table)
I will use it but it requre API 11.
you can execute select count(*) from table and check if count> 0 then leave else populate it.
like
SQLiteDatabase db = table.getWritableDatabase();
String count = "SELECT count(*) FROM table";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
if(icount>0)
//leave
else
//populate table
Do a SELECT COUNT:
boolean empty = true
Cursor cur = db.rawQuery("SELECT COUNT(*) FROM YOURTABLE", null);
if (cur != null && cur.moveToFirst()) {
empty = (cur.getInt (0) == 0);
}
cur.close();
return empty;
public boolean isEmpty(String TableName){
SQLiteDatabase database = this.getReadableDatabase();
long NoOfRows = DatabaseUtils.queryNumEntries(database,TableName);
if (NoOfRows == 0){
return true;
} else {
return false;
}
}
Optimal Solutions
public boolean isMasterEmpty() {
boolean flag;
String quString = "select exists(select 1 from " + TABLE_MASTERS + ");";
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(quString, null);
cursor.moveToFirst();
int count= cursor.getInt(0);
if (count ==1) {
flag = false;
} else {
flag = true;
}
cursor.close();
db.close();
return flag;
}
Here is a better option:
public boolean validateIfTableHasData(SQLiteDatabase myDatabase,String tableName){
Cursor c = myDatabase.rawQuery("SELECT * FROM " + tableName,null);
return c.moveToFirst();
}
This is how you can do it -
if(checkTable("TABLE"))
{
//table exists fill data.
}
Method to check table -
public static boolean checkTable(String table) {
Cursor cur2 = dbAdapter.rawQuery("select name from sqlite_master where name='"
+ table + "'", null);
if (cur2.getCount() != 0) {
if (!cur2.isClosed())
cur2.close();
return true;
} else {
if (!cur2.isClosed())
cur2.close();
return false;
}
}
I think, this solution is better:
boolean flag;
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext(), DatabaseHelper.DATABASE_NAME, null, DatabaseHelper.DATABASE_VERSION);
try {
sqLiteDatabase = databaseHelper.getWritableDatabase();
} catch (SQLException ex) {
sqLiteDatabase = databaseHelper.getReadableDatabase();
}
String count = "SELECT * FROM table";
Cursor cursor = sqLiteDatabase.rawQuery(count, null);
if (cursor.moveToFirst()){
flag = false;
} else {
flag = true;
}
cursor.close();
sqLiteDatabase.close();
return flag;
moveToFirst() check table and return true, if table is empty. Answer that is marked correct - uses extra check.

Getting the next record into view from database

I have two buttons inside of my application, one for next and one for prev. I want the next button to get the next record inside of my database and display it inside of my view, and the prev button to get the previous record and display it inside of my view. How would I call the next or previous record? I have looked for tutorials and stuff but didn't find any. I anyone has a tutorial please share with me. Thanks for any help. I wish I had some code to provide but I really don't know where to start.
I use an int to pull the record from the dbase.
From my ContactView class
static long record = 1;
public void getData() {
DBase db = new DBase(this);
db.open();
lastRecord = db.lRec();
firstRecord = db.fRec();
rRec = db.getRec(record);
db.close();
}
then my query is from my Dbase class
public String[] getRec(long record) {
record = ContactView.record;
String[] columns = new String[] { KEY_ROWID, KEY_ONE, KEY_TWO,
KEY_THREE, KEY_FOUR, KEY_FIVE, KEY_SIX };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
+ record, null, null, null, null);
if (c != null && c.moveToFirst()) {
String rRec = c.getString(0);
String rOne = c.getString(1);
String rTwo = c.getString(2);
String rThree = c.getString(3);
String rFour = c.getString(4);
String rFive = c.getString(5);
String rSix = c.getString(6);
String[] rData = { rRec, rOne, rTwo, rThree, rFour,
rFive, rSix };
return rData;
}
return null;
}
and the next few are from my ContactView class
my buttons
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bSQLvPrev:
recordMinus();
display();
break;
case R.id.bSQLvNext:
recordPlus();
display();
break;
}
}
and the methods they call
public void display() {
etSQLvRec.setText(rRec[0]);
etSQLvOne.setText(rRec[1]);
etSQLvTwo.setText(rRec[2]);
etSQLvThree.setText(rRec[3]);
etSQLvFour.setText(rRec[4]);
etSQLvFive.setText(rRec[5]);
etSQLvSix.setText(rRec[6]);
}
public void recordPlus() {
record++;
}
public void recordMinus() {
record--;
}
That will get the record from the database based on the "record" variable, and the buttons increment it, or decrement it, it also skips any "empty" records.
EDIT OK, I had changed some stuff around since I lasted used my db, so use the next recordPlus() and recordMinus() code instead
public void recordPlus() {
if (record < lastRecord) {
record++;
} else {
record = firstRecord;
}
getData();
do {
if (record < lastRecord) {
record++;
} else {
record = firstRecord;
}
getData();
} while (rRec == null);
}
public void recordMinus() {
if (record == 1) {
record = lastRecord;
} else {
record--;
}
getData();
do {
if (record == 1) {
record = lastRecord;
} else {
record--;
}
getData();
} while (rRec == null);
}
And you'll need my fRec() and lRec() which find the first and last records in the DB
public long fRec() {
Cursor c = ourDatabase.query(DATABASE_TABLE, new String[] { "min(" +
KEY_ROWID
+ ")" }, null, null, null, null, null);
c.moveToFirst();
long rowID = c.getInt(0);
return rowID;
}
}
public long lRec() {
long lastRec = 0;
String query = "SELECT ROWID from Table order by ROWID DESC limit 1";
Cursor c = ourDatabase.rawQuery(query, null);
if (c != null && c.moveToFirst()) {
lastRec = c.getLong(0);
}
return lastRec;
}

Categories

Resources