Android SQLlite Get List of Columns from Empty Table - java

Using Android SQL, I'm trying to get a list of the columns from an SQL table which is empty.
Here is what I have tried so far:
SQLiteDatabase db = getReadableDatabase();
ArrayList<String> output = new ArrayList<String>();
Cursor ti = db.rawQuery("PRAGMA table_info("+myTable+")", null);
if ( ti.moveToFirst() ) {
do {
output.add(ti.getString(1));
} while (ti.moveToNext());
}
ti.close();
db.close();
return output;
The resulting list Appears just the word INTEGER, while the database has many columns. How can I make this work?

this is i use to retrieve column name in string:
SQLiteDatabase mDataBase;
(some code here...)
mDataBase = getReadableDatabase();
Cursor dbCursor = mDataBase.query(TABLE_NAME, null, null, null, null, null, null);
String[] columnNames = dbCursor.getColumnNames();
or this :
Cursor c = db.rawQuery("SELECT * FROM table WHERE 0", null);
try {
String[] columnNames = c.columnNames();
} finally {
c.close();
}

The column name is returned in the column named name:
...
int nameColIdx = ti.getColumnIndexOrThrow("name");
...
output.add(ti.getString(nameColIdx));
...

Related

How can I search all columns of a table in Android Studio using SQL database

I have an Android app with a SQL database that has 4 columns. I would like to search all 4 columns in the database however I can only get 1 to be searched.
I'm not quite sure on how to get it to search all 4 columns.
All 4 Columns are displayed but I can only search one. I can not seem to get it to search all 4 columns.
the code I'm using to get it to search one column is
#SuppressLint("Range")
public List<Data> getDataByVARIETY (String VARIETY) {
variety = VARIETY;
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"VARIETY", "COMMODITY", "PLU", "BOTANICAL"};
String tableName = "data";
qb.setTables(tableName);
//This will query : Select * from Data where Variety %PATTERN%"
Cursor cursor = qb.query(db, sqlSelect, "VARIETY LIKE ?", new String[]{"%" + VARIETY + "%"}, null, null, null);
List<Data> result = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
Data data = new Data();
data.setCOMMODITY(cursor.getString(cursor.getColumnIndex("COMMODITY")));
data.setVARIETY(cursor.getString(cursor.getColumnIndex("VARIETY")));
data.setPLU(cursor.getString(cursor.getColumnIndex("PLU")));
data.setBOTANICAL(cursor.getString(cursor.getColumnIndex("BOTANICAL")));
result.add(data);
} while (cursor.moveToNext());
}
return result;
}
so all i had to do was
change this
qb.setTables(tableName);
//This will query : Select * from Data where Variety %PATTERN%"
Cursor cursor = qb.query(db, sqlSelect, "VARIETY LIKE ?", new String[]{"%" + VARIETY + "%"}, null, null, null);
to this
qb.setTables(tableName);
//This will query : Select * from Data where Variety %PATTERN%"
String conditions = "COMMODITY LIKE ? OR PLU LIKE ? OR VARIETY LIKE ?";
String par;
par = "%"+COMMODITY+"%";
Cursor cursor = db.query(tableName, sqlSelect, conditions, new String[]{par, par, par}, null, null, null);

Android SQLite take the first element from database column

I am working on a project and created a database with SQLite. In my database I have just two columns, column names are r_id and m_id. I want to take the first element of the r_id and assign it in to a string. The elements of the r_id column is like 1, 2, 3.. in this situation my String has to be 1.
My code; creating a db query:
There is no problem I can add data correcly.
my_table = "CREATE TABLE "my_table"("r_id" Text, "m_id" Text);";
db.execSQL(my_table );
Code to take the first element of the column;
public String getSetting() {
String result = "";
String[] columns = {"r_id"};
String[] selectionArgs = {"1"};
String LIMIT = String.valueOf(1); // <-- number of results we want/expect
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.query(true, "r_id", columns, "row", selectionArgs, null, null, null, LIMIT);
if (c.moveToFirst()) {
result = result + c.getString(0);
} else {
result = result + "result not found";
}
c.close();
databaseHelper.close();
return result;
}
The error I am getting:
android.database.sqlite.SQLiteException: no such column: row (code 1 SQLITE_ERROR): , while compiling: SELECT DISTINCT r_id FROM my_table WHERE row LIMIT 1
The 4th argument of query() is the WHERE clause of the query (without the keyword WHERE) and for it you pass "row".
Also, the 2nd argument is the table's name for which you pass "r_id", but the error message does not contain ...FROM r_id... (although it should), so I guess that the code you posted is not your actual code.
So your query (translated in SQL) is:
SELECT DISTINCT r_id FROM my_table WHERE row LIMIT 1
which is invalid.
But you don't need a WHERE clause if you want just the min value of the column r_id.
You can do it with a query like:
SELECT MIN(r_id) AS r_id FROM my_table
without DISTINCT and a WHERE clause.
Or:
SELECT r_id FROM my_table ORDER BY r_id LIMIT 1;
So your java code should be:
public String getSetting() {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT MIN(r_id) AS r_id FROM my_table", null);
String result = c.moveToFirst() ? c.getString(0) : "result not found";
c.close();
databaseHelper.close();
return result;
}
I used rawQuery() here instead of query().
Or:
public String getSetting() {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.query(false, "my_table", new String[] {"r_id"}, null, null, null, null, "r_id", "1");
String result = c.moveToFirst() ? c.getString(0) : "result not found";
c.close();
databaseHelper.close();
return result;
}

Android retrieving phone contacts query takes long time

