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.
Related
I'm trying to get the value or data from the array that doesn't exists in the database.
public Cursor checkExistence(){
Cursor c=null;
String[] values={"headache","cold"};
SQLiteDatabase db= getReadableDatabase();
String query="SELECT * FROM "+TABLE_SYMPTOMS+" WHERE "+COLUMN_SYMP+" IN ("+toArrayRep(values)+")";
c=db.rawQuery(query,null);
Log.i("From Cursor","Cursor Count : " + c.getCount());
if(c.getCount()>0){
String val= c.getString()
Log.i("From Cursor","No insertion");
}else{
Log.i("From Cursor","Insertion");
}
db.close();
return c;
}
public static String toArrayRep(String[] in) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < in.length; i++) {
if (i != 0) {
result.append(",");
}
result.append("'" + in[i] + "'");
}
return result.toString();
}
In the String values={"headache","cold"} ,headache exists but cold does not exist in the database. From the code above, the Cursor returns Count=1 which is count>0 hence i can't insert into table.I would like to know how i can independently check whether the individual data exists, and the one which doesn't exist will be inserted into table.So in this case, "Cold" would be able to be inserted into the table.
If you use a single query to check all values, then what you get is a list of existing values, and you still have to search in the original list for any differences.
It is simpler to check each value individually:
String[] values = { "headache", "cold" };
SQLiteDatabase db = getReadableDatabase();
db.beginTransaction();
try {
for (String value : values) {
long count = DatabaseUtils.queryNumEntries(db,
TABLE_SYMPTOMS, COLUMN_SYMP+" = ?", new String[] { value });
if (count == 0) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_SYMP, value);
db.insert(TABLE_SYMPTOMS, null, cv);
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
You need check Cursor.moveToFirst()
True = Have records in cursor.
False = Dont have records.
Example my code:
return database.query( table.getNameTable(),
table.getColumns(),
table.getWhereSelectTableScript(),
null,
table.getGroupBySelectTableScript(),
table.getHavingSelectTableScript(),
table.getOrderBySelectTableScript(),
table.getLimitRecordsSelectTableScript());
See more here !
I have created a Sugar ORM database successfully in my app, I can update, delete and also get all data from a row, but I want a single column data matched with another data...
I mean, I have a registration database with fields: username, password, first_name, last_name, email fields.
After login a user with right username and password, I want THAT User's First_Name in a Textview sent to the Next Activity...
How can I do this? Over last two days I have tried but failed, please help me...
Thanks in advance...
public static List<String> getResultWithRawQuery(String rawQuery, Context mContext) {
List<String> stringList = new ArrayList<>();
if (mContext != null) {
long startTime = System.currentTimeMillis();
SugarDb sugarDb = new SugarDb(mContext);
SQLiteDatabase database = sugarDb.getDB();
try {
Cursor cursor = database.rawQuery(rawQuery, null);
try {
if (cursor.moveToFirst()) {
do {
stringList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
Timber.d(cursor.getString(0), "hi");
} finally {
try {
cursor.close();
} catch (Exception ignore) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("total time query" + totalTime);
}
return stringList;
}
Another example that returns a List of values in the column. Use as such:
String rawQuery = ("SELECT feed_key FROM team_feed_key WHERE team_id = " + mTeam_id + " ORDER BY feed_key DESC");
Did you try to run a raw query like this?
List<Note> notes = Note.findWithQuery(Note.class, "Select * from Note where name = ?", "satya");
from: http://satyan.github.io/sugar/query.html
you can add function to SugarRecord.java forever
public static String Scaler(String Query) {
String Result = "";
SugarDb db = getSugarContext().getSugarDb();
SQLiteDatabase sqLiteDatabase = db.getDB();
SQLiteStatement sqLiteStatament = sqLiteDatabase
.compileStatement(Query);
try {
Result = sqLiteStatament.simpleQueryForString();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqLiteStatament.close();
}
return Result;
}
or
public static String Scaler(String Query) {
String Result = "";
SQLiteDatabase sqLiteDatabase = SugarContext.getSugarContext().getSugarDb().getDB();
SQLiteStatement sqLiteStatament = sqLiteDatabase
.compileStatement(Query);
try {
Result = sqLiteStatament.simpleQueryForString();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqLiteStatament.close();
}
return Result;
}
Scaler("Select First_Name from Note where name ='ali' limit 1");
I had the same problem.
I hope this helps someone:
String firstName = Select.from(User.class).where("EMAIL = "+ user.getEmail()).first().getFirstName();
Hi this must work you can not edit the libraries but you can extend them so check this out:
public class DBUtils extends SugarRecord {
public static <T> List<Object> findByColumn(Context context, String tableName,T ColumnObjectType, String columnName) {
Cursor cursor = new SugarDb(context).getDB().query(tableName, new String[]{columnName}, null, null,
null, null, null, null);
List<Object> objects = new ArrayList<>();
while (cursor.moveToNext()){
if (ColumnObjectType.equals(long.class) || ColumnObjectType.equals(Long.class)) {
objects.add(cursor.getLong(0));
}else if(ColumnObjectType.equals(float.class) || ColumnObjectType.equals(Float.class)){
objects.add(cursor.getFloat(0));
}else if(ColumnObjectType.equals(double.class) || ColumnObjectType.equals(Double.class)){
objects.add(cursor.getDouble(0));
}else if(ColumnObjectType.equals(int.class) || ColumnObjectType.equals(Integer.class)){
objects.add(cursor.getInt(0));
}else if(ColumnObjectType.equals(short.class) || ColumnObjectType.equals(Short.class)){
objects.add(cursor.getShort(0));
}else if(ColumnObjectType.equals(String.class)){
objects.add(cursor.getString(0));
}else{
Log.e("SteveMoretz","Implement other types yourself if you needed!");
}
}
if (objects.isEmpty()) return null;
return objects;
}
}
The usage is simple use DBUtils.findByColumn(...);
Any where you like and from now on you can use only this class instead of SugarRecord and add your own other functions as well.
hint:
ColumnObjectType as the name Suggest tells the type of column like you send Integer.class
I am creating app in which i register user and store user's information in database,so i have created database and storing value in databse but i don't know how to fetch data from database and show in textview?Using below query to fetch data but it has error.What is correct way?
public void insertEntry(String fname, String lname, String gen,String weight)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("firstname", fname);
values.put("lastname", lname);
values.put("gender", gen);
values.put("weight",weight);
}
public Cursor fetchData()
{
SQLiteDatabase mDB = dbHelper.getWritableDatabase();
return mDB.rawQuery("SELECT * FROM Register WHERE firstname=? lastname =?" , null);
}
Using this to set fetched value on textview in different activity
Cursor name = sqliteDataBase.fetchData();
tv_name.setText((CharSequence) name);
Try this,
try {
SQLiteDatabase mDB = dbHelper.getReadableDatabase();
String selectQuery = "SELECT * FROM Register WHERE firstname= "+first+" lastname =" + last + ";";
cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
String firstName = cursor.getString(cursor.getColumnIndex("firstname")));
}
}
} catch(Exception e) {
e.printSTackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
public String fecthResults()
{
String name = null;
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
Cursor cursor = sqLiteDatabase.query(TABLE_NAME, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
name = cursor.getString(cursor.getColumnIndex("firstname")
} while (cursor.moveToNext());
cursor.close();
}
sqLiteDatabase.close();
return name;
Get the name and then set it directly to a texView
A Cursor is an interface that provides random read-write access to the result set returned by the query. It contains multiple rows of data and this data can be easily processed by help of For loop.
Lets take an example to understand the process. Suppose, you need to access data from a column name "col_1" and show the data in TextView. The For loop for the process will be as follows.
for (cursor.moveToNext()) {
textView.setText(cursor.getString(cursor.getColumnIndex("col_1")));
}
Now, if we need only one value (from only one record or tuple) then, we can opt out the For loop and change the code as shown below.
if (cursor.moveToFirst()) {
textView.setText(cursor.getString(cursor.getColumnIndex("col_1")));
}
Always remember to close the cursor after using it.
To close the cursor, use the following line of code.
cursor.close();
For more information, please visit the following links:
https://developer.android.com/reference/android/database/Cursor.html
https://developer.android.com/training/basics/data-storage/databases.html#ReadDbRow
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.
Here I want to store data in ArrayList visible Sections please help me...
Here's my code.
public DataSingleton() {
try {
db = openOrCreateDatabase("/sdcard/Download/Nanhikali_db.db", Context.MODE_PRIVATE, null);
Cursor c = db.rawQuery("select label from nanhikali where level = 1", null);
if (c.moveToFirst()) {
while (c.moveToNext()) {
String lb = c.getString(c.getColumnIndex("label"));
visibleSections.add(lb);
visibleSections = new ArrayList<>();
}
}
}
catch(Exception e)
{
}
Your column string maybe wrong:
Try like this.
if(c.moveToFirst()){
while(c.moveToNext()){
String lb = c.getString(c.getColumnIndex("label"));
visibleSections.add(lb);
}
}
Not "lebel".
You are re assigning the array list every time your loop iterates.
remove visibleSections = new ArrayList<>(); from your loop.
and use While Loop as
while(!cursor.isAfterLast())
{
//get All data here then
cursor.moveToNext();
}