I have a database manager class where i build a table that has two columns. the first column being an integer, and i am trying to write a method that will return all values in that column as a list:
public List<Integer> getAllStyleIDs(){
List<Integer> results = null;
SQLiteDatabase db = this.getReadableDatabase();
// Select All Query
String selectQuery = "select * from " + DBConstants.allStyles;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
results.add(cursor.getInt(0));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return results;
}
but i am getting a null point exception
any ideas?
Your list results is null, then you attempt to add to it. Try this:
List<Integer> results = new ArrayList<Integer>();
First thing: the list hasn't been initialized.
Second thing: using raw queries is not recommended:
Try something like this:
List<Integer> results = new ArrayList<Integer>();
this.database = this.getReadableDatabase();
String [] columns = {_ID}; // name of the column
Cursor cursor = this.database.query(COURSES_TABLE, columns, null, null, null, null, null);
int iId = cursor.getColumnIndex(_ID);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
Integer rowId = cursor.getInt(iName);
results.add(rowId);
}
cursor.close();
this.database.close();
return results;
Related
I have some data from the database that I want to show randomly and only 5 data appear, I've tried using ORDER BY RAND () but the app crashes when I open it
below is my syntax query
public List<Soal> getSoal(){
List<Soal> listSoal = new ArrayList<Soal>();
String query = "select * from tbl_soal ORDER BY RAND() LIMIT 5";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if(cursor.moveToFirst()){
do{
Soal s = new Soal();
s.setSoal(cursor.getString(1));
s.setPil_a(cursor.getString(2));
s.setPil_b(cursor.getString(3));
s.setPil_c(cursor.getString(4));
s.setPil_d(cursor.getString(5));
s.setJwban(cursor.getInt(6));
s.setGambar(cursor.getInt(7));
listSoal.add(s);
}while(cursor.moveToNext());
}
return listSoal;
}
so where is the error, or is there any solution for my problem ?
You can check this answer as well
https://stackoverflow.com/a/23628508/6672577
public List<Soal> getSoal() {
List<Soal> listSoal = new ArrayList<Soal>();
String query = "SELECT * FROM table ORDER BY RANDOM() LIMIT 5";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor != null) { // To check that cursor is not null.
if (cursor.moveToFirst()) {
do {
Soal s = new Soal();
s.setSoal(cursor.getString(1));
s.setPil_a(cursor.getString(2));
s.setPil_b(cursor.getString(3));
s.setPil_c(cursor.getString(4));
s.setPil_d(cursor.getString(5));
s.setJwban(cursor.getInt(6));
s.setGambar(cursor.getInt(7));
listSoal.add(s);
} while (cursor.moveToNext());
}
}
return listSoal;
}
I am using android studio to handle database SQLite.
I need to list all the items in a table as items in a listview..How can i do it.
I know how to get the first item using cursor.moveToFirst() like this
public Rows getRows(){
String query = "SELECT * FROM "+TABLE_NAME;
SQLiteDatabase db = getWritableDatabase();
cursor = db.rawQuery(query,null);
Rows rows;
if(cursor.moveToFirst()){
rows.setcol1(cursor.getString(0));
rows.setcol2(cursor.getString(1));
rows.setcol3(cursor.getString(2));
cursor.close();
}
else{
rows=null;
}
return rows;
}
can i use cursor.moveToNext() if yes please give me the code....
Use like this,
public ArrayList<Rows> getRows(){
String query = "SELECT * FROM "+TABLE_NAME;
SQLiteDatabase db = getWritableDatabase();
cursor = db.rawQuery(query,null);
ArrayList<Rows> list=new ArrayList<Rows>();
while(cursor.moveToNext()){
Rows row=new Rows();
row.setcol1(cursor.getString(0));
row.setcol2(cursor.getString(1));
row.setcol3(cursor.getString(2));
list.add(row);
}
cursor.close();
db.close();
return list;
}
String retq="SELECT * FROM information ";
sql=openOrCreateDatabase("detail.db", MODE_PRIVATE, null);
Cursor c=sql.rawQuery(retq, null);
c.moveToFirst();
do
{
id=c.getInt(0);
String nam=c.getString(1);
String dob=c.getString(2);
String qualification=c.getString(3);
String gender=c.getString(4);
String mariage=c.getString(5);
String experience=c.getString(6);
//Toast.makeText(RetrievedActivity.this, c.getString(1), Toast.LENGTH_SHORT).show();
s=("id:"+id+"\nname:"+nam+"\nDate Of Birth:"+dob+"\nqualification:"+qualification+"\nGender:"+gender+"\nmariage:"+mariage+"\nexperience:"+experience);
alist2.add(s);
adapter = new ArrayAdapter<String>(Retrieve.this, android.R.layout.simple_list_item_1, alist2);
retrieve.setAdapter(adapter);
}while(c.moveToNext());
c.close();
sql.close();
//adapter.notifyDataSetChanged();
}});
I have been trying to get all rows from the SQLite database. But I got only last row from the following codes.
FileChooser class:
public ArrayList<String> readFileFromSQLite() {
fileName = new ArrayList<String>();
fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);
fileSQLiteAdapter.openToRead();
cursor = fileSQLiteAdapter.queueAll();
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
fileName.add(cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1)));
} while (cursor.moveToNext());
}
cursor.close();
}
fileSQLiteAdapter.close();
return fileName;
}
FileSQLiteAdapter class:
public Cursor queueAll() {
String[] columns = new String[] { KEY_ID, KEY_CONTENT1 };
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns, null,
null, null, null, null);
return cursor;
}
Please tell me where is my incorrect. Appreciate.
try:
Cursor cursor = db.rawQuery("select * from table",null);
AND for List<String>:
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(cursor.getColumnIndex(countyname));
list.add(name);
cursor.moveToNext();
}
}
Using Android's built in method
If you want every column and every row, then just pass in null for the SQLiteDatabase column and selection parameters.
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null, null);
More details
The other answers use rawQuery, but you can use Android's built in SQLiteDatabase. The documentation for query says that you can just pass in null to the selection parameter to get all the rows.
selection Passing null will return all rows for the given table.
And while you can also pass in null for the column parameter to get all of the columns (as in the one-liner above), it is better to only return the columns that you need. The documentation says
columns Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
Example
SQLiteDatabase db = mHelper.getReadableDatabase();
String[] columns = {
MyDatabaseHelper.COLUMN_1,
MyDatabaseHelper.COLUMN_2,
MyDatabaseHelper.COLUMN_3};
String selection = null; // this will select all rows
Cursor cursor = db.query(MyDatabaseHelper.MY_TABLE, columns, selection,
null, null, null, null, null);
This is almost the same solution as the others, but I thought it might be good to look at different ways of achieving the same result and explain a little bit:
Probably you have the table name String variable initialized at the time you called the DBHandler so it would be something like;
private static final String MYDATABASE_TABLE = "anyTableName";
Then, wherever you are trying to retrieve all table rows;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + MYDATABASE_TABLE, null);
List<String> fileName = new ArrayList<>();
if (cursor.moveToFirst()){
fileName.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
while(cursor.moveToNext()){
fileName.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
}
}
cursor.close();
db.close();
Honestly, there are many ways about doing this,
I have been looking into the same problem! I think your problem is related to where you identify the variable that you use to populate the ArrayList that you return. If you define it inside the loop, then it will always reference the last row in the table in the database. In order to avoid this, you have to identify it outside the loop:
String name;
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
name = cursor.getString(cursor
.getColumnIndex(countyname));
list.add(name);
cursor.moveToNext();
}
}
Update queueAll() method as below:
public Cursor queueAll() {
String selectQuery = "SELECT * FROM " + MYDATABASE_TABLE;
Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);
return cursor;
}
Update readFileFromSQLite() method as below:
public ArrayList<String> readFileFromSQLite() {
fileName = new ArrayList<String>();
fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);
fileSQLiteAdapter.openToRead();
cursor = fileSQLiteAdapter.queueAll();
if (cursor != null) {
if (cursor.moveToFirst()) {
do
{
String name = cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1));
fileName.add(name);
} while (cursor.moveToNext());
}
cursor.close();
}
fileSQLiteAdapter.close();
return fileName;
}
Cursor cursor = myDb.viewData();
if (cursor.moveToFirst()){
do {
String itemname=cursor.getString(cursor.getColumnIndex(myDb.col_2));
String price=cursor.getString(cursor.getColumnIndex(myDb.col_3));
String quantity=cursor.getString(cursor.getColumnIndex(myDb.col_4));
String table_no=cursor.getString(cursor.getColumnIndex(myDb.col_5));
}while (cursor.moveToNext());
}
cursor.requery();
public List<String> getAllData(String email)
{
db = this.getReadableDatabase();
String[] projection={email};
List<String> list=new ArrayList<>();
Cursor cursor = db.query(TABLE_USER, //Table to query
null, //columns to return
"user_email=?", //columns for the WHERE clause
projection, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null);
// cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(cursor.getColumnIndex("user_id")));
list.add(cursor.getString(cursor.getColumnIndex("user_name")));
list.add(cursor.getString(cursor.getColumnIndex("user_email")));
list.add(cursor.getString(cursor.getColumnIndex("user_password")));
// cursor.moveToNext();
} while (cursor.moveToNext());
}
return list;
}
a concise solution can be used for accessing the cursor rows.
while(cursor.isAfterLast)
{
cursor.getString(0)
cursor.getString(1)
}
These records can be manipulated with a loop
i want to get the value from the cursor without the SimpleCursorAdapter part.here is the code
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_CONTENT1, KEY_CONTENT2,KEY_CONTENT3};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
and the activity side code
cursor = mySQLiteAdapter.queueAll();
from = new String[]{SQLiteAdapter.KEY_ID, SQLiteAdapter.KEY_CONTENT1, SQLiteAdapter.KEY_CONTENT2, SQLiteAdapter.KEY_CONTENT3};
int[] to = new int[]{R.id.id, R.id.text1, R.id.text2,R.id.text3};
cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
while(!cursor.isAfterLast())
{
String tilt = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT1));
String pkg = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT3));
if(tilt.equals("LEFT"))
{
Log.v("LEFT",pkg);
}
else if(tilt.equals("RIGHT"))
{
Log.v("RIGHT",pkg);
}
cursor.moveToNext();
}
i am getting the pkg value correct.but i want to get the values directly from the cursor while removing SimpleCursorAdapter part the code doesn't work.
any help would be appreciated :)
You can get values without declaring adapters. Adapters are need if you want to show the data in the list widgets. So your can be the following:
cursor = mySQLiteAdapter.queueAll();
if (cursor == null) {
//check if there are errors or query just return null
}
if (cursor.moveToFirst()) {
while(!cursor.isAfterLast())
{
String tilt = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT1));
String pkg = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT3));
if(tilt.equals("LEFT"))
{
Log.v("LEFT",pkg);
}
else if(tilt.equals("RIGHT"))
{
Log.v("RIGHT",pkg);
}
cursor.moveToNext();
}
}
First you must count how many rows are in your table. Then assign that count to variable and it use to create an array. For array size you can use that count variable. Then create a for loop and use that count variable for rounds. After create your query and assign values to your arrays. 100% worked!.
int sqlcount;
Cursor mFetch;
SQLiteDatabase mydb = openOrCreateDatabase("your database name", MODE_PRIVATE, null);
mydb.execSQL("create table if not exists customer(name varchar,email varchar)");
Cursor mCount = mydb.rawQuery("select count(*) from customer", null);
mCount.moveToFirst();
sqlcount = mCount.getInt(0);
mCount.close();
String cname[] = new String[sqlcount];
String cemail[] = new String[sqlcount];
for(int i=0;i<sqlcount;i++) {
mFetch= mydb.rawQuery("select name,email from customer", null);
mFetch.moveToPosition(i);
cname[i] = mFetch.getString(0);
cemail[i] = mFetch.getString(1);
}
mFetch.close();
Toast.makeText(MainActivity.this,String.valueOf(cname[0]),Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this,String.valueOf(cemail[1]),Toast.LENGTH_SHORT).show();
I have a table layout that I want to populate with the result from a database query. I use a select all and the query returns four rows of data.
I use this code to populate the TextViews inside the table rows.
Cursor c = null;
c = dh.getAlternative2();
startManagingCursor(c);
// the desired columns to be bound
String[] columns = new String[] {DataHelper.KEY_ALT};
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.name_entry};
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
R.layout.list_example_entry, c, columns, to);
this.setListAdapter(mAdapter);
I want to be able to separate the four different values of KEY_ALT, and choose where they go. I want them to populate four different TextViews instead of one in my example above.
How can I iterate through the resulting cursor?
Cursor objects returned by database queries are positioned before the first entry, therefore iteration can be simplified to:
while (cursor.moveToNext()) {
// Extract data.
}
Reference from SQLiteDatabase.
You can use below code to go through cursor and store them in string array and after you can set them in four textview
String array[] = new String[cursor.getCount()];
i = 0;
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
array[i] = cursor.getString(0);
i++;
cursor.moveToNext();
}
for (boolean hasItem = cursor.moveToFirst(); hasItem; hasItem = cursor.moveToNext()) {
// use cursor to work with current item
}
Iteration can be done in the following manner:
Cursor cur = sampleDB.rawQuery("SELECT * FROM " + Constants.TABLE_NAME, null);
ArrayList temp = new ArrayList();
if (cur != null) {
if (cur.moveToFirst()) {
do {
temp.add(cur.getString(cur.getColumnIndex("Title"))); // "Title" is the field name(column) of the Table
} while (cur.moveToNext());
}
}
Found a very simple way to iterate over a cursor
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
// access the curosr
DatabaseUtils.dumpCurrentRowToString(cursor);
final long id = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
}
I agree to chiranjib, my code is as follow:
if(cursor != null && cursor.getCount() > 0){
cursor.moveToFirst();
do{
//do logic with cursor.
}while(cursor.moveToNext());
}
public void SQLfunction() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"column1","column2" ...};
String sqlTable = "TableName";
String selection = "column1= ?"; //optional
String[] selectionArgs = {Value}; //optional
qb.setTables(sqlTable);
final Cursor c = qb.query(db, sqlSelect, selection, selectionArgs, null, null, null);
if(c !=null && c.moveToFirst()){
do {
//do operations
// example : abcField.setText(c.getString(c.getColumnIndex("ColumnName")))
}
while (c.moveToNext());
}
}
NOTE: to use SQLiteQueryBuilder() you need to add
compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
in your grade file