I need help for getting SQLite data - android

I use this method for retrieving my data
public String getdata() {
String[] columns= new String[]{RowId,RowBusinessName};
Cursor c=OurDatabase.query(TableName,columns,null,null,null,null,null);
String Result="";
int iRowId=c.getColumnIndex(RowId);
int iRowBusinessName=c.getColumnIndex(RowBusinessName);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
Result=Result+c.getString(iRowBusinessName)+"\n";
}
return Result;
}
How can I make it return structured data (id & business_name)?
I want to display every business_name in a single textview.
Please help

If I understand what you are trying to do, here is the solution if you want to get only 1 RowBusinessName returned as a String. (Hoping that your RowBusinessName is type String).
public String getdata(int rowId) {
String[] columns= new String[]{RowId,RowBusinessName};
Cursor cursor = db.query(TABLENAME, columns, RowId + "=?", new String[]{rowId + ""}, null, null, null, null);
String Result="";
if (cursor != null && cursor.moveToFirst()) {
// not required though
int rowId = cursor.getInt(cursor.getColumnIndexOrThrow(RowId));
String rowBusinessName = cursor.getString(cursor.getColumnIndexOrThrow(RowBusinessName));
result = rowBusinessName;
}
return result;
}
Now if you want a list of RowBusinessName, then you have to build a List<String> rather than appending it to Result. That's not really a good way!
public List<String> getAll() {
List<String> businessNameList = new ArrayList<String>();
String[] columns= new String[]{RowId,RowBusinessName};
Cursor c=OurDatabase.query(TableName,columns,null,null,null,null,null);
if (c != null && c.moveToFirst()) {
// loop until the end of Cursor and add each entry to Ticks ArrayList.
do {
String businessName = cursor.getString(cursor.getColumnIndexOrThrow(RowBusinessName));
if (businessName != null) {
businessNameList.add(businessName);
}
} while (c.moveToNext());
}
return businessNameList;
}
These are work around.
The appropriate answer would be to create an Object that holds id and businessName. That way, you build an object from DB and just return the entire Object.

Related

select from db in sqlite database

what is wrong with this code
when i run it the program don,t response
public Cursor checkauth(String username,String password)
{
Ecommerce=getReadableDatabase();
// Cursor curser =Ecommerce.rawQuery("select * from customer where username = ? and password =?", new String []{username,password});
//String [] details={"id","custname","gender"};
Cursor c = Ecommerce.rawQuery("select id from customer where username = ? AND password = ?" , new String[] {username,password });
//Cursor cursor = Ecommerce.query(true, "customer",details,"username = ? AND password = ?", new String[] { username, password },null, null, null, null, null);
while(c != null)
{
c.moveToFirst();
}
return c;
}
in activity
public void onClick(View arg0) {
// TODO Auto-generated method stub
user_name=username.getText().toString();
passwords=password.getText().toString();
Cursor c=data.checkauth(user_name, passwords);
while(!c.isAfterLast())
{
username.setText(String.valueOf(c.getInt(0)));
c.moveToNext();
}
}
![enter image description here][1]
You're blocking your UI thread.
This loop never completes:
while(c != null)
{
c.moveToFirst();
}
The while condition is always true. The loop doesn't seem to be doing anything useful, you can probably just leave a plain c.moveToFirst() there.
Try with this..
String selectQuery = "Write select query" ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
boolean result = false;
if (cursor.moveToFirst())
{
do
{
result = true;
} while (cursor.moveToNext());
}
else
{
result = false;
}
Even though this question is answered already, I'd like to suggest a simple improvement. What you're doing is kind of useless. Your goal is to know whether or not a user exists and what his or her id is.
public int checkAuth(String username, String password) {
String sql = "select id from customer where username = ? AND password = ?";
Ecommerce = getReadableDatabase(); //field names never start with uppercase
Cursor c;
try {
c = Ecommerce.rawQuery(sql, new String[] { username, password });
if (c.moveToFirst()) //if the cursor has any records, this returns true, else false
return c.getInt(0); //so if a user exists with given params, we can return an id
else
return -1; //if not, we return -1, which means: user/pass-combination not found
}
finally { //but after the whole method, we need to do some things:
if (c != null && !c.isClosed())
c.close(); //close the cursor
closeDatabase(); //and close the database
}
}
This way you keep your UI code separated from your database code. A cursor shouldn't appear in UI-code. Which above modifications, the UI code looks a lot cleaner
int i = data.checkAuth(username, password);
if (i == -1) {
//alert of some kind
}
else
username.setText(String.valueOf(i));

