Android SQLite rawQuery giving trouble - android

There's this method which i've created to know if a contact exists in my Sqlite database.
public Cursor doesContactExist(String name)
{
return db.rawQuery("select * from contacts where name = ?; ", new String[] {name});
}
But whenever it is called from another activity it crashes only at this point....
if(db.doesContactExist(name)==null){ <== crashes here
try {
db.open();
db.insertContact(name,cNumber);//name and number are Strings
listItems.add(name); //a List View array
db.close();
adapter.notifyDataSetChanged(); //adapter for ListView
}
catch (Exception e) {
//some code }
}
According to me the rawQuery is having some troulble, especially the sql String in it.
Any help please?

you try to make a select before your database is open:
if(db.doesContactExist(name)==null){ <== it is closed here
try {
db.open(); <== open the db here
change it to:
db.open();
if(db.doesContactExist(name)==null){
try {

I think it might help you..
db.open();
if(db.doesContactExist(name)==null)
{
try
{
// Your Code Here..
}
}
and in Database Class
public Cursor doesContactExist(String name)
{
return db.rawQuery("SELECT * FROM contacts WHERE name=?", new String[ {name.toString()});
}
use db.open() method before using any database function because it will open your connection with database.. and at last don't forget to close database like db.close() and if you are using Cursor anywhere in code please close this also. it not generates any error but it gives you warnings. :)

Related

make sure cursor is initialized correctly before accessing data from it

Can anyone help me how to execute this query?
I am trying to fetch distinct supervisor from project table. supervisor is column name and its index is 5.
try {
String query = "select distinct supervisor from project ";
Cursor cursor= db.rawQuery(query,null);//query( query , null, null,null,null,null,null);
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(5));
} while (cursor.moveToNext());
}
// finish();
cursor.close();
db.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return labels;
}
Your query is wrong.
You have to query write like this.
select * from project where YOUR_CONDITION
I don't know what you exactly trying to do.
Example query.
select * from customers where LastName = 'Tremblay'
To get Distinct value of supervisor you should query like this.
select * from project group by supervisor
Hope it helps:)
You could use an if statement ie if cursor != null, do something.

Application crashes while reading an empty table in android

The issue is purely with the contents inside the tables. If the table is not empty (with one or more records), application works perfectly. I am deleting the contents of table and immediately after that reading the same table, it throws exception and app force closes.
I tried searching for it but couldn't conclude. The key point is : index out of bound exception which is thrown at movetofirst() method of cursor when i am going to read the table, i suppose... Please help.
public List<TableData> readForPaymentDetais()
{
List<TableData> paymentDetails = new ArrayList<TableData>();
try
{
String selectQuery = "select * from PaymentDetails";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.getCount() !=0)
{
if(cursor.moveToFirst())
{
do
{
TableData data = new TableData();
data.setPaymentMade(Float.valueOf(cursor.getString(0).toString()));
data.setDateOfPayment(cursor.getString(1));
paymentDetails.add(data);
}
while(cursor.moveToNext());
}
}
return paymentDetails;
}
catch(Exception exc)
{
return null;
}
}
Before executing moveToFirst method of cursor please check whether cursor is empty. For that you can use code like:
if (mCursor.getCount() == 0) {
// cursor is empty
}
If cursor is not empty put your stuff in else part.

Delete Record from Database row wise in Android

I'm trying to build my first Android application, but I'm experiencing a problem: I write following code for insert record in database, but I don't know how to delete a row, so can anybody help me???
Code for insert record:
public void btnAddEmp_Click(View view)
{
boolean ok=true;
try
{
Spannable spn=txtAge.getText();
String name=txtName.getText().toString();
int age=Integer.valueOf(spn.toString());
int deptID=Integer.valueOf((int)spinDept.getSelectedItemId());
Student emp=new Student(name,age,deptID);
dbHelper.AddEmployee(emp);
}
catch(Exception ex)
{
ok=false;
CatchError(ex.toString());
}
finally
{
if(ok)
{
//NotifyEmpAdded();
Alerts.ShowEmpAddedAlert(this);
txtEmps.setText("Number of students "+String.valueOf(dbHelper.getEmployeeCount()));
}
}
}
DELETE FROM tableName WHERE fieldName = value
This is delete query. Execute it with execSql
Edit: use execSql instead of rawQuery
You can simply do this using SQLiteDatabase.execSQL() and don't try rawQuery It's meant for querying.
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM tableName where fieldName=Value");
db.close();
Check out the detailed answer here

What is going wrong in this?

I am fetching the list of tables from the database. I am using this code to get the list of tables:
public void showAllTable()
{
db.execSQL("select name from sqlite_master where type = 'table'");
}
This query execute successful in to the shell window.
Now I want to display that list of tables in Android. How it is possible? I am calling this function from another activity.
Edited:
Thanks to Stack Overflow, I found the answer here.
The usual way to display a list of data is to use a ListView. To do this you will need to do the following:
1: change your db query to db.query instead of db.exec and store the values in a List:
ArrayList<String> tables = new ArrayList<String>();
Cursor mCursor = db.query("sqlite_master", new String[]{"name"}, "type = table",
null,null,null,null);
if (mCursor.getCount() > 0) {
for (mCursor.moveToFirst(), !mCursor.isAfterLast(), mCursor.moveToNext()) {
tables.add(mCursor.getString(0));
}
}
/** Important! always close cursors and DB's */
mCursor.close();
db.close();
return tables;
2: Use a ListView and an ArrayAdapter to display the information. See The Android Tutorial on how to do this.

What's wrong with my code while populating Listview from SQLite?

Following s my Code to display data to listview from database. But it will not work and crash my application.please Give perfect solution for my this problem.
My Code......
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.deletestudent);
// DisplayStudent();
ArrayList<String > arrlst=new ArrayList<String>();
ListView lst_stu=(ListView) findViewById(R.id.ListView01);
db.open();
Cursor cur=db.GetStudent();
for (int i=0;i<cur.getCount();i++)
{
cur.moveToFirst();
String stunm=cur.getString(1);
arrlst.add(1, stunm);
lst_stu.setAdapter((ListAdapter) arrlst);
db.close();
}
}
for (int i=0;i<cur.getCount();i++)
{
cur.moveToFirst();
String stunm=cur.getString(1);
arrlst.add(1, stunm);
lst_stu.setAdapter((ListAdapter) arrlst);
db.close();
}
The problem is that you are closing the cursor in the first iteration.
Give perfect solution for my this problem.
You look like my boss, excepts that he pays 20 dollars per hour....
Whatever, there are a lot of things which are bad in your code, mostly because you don't understand how a cursor works:
Why do you call moveToFirst on each iteration? Does it make sens for you?
Why do you close the cursor inside the for?
Why do you set the adapter on each iteration?
Why do you use an array adapter instead of CursorAdapter?
Please Try Below Code
try
{
Cursor cursor = null;
db.OpenDatabase();
cursor = db.GetStudent();
// Here if condition check wheather the cursor returns record or not.
// If cursor has some records then it will return non zero number .
if (cursor.getCount() != 0)
{
// Here if condition check wheather the cursor move to first record or not
// If it moves to first record then it will return true.
if (cursor.moveToFirst())
{
do
{
arrlst.add(cursor.getInt(cursor.getColumnIndex("your_field_in_database")).trim());
}while (cursor.moveToNext());
}
}
cursor.close();
db.closeDatabase();
lst_stu.setAdapter((ListAdapter) arrlst);
}
catch(Exception e)
{
e.printStackTrace();
}

Categories

Resources