Disabling button and storing in database - android

I am calling same activity for 5, 6 different movies to book ticket. I have used button for seats. I set button disable after clicking and store its id in sql database. Now when I come again to book another ticket for same movie, same show
String[] projection= new String[]{
movieEntry.COLUMN_NAME_SEAT
};
//where clause
String selection=movieEntry.COLUMN_NAME_MN + " =?"+" AND "+movieEntry.COLUMN_NAME_MD +" =?" +" AND "+movieEntry.COLUMN_NAME_MT +" =?" ;
// int i=0;
String colindex=null;
// this query is select seatno from tablename
// where movie_name='movie that user selected' and movie_time='user seklected currently'
//and movie_date='';
//it is working correctly its fetching all records
// i am trying to add all this fetched seatno to the seatsArraylist so that
//we can get it from this arrayList and disable that seats for the user for that particular movie and date and time
// but problem is that it is adding only one records to arraylist
//can you plz go through this code
String[] selectionArgs ={ Movietitle, Datem, Mtiming} ;
try{
Cursor cursor = rdb.query(
movieEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
null
);
if(cursor!= null ) {
int i=0;
while(cursor.moveToFirst())
{
colindex= cursor.getString(i);
seatsArrayList.add(colindex);
i++;
tv1.setText(seatsArrayList.get(2));
}
tv.setText(colindex);
}
/* for(int j=0;j<=seatsArrayList.size();j++)
{
if(seatsArrayList.get(j)=="Seat4")
{
theBtn[3].setEnabled(false);
}
}*/

You are not supposed to iterate in your cursor like that you have just made your cursor to move to the first part (0th). To iterate in a cursor its easy with a for loop like this:
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
// all operations should be here
}
And again even inside the loop the method cursor.getString(int) the int passed is not the index of a cursor but it is a column index. In your table there may be multiple columns the first one is (0th) the second column is (1st). So you should pass column indexes.

Related

Why Sqlite return only last row not all rows data?