How to retrieve whole Row of data in Sqlite

I want to retrieve a whole row at a time in sqlite database. All of them are strings. I wrote a method.
If anyone could check the error of this.
Thanks
public ArrayList<Integer> queueAll_row(){
String[] columns = new String[]{Key_row_ID,Key_Customer_name,Key_customer_nic,Key_roof,Key_floor,Key_walls,Key_toilets,Key_No_Rooms,Key_electricity,Key_drinkingWater,Key_status,Key_ownership
,Key_hvBankAcc,Key_loansOfOtherBnks,Key_current_No_Emp,Key_new_Emp,Key_income_source1,Key_income_source2,Key_income_source3};
Cursor cursor = ourDb.query(DB_Table, columns,
null, null, null, null, null);
ArrayList<Integer> values = new ArrayList<Integer>();
cursor.moveToFirst();
while (cursor.moveToNext()) {
values.add(cursor.getInt(0));
}
return values;
}
Please try this, I hope its help you.
public ArrayList<ProjectModel> getprojectName() {
ArrayList<ProjectModel> values = new ArrayList<ProjectModel>();
String query = "SELECT * from project";
cursor = sqLiteDatabase.rawQuery(query, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
values.add(new ProjectModel(cursor.getString(cursor
.getColumnIndex("project_id")), cursor
.getString(cursor.getColumnIndex("project_name"))));
} while (cursor.moveToNext());
}
}
return values;
}
model class
public class ProjectModel {
private String project_id;
private String project_name;
public ProjectModel(String project_id, String project_name) {
super();
this.project_id = project_id;
this.project_name = project_name;
}
public String getProject_id() {
return project_id;
}
public String getProject_name() {
return project_name;
}
You may run a raw query also to get whole row from a table in database..
you may try this code.. hope it will work for you.
public ArrayList<Integer> queueAll_row() {
String query = "select * from " + DB_Table;
Cursor cursor = ourDb.rawQuery(query, null);
ArrayList<Integer> values = new ArrayList<Integer>();
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
while (cursor.moveToNext()) {
values.add(cursor.getInt(0));
}
}
return values;
}
Steps:-
1.To store all value from single row you have to use model class
2.add following code
public ArrayList queueAllRow(){
String query = "select * from "+DB_Table;
Cursor cursor = ourDb.rawQuery(query, null);
ArrayList<ModelClass> values = new ArrayList<ModelClass>();
if(cursor.moveToFirst()){
do {
ModelClass ob1=new ModelClass();
ob1.setvalue(cursor.getString(cursor.getColumnIndex("COL_NAME")));
//set the values to other data members, same like above
values.add(ob1);
} while (cursor.moveToNext());
}
return values;
}

Closing cursors across JAR boundaries