Hello i am using the next code for retrieving phone contacts name,number and its taked to long.
After littel search i found the the cursor.moveToFirst() command is that one who cuz this .
But i couldent find any solution ): may some one help me please ?
Thanks !
public void loadPhoneMembers(){
ContentResolver cr = this.getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if(cursor.moveToFirst())
{
do
{
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{ id }, null);
while (pCur.moveToNext())
{
String contactNumber=pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String contactName =
pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if(!phonesAdded.contains(contactNumber)){
members.add(contactName+","+contactNumber); // members is arrayList
}
break;
}
pCur.close();
}
} while (cursor.moveToNext()) ;
}
}
You are querying one extra Cursor for each Contact from your first query. You can query the Names and TelephoneNumbers in one query and ignore the Contacts without Telephone number.
String[] projection = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER ,ContactsContract.CommonDataKinds.Phone.PHOTO_URI};
Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,projection, null, null, null);
Also, while (cursor.moveToNext()){
}
has same effect as the following.
if(cursor.moveToFirst())
{
do
{
} while (cursor.moveToNext()) ;

Can't get any data from sqlite db on Android

I have a DB helper that does this function:
public Cursor getCourseNames() throws SQLException {
mDb = mDbHelper.getReadableDatabase();
return mDb.query("Course",null, COURSE_ROWID, null, null, null, null, null);
}
The table it is pulling from looks like this:
private static final String COURSE_ID = "CourseID";
private static final String COURSE_NAME = "Name";
private static final String COURSE_CODE = "CourseCode";
private static final String COURSE_ROWID = "_id";
private static final String COURSE_CREATE =
"create table " +
"Course" + " ( " +
COURSE_ROWID + " integer primary key autoincrement, " +
COURSE_ID + "integer not null," +
COURSE_NAME + "text not null, " +
COURSE_CODE + "text not null" + ");";
In my main activity I try this and get a null pointer...
public void buildCoursetoChapterList(){
Cursor cursor = dbHelper.getCourseNames();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(MainActivity.this, android.R.layout.simple_list_item_1, cursor, null, null);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
Anyone have an idea what my problem is?
I put data into the db earlier on:
if(dbHelper.checkCourseForData() !=null)
{
setContentView(R.layout.classlist);
}
else
{
dbHelper.addFirstClassToDb(course_code, name, course_id);
Log.d+i("Course added to DB", course_code + " " + name + " " + course_id);
}
tried this and still nothing, I want to select all the Name values within Course.
No clue... losing hope.
public Cursor checkCourseForData() throws SQLException {
String[] values = {COURSE_NAME};
Cursor mCursor = mDb.query("Course",values,COURSE_ROWID + "=" + "Name", null, null, null, null, null);
if (mCursor != null) { mCursor.moveToFirst(); }
return mCursor;
}
It should be this
public Cursor getCourseNames() throws SQLException {
String[] values = {COURSE_NAME};
mDb = mDbHelper.getReadableDatabase();
return mDb.query("Course",values,COURSE_ROWID, null, null, null, null, null);
}
Explanation :
the medthod in the api has been defined as
public Cursor query (String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having, String orderBy)
So you need to pass the strings accordingly.
User my example as a reference it works for me
private String name;
private String Events_Table = "events";
private String[] Columns = {"_id", "Name", "Date", "Time_Slot", "Venue", "Details", "EHName", "EHNumber"} ;
private String WhereClause = Columns[1]+"=?" ;
Cursor cursor = db.query(Events_Table, Columns, WhereClause, new String[] {name}, null, null, null);
Consider Reading this
Parameters
table The table name to compile the query against.
columns A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
groupBy A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
having A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
orderBy How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.

Android SQlite column numbers mismatched?

I'm trying to read from a SQLite database using the following code:
public List<DBEntry> getAllDBEntrys() {
List<DBEntry> DBEntrys = new ArrayList<DBEntry>();
Cursor cursor = database.query(DatabaseClass.TABLE_APPTS,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
DBEntry DBEntry = cursorToDBEntry(cursor);
DBEntrys.add(DBEntry);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return DBEntrys;
}
private DBEntry cursorToDBEntry(Cursor cursor) {
DBEntry DBEntry = new DBEntry();
DBEntry.setId(cursor.getLong(0));
DBEntry.setName(cursor.getString(1));
DBEntry.setStartDate(new Date(cursor.getLong(2)));
DBEntry.setDueDate(new Date(cursor.getLong(3)));
DBEntry.SetPriority(cursor.getInt(4));
DBEntry.setDesc(cursor.getString(5));
DBEntry.SetCompletion(cursor.getInt(6)==1?true:false);
return DBEntry;
}
I get this error:
01-23 16:35:23.509: E/CursorWindow(14609): Failed to read row 0, column 6 from a CursorWindow which has 1 rows, 6 columns.
The database already has one entry, as the sqlite3 utility shows:
sqlite> select * from ThingsToDo;
0|asdf|1358847122203|1359192722202|7|abcd|0
sqlite> .schema
CREATE TABLE ThingsToDo( _id integer primary key autoincrement,name text not null,start_date integer,due_date integer,priority integer,description text, completed integer);
CREATE TABLE android_metadata (locale TEXT);
I think the issue is that the _id column is not counted as a column, because the cursor.getColumnCount() function returns 6, not 7 as the sqlite3 utility showed when I moved to file to my PC.
How can I make this work?
public List<DBEntry> getAllDBEntrys()
{
List<DBEntry> DBEntrys = new ArrayList<DBEntry>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_APPTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do
{
DBEntry DBEntry = new DBEntry();
DBEntry .setID(Integer.parseInt(cursor.getString(0)));
DBEntry .setName(cursor.getString(1));
DBEntry .setPhoneNumber(cursor.getString(2));
// Adding to list
DBEntrys .add(DBEntry );
} while (cursor.moveToNext());
}
// return list
return DBEntrys ;
}

Categories