how data will be stored in array sqlite android - android

sqlite query for store all the data in single array.means I have a table where 8 fields are there and I want to retrive all the data in a single array and return array.
Can I do this?
Code from the comment below:
public String[] login1(String email) throws SQLException {
/* Cursor mCursor = db.rawQuery("SELECT * FROM " + TABLE_NAME
+ " WHERE email=? AND password=?",
new String[]{username,res});
*/
try {
/*Cursor c = db.rawQuery("select * from member where email ="
+ "\""+ email.trim() + "\""+" and password="
+ "\""+ res.trim() + "\"", null);
*/
Cursor c = db.rawQuery("Select usermasterid,invalidlogincount,password,"
+ "nextpage,status,user,businessnextpage "
+ "from member where email " + "\""+ email.trim()
+ "\"", null);

There is not enough info in your question, but it should be roughly like this(assuming your data is int):
public int[] getDBRowAsArray() {
int[] myArray = new int[8];
Cursor cursor = yourSQLiteOpenHelper.rawQuery("Your SQL query here", null);
for(int i = 0; i < 8; i++) {
myArray[i] = cursor.getInt(i);
}
return myArray;
}

I assume there are 8 records and not fields in the db.
public String[] getData(){
Cursor c = db.query(args...);
if(c != null && c.moveToFirst()){
int count = c.getCount();
String[] vals = new String[count];
for(int i = 0; i < count; i++){
vals[i] = c.getString(c.getColumnIndex(Table.COLUMN));
c.moveToNext();
}
c.close();
return vals;
}
return null;
}

Related

CursorIndexOutOfBoundsException:

I am new to the android i am trying to get the cursor values related to the particular column value. but it's showing null.
public int getDashBoardCount() {
String countQuery = "SELECT * FROM " + DASHBOARD_TABLE + " WHERE " + VECHICAL_TYPE + " = " + 'c';
From here also i am getting no such column: c (code 1): , while compiling: SELECT * FROM dashboard_table WHERE vehicle_type = c
String countQuery = "SELECT * FROM " + DASHBOARD_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
public DashBoardAvaCapModel getVechicalRelAva(String vechical_type) {
SQLiteDatabase db = null;
Cursor cursor = null;
DashBoardAvaCapModel dash = null;
try {
db = this.getReadableDatabase();
cursor = db.query(DASHBOARD_TABLE, new String[]{_ID,
AVAILABLE, CAPACITY, BOOKED, VECHICAL_TYPE}, VECHICAL_TYPE + "=?",
new String[]{String.valueOf(vechical_type)}, null, null, null, null);
int idkey = cursor
.getColumnIndex(_ID);
int available = cursor
.getColumnIndex(AVAILABLE);
int capactity = cursor
.getColumnIndex(CAPACITY);
int booked = cursor
.getColumnIndex(BOOKED);
int vechicaltype = cursor
.getColumnIndex(VECHICAL_TYPE);
if (cursor != null && cursor.moveToFirst())
dash = new DashBoardAvaCapModel(Long.valueOf(cursor.getString(idkey)),
cursor.getString(available), cursor.getString(capactity), cursor.getString(booked), cursor.getString(vechicaltype));
Log.e("dash", "" + cursor.getString(available));
} catch (final Exception ex) {
String exp = String.valueOf(ex);
Log.e("Databa", "" + exp);
} finally {
cursor.close();
db.close();
}
return dash;
}
After writing this line
cursor = db.query(DASHBOARD_TABLE, new String[]{_ID,
AVAILABLE, CAPACITY, BOOKED, VECHICAL_TYPE}, VECHICAL_TYPE + "=?",
new String[]{String.valueOf(vechical_type)}, null, null, null, null);
pls try to write
cursor.moveToFirst();
For first one you can use like
String countQuery = "SELECT * FROM " + DASHBOARD_TABLE + " WHERE " + VECHICAL_TYPE + " = '" + c + "'"
where c is any variable
Hope this will help you

refresh SQLite database table according to Android spinner

I already did my code based on WIllJBD's suggestion
I want the table refresh the data when its clicked according to spinner, but my toast gave "Database Error". Here is the code for the selected item on spinner
public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
String tam = spDealer.getSelectedItem().toString();
String dealerID = in.getDealID(tam);
String queryrow = in.MatchDealerID(dealerID);
if (queryrow == dealerID)
{
Cursor c = in.getViewInfoBilling(queryrow);
int rows = c.getCount();
int cols = c.getColumnCount();
c.moveToFirst();
for (int i = 0; i < rows; i++) {
TableRow row = new TableRow(this);
row.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
// inner for loop
for (int j = 0; j < cols; j++)
{
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
tv.setText(c.getString(j));
row.addView(tv);
}
c.moveToNext();
mytable.addView(row);
}
in.close();
} else
{
Toast.makeText(Billing.this, "Data Error!!",Toast.LENGTH_LONG).show();
}
}
And here is my method:
public Cursor getViewInfoBilling(String id){
Cursor mcursor = db.rawQuery("SELECT BillDate,SODashboardNo, SODashboardAmount " +
"FROM SODashboard, Bill WHERE SODashboard.SODashboardNo = Bill.TampSODashboardNo " +
"AND SODashboard.DealerID = id", null);
return mcursor;}
public String getDealID(String dealName) throws SQLException{
Cursor mCursor = db.query(Dealer_TABLE, null, ""+Col_DealerName+"=?", new String[]{dealName}, null, null,null);
if(mCursor.getCount()<1){
mCursor.close();
return "Not Exist";
}
mCursor.moveToFirst();
String tampDealID = mCursor.getString(mCursor.getColumnIndex(Col_DealerID));
mCursor.close();
return tampDealID;}
public String MatchDealerID(String tam){
String matchquery = "SELECT DealerID FROM SODashboard, Dealer " +
"WHERE SODashboard.TampDealerIDSOD = tam";
return matchquery;
}
Isnt the ID selected on spinner already same with the ID thats on DB? I already created MatchDealerID and getDealID to compare them.. what should I do make the table refreshes after clicked? Please help me to solve this issue... thank you
There is something wrong in this method.
public Cursor getViewInfoBilling(String id){
Cursor mcursor = db.rawQuery("SELECT BillDate,SODashboardNo, SODashboardAmount " +
"FROM SODashboard, Bill WHERE SODashboard.SODashboardNo = Bill.TampSODashboardNo " +
"AND SODashboard.DealerID =" + id, null);
//OR
/*
Cursor mcursor = db.rawQuery("SELECT BillDate,SODashboardNo, SODashboardAmount " +
"FROM SODashboard, Bill WHERE SODashboard.SODashboardNo = Bill.TampSODashboardNo " +
"AND SODashboard.DealerID =?", new String[] { id });
*/
return mcursor;}
There are two versions , try both , have good luck

Double values for selected contact android

I have a List of contacts with check box.When the user checks the check box i have updated my table field selectedValue with value=1 .Now what i want is i wamna get all the contacts in comma seperated way where selectedValue=1.So for that i have written a query.But my result is not desired.
For eg
I have 4 contacts A,B,C,D in a list.Now if user selects A and C from the list and when i fire that query to get the contacs comma seperated,this is what i get
A,A,C,C
I dont know why 2 values of A and C are comming
Code
public StringBuilder getCheckedContact() {
database = getWritableDatabase();
StringBuilder values = new StringBuilder();
String query = "Select * From " + contactTable + " where " + selectedContact + "=1";
Cursor c = database.rawQuery(query, null);
while (c.moveToNext()) {
for (int i = 0; i < c.getCount(); i++) {
values.append(c.getString(c.getColumnIndexOrThrow(contactName)));
if (i != c.getCount() - 1) {
values.append(",");
}
}
}
c.close();
database.close();
return values;
}
Your while loop loops over the results once, then the for loop loops over the results second time. If you select 4 contacts, you'd get 4*4=16 results.
Why did you add the inner for loop?
This could be rewritten as follows:
public StringBuilder getCheckedContact() {
database = getWritableDatabase();
StringBuilder values = new StringBuilder();
String query = "Select * From " + contactTable + " where " + selectedContact + "=1";
Cursor c = database.rawQuery(query, null);
boolean firstItem = true;
while (c.moveToNext()) {
if(firstItem)
firstItem = false;
else
values.append(",");
values.append(c.getString(c.getColumnIndexOrThrow(contactName)));
}
c.close();
database.close();
return values;
}

Selecting NULL values in Android SQLite

I'm executing the following method with no success beacause of the selectArgs being incorrect (at least this is what I believe.
findAll:
public Collection<Object> findAllByCodigoSetorOrderByStatusWhereDataAgendamentoIsNull(Integer vendedor) {
Collection<Object> objects = null;
String selection = Object.FIELDS[20] + "=?" + " OR " + Object.FIELDS[20] + "=?" + " OR " + Object.FIELDS[20] + "=?" + " AND " + Object.FIELDS[6] + "=?";
String[] selectionArgs = new String[] { "''", "'null'", "NULL", String.valueOf(vendedor) };
Collection<ContentValues> results = findAllObjects(Object.TABLE_NAME, selection, selectionArgs, Object.FIELDS, null, null, Object.FIELDS[4]);
objects = new ArrayList<Object>();
for (ContentValues result : results) {
objects.add(new Object(result));
}
return objects;
}
findAllObjects:
protected Collection<ContentValues> findAllObjects(String table, String selection, String[] selectionArgs, String[] columns, String groupBy, String having, String orderBy) {
Cursor cursor = null;
ContentValues contentValue = null;
Collection<ContentValues> contentValues = null;
try {
db = openRead(this.helper);
if (db != null) {
cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
contentValues = new ArrayList<ContentValues>();
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
contentValue = new ContentValues();
for (int c = 0; c < cursor.getColumnCount(); c++) {
contentValue.put(cursor.getColumnName(c), cursor.getString(c));
}
contentValues.add(contentValue);
cursor.moveToNext();
}
}
return contentValues;
} finally {
close(db);
}
}
How can I correctly select and compare a column to - null, 'null' and '' using the db.query?
Android's database API does not allow to pass NULL values as parameters; it allows only strings.
(This is a horrible design bug. Even worse, SQLiteStatement does allow all types for parameters, but works only for queries that return a single value.)
You have no choice but to change the query string to blah IS NULL.
Old question but i was still stuck on this for a few hours until i found this answer. For whatever reason this strange behaviour (or bug) still exists within the android sdk, if you want to query against null values simply do
SQLiteDatabase db = getReadableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("columnName", newValue);
String nullSelection = "columnName" + " IS NULL";
db.update("tableName", contentValues, nullSelection, null);
db.close();
In this example i am updating values, but it is a similar concept when just selecting values
As mentioned in other answers, for null "IS NULL" need to be used. Here is some convenience code for having both null and strings (I'm using delete in the example but the same can be done for other methods, e.g. query):
public void deleteSomething(String param1, String param2, String param3) {
ArrayList<String> queryParams = new ArrayList<>();
mDb.delete(TABLE_NAME,
COLUMN_A + getNullSafeComparison(param1, queryParams) + "AND " +
COLUMN_B + getNullSafeComparison(param2, queryParams) + "AND " +
COLUMN_C + getNullSafeComparison(param3, queryParams),
queryParams.toArray(new String[0]));
}
private String getNullSafeComparison(String param, List<String> queryParams) {
if (param == null) {
return " IS NULL ";
} else {
queryParams.add(param);
return " = ? ";
}
}
You can bind NULL values to SQLiteStatement:
SQLiteDatabase db = getWritableDatabase();
SQLiteStatement stmt = db.compileStatement("UPDATE table SET " +
"parameter=? WHERE id=?");
if (param == null)
stmt.bindNull(1);
else
stmt.bindString(1, param);
stmt.execute();
stmt.close();
db.close();

Android SQLite Query: Trouble with WHERE clause

Please let me know why my where clause isn't working. I tried using the query instead of rawquery but no luck.
try {
String categoryex = "NAME";
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
MyData = dbHelper.getWritableDatabase();
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + where Category = '+categoryex'" , null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("Category"));
String age = c.getString(c.getColumnIndex("Text_Data"));
results.add( firstName + " Directions: " + age);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (MyData != null)
MyData.execSQL("DELETE FROM " + tableName);
MyData.close();
}
try... (you left out a double-quote before where.
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + " where Category = '" +categoryex + "'" , null);
I think you should use rawQuery in this form:
rawQuery("SELECT * FROM ? where Category = ?", new String[] {tableName, categoryex});
I think it's more secure this way.
Your quotes are buggered:
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + " where Category = '" + categoryex + "'" , null);
You also should read up on SQL injection attacks.
it will be more easy if you use this technique instead of rawQuery,its easy way change your table name, columns and where conditions accordingly.
public ArrayList<Invitees> getGroupMembers(String group_name) {
ArrayList<Invitees> contacts = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {COLUMN_CONTACT, COLUMN_PHONE_NUMBER};
String selection = COLUMN_GROUP_NAME + "=?";
String[] selectionArgs = {group_name};
Cursor cursor = db.query(GROUPS_TABLE_NAME, projection, selection, selectionArgs, null, null, null);
if (cursor.moveToFirst()) {
do {
Invitees invitees = new Invitees();
invitees.setUserName(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_CONTACT)));
invitees.setInviteePhone(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_PHONE_NUMBER)));
contacts.add(invitees);
} while (cursor.moveToNext());
}
return contacts;
}

Categories

Resources