I don't know what's wrong with my code I follow the rule but I get wrong result. I want to search db and find all rows data but I only get last row from sqlite. my code to search database is bellow:
public ArrayList<ArrayList<ContractSaveDataFromDB>> ActiveContractData(String phone, String numberId)
{
ArrayList<ContractSaveDataFromDB> UserData = new ArrayList<ContractSaveDataFromDB>();
ArrayList<ArrayList<ContractSaveDataFromDB>> SendUserData =
new ArrayList<ArrayList<ContractSaveDataFromDB>>();
SQLiteDatabase db = this.getReadableDatabase();
String whereClause = "phone = ? AND numberId = ?";
String[] whereArgs = new String[]{
phone,
numberId
};
String orderBy = "activeContract";
Cursor res2=db.query("usersAccount",null,whereClause,whereArgs,null,null,orderBy);
res2.moveToFirst();
do{
UserData.clear();
int index;
ContractSaveDataFromDB contractSaveDataFromDB=new ContractSaveDataFromDB();
index = res2.getColumnIndex("buyAmount");
String buyAmount = res2.getString(index);
contractSaveDataFromDB.setBuyAmount(buyAmount);
UserData.add(contractSaveDataFromDB);
SendUserData.add(UserData);
} while(res2.moveToNext());
res2.close();
db.close();
return SendUserData;
I don't know what's wrong. I appreciate if you help me to solve my problem.
you already added where clause so maybe it is filtering your results try to remove it by change this
Cursor res2=db.query("usersAccount",null,whereClause,whereArgs,null,null,orderBy);
to this
Cursor res2=db.query("usersAccount",null,null,null,null,null,orderBy);
I believe that your issues is that you are trying to use an ArrayList of ArrayList of ContractSaveDataFromDB objects.
I believe that an ArrayList of ContractSaveDataFromDB objects would suffice.
It would also help you if you learnt to do a bit of basic debugging, as an issue could be that you are not extracting multiple rows.
The following is an alternative method that :-
uses the ArrayList of ContractSaveDataFromDB objects,
introduces some debugging by the way of writing some potentially useful information to the log
and is more sound, as it will not crash if no rows are extracted
i.e. if you use moveToFirst and don't check the result (false means the move could not be accomplished) then you would get an error because you are trying to read row -1 (before the first row) as no rows exists in the cursor.
:-
public ArrayList<ContractSaveDataFromDB> ActiveContractData(String phone, String numberId) {
ArrayList<ContractSaveDataFromDB> SendUserData = new ArrayList<ContractSaveDataFromDB>();
SQLiteDatabase db = this.getReadableDatabase();
String whereClause = "phone = ? AND numberId = ?";
String[] whereArgs = new String[]{
phone,
numberId
};
String orderBy = "activeContract";
Cursor res2 = db.query("usersAccount", null, whereClause, whereArgs, null, null, orderBy);
Log.d("RES2 COUNT", "Number of rows in Res2 Cursor is " + String.valueOf(res2.getCount()));
while (res2.moveToNext()) {
ContractSaveDataFromDB current_user_data = new ContractSaveDataFromDB();
current_user_data.setBuyAmount(res2.getString(res2.getColumnIndex("buyAmount")));
Log.d("NEWROW", "Adding data from row " + String.valueOf(res2.getPosition()));
SendUserData.add(current_user_data);
}
res2.close();
db.close();
Log.d("EXTRACTED", "The number of rows from which data was extracted was " + String.valueOf(SendUserData.size()));
return SendUserData;
}
If after running you check the log you should see :-
A line detailing how many rows were extracted from the table
A line for each row (if any were extracted) saying Adding data from row ? (where ? will be the row 0 being the first)
A line saying The number of rows from which data was extracted was ? (? will be the number of elements in the array to be returned)

Complex queries with SQLite in Android

I have a table with 3 columns "ID", "NAME" & "STATUS". I would like to execute a query on my database where I can get only one entry of "ID" which is located at the top row. I have a working sql query,
"SELECT TOP 1 ID from SAMPLE_TABLE WHERE Status='PENDING' ORDER BY ID ASC;"
This is so far what I implemented in android,
// Getting pending items
public int pendingContact() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor mCount = db.query(
TABLE_CONTACTS ,
new String[] { "id" } ,
"status = ?" ,
new String[] { "PENDING" } ,
null ,
null ,
null
);
mCount.moveToFirst();
int count = mCount.getInt(0);
mCount.close();
return count;
}
Al through it gives the desired output but I would like to know if there is any other way of doing this more efficiently.
You can use Limit
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
limit - Limits the number of rows returned by the query, formatted as LIMIT clause. Passing null denotes no LIMIT clause.
You can do this:
Cursor mCount = db.query(TABLE_CONTACTS, new String[] { "id" }, "status = ?", new String[] { "PENDING" }, null, null, "id ASC", "1");
This will keep you from acquiring more data than you need.
When you use ORDER BY, the database will read and sort all PENDING items before it can return the first one.
When using MIN, nothing but the smallest value must be stored temporarily:
SELECT MIN(id) FROM Contacts WHERE Status = 'PENDING'
In code:
Cursor mCount = db.rawQuery("SELECT MIN(id) FROM Contacts WHERE Status = ?",
new String[] { "PENDING" });

Cursor Index Out of Bounds Exception: Index -1 requested with size 0