I use a content provider/resolver, have a separate project/lib that provides a number of DB helper methods. I have a second project/lib that does handy things with a cursor.
Imagine as such DB Helper Method (com.example.DBHelper):
public String[] dumpColumnTable() {
Cursor cursor = cr.query(MY_URI,
new String[] { FIELD },
null,
null,
null
);
return UtilMethods.createArrayFromCursor(cursor);
}
Then the Util methods (com.example.UtilMethods):
public static String[] createArrayFromCursor(Cursor cursor) {
return createArrayFromCursor(cursor, 0);
}
public static String[] createArrayFromCursor(Cursor cursor, int column) {
if (cursor == null) return null;
String[] strings = new String[cursor.getCount()];
if (cursor.moveToFirst()) {
int i=0;
do {
strings[i] = cursor.getString(column);
i++;
} while (cursor.moveToNext());
}
return strings;
}
Obviously the cursor isn't closed. This will leak a cursor. Logcat will give you that message.
SO, close it in the inner util function:
public static String[] createArrayFromCursor(Cursor cursor, int column) {
if (cursor == null) return null;
String[] strings = new String[cursor.getCount()];
if (cursor.moveToFirst()) {
int i=0;
do {
strings[i] = cursor.getString(column);
i++;
} while (cursor.moveToNext());
}
cursor.close();
return strings;
}
But logcat will still claim the cursor wasn't closed before finalize.
If instead, in the DB Helper method, I save the return value, close the cursor, then return it, I get no cursor leak/logcat message:
public String[] dumpColumnTable() {
Cursor cursor = cr.query(MY_URI,
new String[] { FIELD },
null,
null,
null
);
String[] toret = UtilMethods.createArrayFromCursor(cursor);
cursor.close();
return toret;
}
Why ? In debugging, the cursor is marked as close when the calls return. The call stack goes from my activity->db helper->util methods. The db helper and util methods are in separate projects from the activity.
Is there some pass by reference/value issue I'm missing, or crossing multiple JAR boundaries, or the casting of what is a SQLiteCursor to the generic Cursor type that I'm missing ?

Getting data from sqlite on android is really slow

I have this code:
DatabaseHandler db = new DatabaseHandler(this);
System.out.println("Start - " + System.currentTimeMillis());
for (int i = 1; i < db.getChampsCount() + 1; i++) {
String name = db.getChampInfo(i, "name");
String title = db.getChampInfo(i, "title");
String thumb = db.getChampInfo(i, "thumb");
System.out.println("End - " + System.currentTimeMillis());
[...]
}
and this
String getChampInfo(int id, String col) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT " + col + " FROM champions WHERE id = " + id, new String[] {});
if (cursor != null)
cursor.moveToFirst();
db.close();
return cursor.getString(0);
}
Which is a part of DatabaseHelper class
And it works ok, but the problem is it takes way too long to execute (2089ms on my android phone). Those strings are a part of the UI so I don't think I can put that in another thread. What can i do to make this code run faster?
Edit: there are exactly 110 rows
Instead of individual statement, should you not use Single sql statement ?
Just create one ArrayList which will store all the required value in the Activity class.
e.g: ArrayList<String> myData;
Now in database helper class make one function like below:
// TO get All Data of datanase which you want
public ArrayList<String> getAllData() {
ArrayList<String> subTitleList = null;
Cursor cursor = null;
try {
String queryString = "SELECT * FROM champions";
cursor = db.rawQuery(queryString, null);
if (cursor != null && cursor.moveToFirst()) {
subTitleList = new ArrayList<String>();
do {
String nextUser = new String(cursor.getString(cursor.getColumnIndex("name")));
String nextUser = new String(cursor.getString(cursor.getColumnIndex("title")));
String nextUser = new String(cursor.getString(cursor.getColumnIndex("thumb")));
subTitleList.add(nextUser);
}
while (cursor.moveToNext());
System.out.println("it comes in SubTitleList");
}
}
catch (Exception e) {
e.printStackTrace();
subTitleList = null;
}
finally {
if (cursor != null && !cursor.isClosed()) {
cursor.deactivate();
cursor.close();
cursor = null;
}
if(db != null){
db.close();
}
}
//System.out.println("SubTitleList is: "+subTitleList);
return subTitleList;
}
And now in your activity class you can call this function and get all the required data from the myData ArrayList.
myData = db.getAllData(); // i think there is no need of any ID if you are fetching all the data.
Hope you got my point.
You can definitely run those in an AsyncTask. All you have to do is pass the data into the task's parameters or if you cant figure that out just make your task have a constructor that takes the parameters and call it like this:
MyAsync ma = new MyAsync(stuff, stuff, stuff);
ma.execute();
In the task's onPostExecute() is where you can grab the data from your queries that ran in the background and then you can update the UI.
Also the other guys are kind of right. If you can combine your queries that would be best but with a table like that its not really going to give you much of a performance boost, at least I don't think.

Get all rows from SQLite

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

Categories

Resources