I am just trying to search for the data in multiple table.If the where condition data is not present in first table(tab1) then it has to search in the second table(tab2) but I am getting the exception showing that
Cursor Index Out of Bounds Exception: Index -1 requested with size 0
Here is my code
SQLiteDatabase db=openOrCreateDatabase("train",SQLiteDatabase.CREATE_IF_NECESSARY, null);
Cursor c1;
String[] table={"tab1","tab2","tab3","tab4"};
int i=0;
do {
c1 = db.rawQuery("select * from '"+table[i]+"' where name='Triplicane'", null);
i++;
} while(c1 == null);
int id1=c1.getInt(0);
String nam1=c1.getString(1);
Toast.makeText(fare.this,"ID no:"+id1, Toast.LENGTH_LONG).show();
Toast.makeText(fare.this,"name"+nam1, Toast.LENGTH_LONG).show();
So from the beginning. Implicitly, each Cursor is positioned before first row so if you want to work with it you need to call
cursor.moveToFirst()
that moves Cursor to first row if is not empty and then is ready for work. If Cursor is empty simply it returns false. So how i mentioned now this method is very handy indicator whether your Cursor is valid or not.
And as my recommendation i suggest you to change your code because i think is broken and it sounds like "spaghetti code"
Cursor c = null;
String[] tables = {"tab1", "tab2", "tab3", "tab4"};
for (String table: tables) {
String query = "select * from '" + table + "' where name = 'Triplicane'";
c = db.rawQuery(query, null);
if (c != null) {
if (c.moveToFirst()) { // if Cursor is not empty
int id = c.getInt(0);
String name = c.getString(1);
Toast.makeText(fare.this, "ID: " + id, Toast.LENGTH_LONG).show();
Toast.makeText(fare.this, "Name: " + name, Toast.LENGTH_LONG).show();
}
else {
// Cursor is empty
}
}
else {
// Cursor is null
}
}
Notes:
Now i want to tell you some suggestions:
An usage of parametrized statements is very good practise so in a
future if you will work with statements, use placeholders in them. Then your statements becomes more human-readable, safer(SQL Injection) and faster.
It's also a very good practise to create static final fields that will hold
your column names, table names etc. and to use
getColumnIndex(<columnName>) method to avoid "typo errors" which are looking for very bad.
Your Cursor flag to empty row , On Sqlite cursor pointed to row number -1 ,
then if you use c.moveNext() or c.moveToFirst() you'll be able to read rows "row by row "
write cursor.movetoFirst() before getting data from cursor.

Select multiple rows at a table and insert to an array

I have a table called food. I am selecting the "category" of the food item and I want to show it in a List View. This is the code I tried.
Cursor c = db.query(DATABASE_TABLE,
new String[] { "category" }, null, null, null, null, null);
ArrayList<ArrayList<String>> results = new ArrayList<ArrayList<String>>();
if(c.moveToFirst())
{
do
{ ArrayList<String> recipe = new ArrayList<String>();
recipe.add(c.getString(1));
recipe.add(c.getString(2));
recipe.add(c.getString(3));
recipe.add(c.getString(4));
results.add(recipe);
}while(c.moveToNext());
if(c != null && !c.isClosed())
c.close();
}
Try Now,
Cursor c = db.query(DATABASE_TABLE,
new String[] { "category" }, null, null, null, null, null);
ArrayList<String> results = new ArrayList<String>();
if(c.moveToFirst())
{
do
{
results.add(c.getString(0)); // instead of 0 Index of Category column in your case
}while(c.moveToNext());
if(c != null && !c.isClosed())
c.close();
}
From your database query You are selecting only category column so you have only one column result in cursor and its start with 0 index. So c.getString(1) to c.getString(4) is meaning less. If your select all data from table then only you get all columns..
I see your problem, you are only returning one column (category), yet you are trying to access several different ones.
You should be returning at least five (since you are trying to access up to 4 and the cursor columns start at 0).
If you are trying to pull a list of items with a certain category you need to change your query. Somethign like this :
String query = "SELECT * FROM " + DATABASE_TABLE + " WHERE category = " + category;
return mDb.rawQuery(query, null);
That will select all items that have a category matching whatever is contained in the variable category, and return all the coilumns in the row.

how to retrieve particular records from SQLite in android

I need to get data from DB & displayed it as list with pagination.
i.e. If i retrieved 4 items..i need to display first 2 items in first page.
When i click next button.,remaining 2 items should be displayed which replaces old 2.
How could i restrict data from DB as 2 like that?
My code..
db.open();
// db.insertTitle("Money");
//db.insertTitle("make");
//db.insertTitle("make");
//db.insertTitle("make");
Cursor c = db.getAllTitles();
if (c.moveToFirst())
{
do {
String firstName = c.getString(c.getColumnIndex("user"));
results.add( firstName );
} while (c.moveToNext());
}
setListAdapter(new ArrayAdapter<String>(DisplayAll.this, android.R.layout.simple_list_item_1,results));
db.close();
}
My DBAdapter..
public Cursor getAllTitles()
{
return db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_USER,
},
null,
null,
null,
null,
null);
}
Please try this
public Cursor getAllRecords(int page,int totalRecord)
{
return db.rawQuery("select * from your_table_name limit "+(page-1)*totalRecord+","+totalRecord, null);
}
Where limit = how many record you want at a time if you want 2 record then pass limit = 2 if 10 record then set limit = 10..
and page = first initial page variable with 1 and when second time you fetch next record increase your page variable by 1 .

Categories

Resources