This is about Android and SQLite database.
Simply, I want to know, how can I assign value to variable that get from the Database table?
I have table called wish and colmns are date[date value string], phoneno[phone no string] and wishtype[simply a string].
All I want is get phoneno, and wishtype according to usergiven date[input to the query will be the date] and assign those two into seperate variable.
I tried out so many methods, but it gives me a runtime errors.
String phone_no;
String wish_type;
Cursor c = getContentResolver().query(your_table_uri,
new String[] {"_id", "phone_no", "wish_type", "date" /*these are your column names*/},
"date=?", your_date_filter, null);
if(c.moveToFirst()) { // checks if c retrieves anything. you may want to check first if c!=null
phone_no = c.getString(c.getColumnIndex("phone_no"));
wish_type = c.getString(c.getColumnIndex("wish_type"));
}
Related
I would like to create something like a dynamic where clause but struggle with it.
FrameWork:
I want to use 4 Togglebuttons, which obviously return me with "Togglebutton.ischecked()" a true or false boolean. According to that I want to choose the correct courser of my database.
The Togglebuttons have the values "Basic","Common","Uncommon" and "Rare".
If a Togglebuttons is pressed it calls the DB Method which than yields to setting up my layout with the data of the Database.
Issue: I have problems creating a correct Query which changes the whereArguments and whereClause accordingly. From my Understanding the whereClause needs a String and the whereSelection needs a StringArray.
What I tried:
I tried creating a StringArray accordingly, which yields the problem of having a fixed index. Therefore I had issues with creating a smart logic, which yields the correct StringArray,
e.g. if ToggleButton (tb) tbBasic = true, tbUncommon = false, tbCommon = true, tbRare = true, I would need something like String[] whereArgs = new String[] {"Basic","Common","Rare"} whereas I can not create that accordingly with a something like a "add" method.
Therefore I tried using an Arraylist which makes adding and deleting according to the toggles very easy.
E.g. if my DBHelper method getAllHeros is called I can create a new Arraylist each time which yields me the correct whereArgs.
ArrayList<String> whereArgsList = new ArrayList<>();
if(btnBasic){
whereArgsList.add("Basic");
}
if(btnCommon){
whereArgsList.add("Common");
}
if(btnUncommon){
whereArgsList.add("Uncommon");
}
if(btnRare){
whereArgsList.add("Rare");
}
Cursor c = db.query("TableHeros", null,whereClause, whereArgsList.toArray(new String[0]),null,null,null,null);
The Issue with that is that obviously the whereClause has to be updated accordingly aswell. So in a Case of the Arraylist being longer than one Element the whereClause would need the same amount of elements aswell.
I hope I made my point clear and I am open to try any Suggestions
You haven't specified what the WHERE clause should look like. However assuming that:
a) the buttons all apply to a single column (COL_TASK_TITLE (which equates to the String title) is used in the code below) and
b) that should multiple buttons be true that you want to select rows that contain both values and
c) also assuming that if none are selected that you want all rows then the following might be along the lines of what you want
:-
public Cursor getMyRows(boolean btnBasic, boolean btnCommon, boolean btnUncommon, boolean btnRare) {
ArrayList<String> whereArgsList = new ArrayList<>();
String whereclause = null;
String[] whereargs = null;
if(btnBasic){
whereArgsList.add("Basic");
}
if(btnCommon){
whereArgsList.add("Common");
}
if(btnUncommon){
whereArgsList.add("Uncommon");
}
if(btnRare){
whereArgsList.add("Rare");
}
StringBuilder whereclauseToBe = new StringBuilder();
for(String s: whereArgsList) {
if (whereclauseToBe.length() > 1) {
whereclauseToBe.append(" OR ");
}
whereclauseToBe.append(COL_TASK_TITLE); //<<<<<<<<< change to your column
whereclauseToBe.append(" = ? ");
}
if (whereclauseToBe.length() < 1) {
Log.d("WHERE CLAUSE","No selections so WHERE CLAUSE and WHERE ARGS have been set as null");
} else {
whereclause = whereclauseToBe.toString();
Log.d("WHERE CLAUSE ", "The generated WHERE CLAUSE would be... WHERE " + whereclauseToBe.toString());
}
if (whereArgsList.size() > 0) {
whereargs = new String[whereArgsList.size()];
whereargs = whereArgsList.toArray(whereargs);
}
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.query(TABLE, null,whereclause, whereargs ,null,null,null,null); //<<<<<<<<<< Change TABLE to table name
return c; //<<<<<<<<<< Could just do `return db.query(TABLE.........`
}
Note this is a method within a subclass of SQLiteOpenHelper aka the Database Helper.
The above was tested using (from an activity) :-
db.getMyRows(false,false,false,false);
db.getMyRows(true,false,false,false);
db.getMyRows(true,false,true,false);
db.getMyRows(false,true,true,false);
db.getMyRows(false,false,false,true);
db.getMyRows(true,true,true,true);
The results written to the log were :-
10-22 04:44:23.975 1429-1429/? D/WHERE CLAUSE: No selections so WHERE CLAUSE and WHERE ARGS have been set as null
10-22 04:44:23.975 1429-1429/? D/WHERE CLAUSE: The generated WHERE CLAUSE would be... WHERE title = ?
10-22 04:44:23.975 1429-1429/? D/WHERE CLAUSE: The generated WHERE CLAUSE would be... WHERE title = ? OR title = ?
10-22 04:44:23.975 1429-1429/? D/WHERE CLAUSE: The generated WHERE CLAUSE would be... WHERE title = ? OR title = ?
10-22 04:44:23.975 1429-1429/? D/WHERE CLAUSE: The generated WHERE CLAUSE would be... WHERE title = ?
10-22 04:44:23.975 1429-1429/? D/WHERE CLAUSE: The generated WHERE CLAUSE would be... WHERE title = ? OR title = ? OR title = ? OR title = ?
Note TABLE and COL_TASK_TITLE were from a table and would need to be changed.
I have an app that inserts data into a database with 2 tables (project and alvara)
The insertion method for the second table depends on what type the first table gets. (1 or 2) for resumed idea.
This is a method that I made for looking into the second table with cursor. If it finds, it sets in setters from alvara_db class. And later on, I use getters to show info on textviews in another activity. The issue is that it's not setting info at all. Is anything wrong in my Cursor?
Thanks in advance!
public ArrayList<alvara_db> getAlvaras(){
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<alvara_db> projects = new ArrayList<>();
String[] project = new String[]{String.valueOf(tipoprojetoid)};
Cursor cur = db.rawQuery("SELECT placa, proj_exec, resp_tec, rtnum, parecer FROM alvara WHERE projetoid = ?", project);
cur.moveToFirst();
alvara_db alvaras = new alvara_db();
alvaras.setPlaca(cur.getInt(cur.getColumnIndex("placa")));
alvaras.setProj_exec(cur.getInt(cur.getColumnIndex("proj_exec")));
alvaras.setResp_tec(cur.getString(cur.getColumnIndex("resp_tec")));
alvaras.setRtnum(cur.getInt(cur.getColumnIndex("rtnum")));
alvaras.setParecer(cur.getString(cur.getColumnIndex("parecer")));
projects.add(alvaras);
return projects;
}
Fragment where I call getAlvaras method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detalhes_projeto_alvara);
db.getAlvaras();
placa = alvaras.getPlaca();
resp_tec = alvaras.getResp_tec();
proj_exec = alvaras.getProj_exec();
rtnum = alvaras.getRtnum();
}
You are not using the returned value from db.getAlvaras().
Instead the alvaras variable in your second snippet is something that is likely not initialized - the code you posted does not show that exactly.
(In addition, you might want to check the return value of moveToFirst() in case the query matches no rows, and add a do-while loop to retrieve more than one row.)
I have a phone number with country code like +91XXXXXXXXXX. and a phone number in my android contacts database is in the form of XX XX XXXXXX. How to compare them in sqlite database query.
Any help would be appreciable....
I need this to update or delete the existing phone number in android database.
Note
Phone number can be of any country. Above is just the example.
you can try the code below
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode("Pass phone number here"));
Cursor c = getContentResolver().query(uri, new String[]{PhoneLookup.NUMBER}, null, null, null);
if(c.getCount()>0){
c.moveToFirst();
System.out.println(c.getString(c.getColumnIndex(PhoneLookup.NUMBER)));
}
c.close();
There can be multiple ways to do this:
As you see below here:
String yourInputString = "+91XXXXXXXXXX";
String dbContactString = "XX XX XXXXXX";
both have different format; so we must have to extract substring ("XXXXXXXXXX") from first string and also have to remove whitespaces ("XXXXXXXXXX") from the second string!
yourInputString = yourInputString.substring(2); // 2 is start index and result will be "XXXXXXXXXX"
dbContactString = dbContactString.replaceAll("\\s+",""); // replaces all whitespaces and result will be "XXXXXXXXXX"
now, both have same format so you can easily compare them with equals().
yourInputString.equals(dbContactString) is the way.
It returns true if yourInputString is equals to dbContactString in value. Else, it will return false.
Hope this helps!
Iam trying to find average of a column in my sqlite database.
Here is the code:
public void getAvgMileage(Prediction pd)
{
String [] columns = new String[]{KEY_ROW_ID, KEY_KM, KEY_FUEL_QTY, KEY_FUEL_PRICE, KEY_TOTAL_COST, KEY_MILEAGE, KEY_DATE,KEY_TANK_FULL};
predictionCursor = ourDatabase.rawQuery("SELECT AVG(_mileage) FROM fuel_table WHERE _mileage IS NOT NULL ORDER BY _id DESC LIMIT 5", null);
predictionCursor.moveToFirst();
if(predictionCursor!=null && predictionCursor.getCount()>0)
{
predictionCursor.moveToLast();
findAvgMileage = (Double.valueOf(predictionCursor.toString()));
pd.setpredictionMileage(findAvgMileage);
}
}
But Iam geting a NullPointerException.
Any help??
Thank you.
It doesn't look like you are getting the value out of the cursor for your SQL recordset
This line:
findAvgMileage = (Double.valueOf(predictionCursor.toString()));
looks like it's trying to take a double value of the tostring() of the actual cursor - which I don't think is going to usable or at least not parseable to Double. The return of Cursor.toString() may well be a null value.
replace the line with the following:
findAvgMileage = predictionCursor.getDouble(0);
This new line will fetch out the value in the first column of the current position of the curosr which in your SQL should be the average value you want.
I m working on an e-learning type of an application where i retrieve the data from the database on list.
It works fine on the emulator,but when i use the APK file of that app on real device,it does not show any data on list, my database is stored in the windows-file explorer-package-data-database-table_name.
I am referring to this site
http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from-a-sqlite-database-in-android/
Here's a snippet of my code using database
list_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, namelist1());
list1.setAdapter(list_adapter);
}
public List<String> namelist1()
{
// We have to return a List which contains only String values. Lets create a List first
List<String> namelist= new ArrayList<String>();
// First we need to make contact with the database we have created using the DbHelper class
Database_helper_class open_database_helper= new Database_helper_class(this);
// Then we need to get a readable database
SQLiteDatabase sqlitedatabase = open_database_helper.getReadableDatabase();
// We need a a guy to read the database query. Cursor interface will do it for us
//(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Cursor cursor =sqlitedatabase.query(open_database_helper.TABLE_E_LEARNING,null,null,null,null,null,null);
//above query is read all the database column
// Cursor object read all the fields. So we make sure to check it will not miss any by looping through a while loop
while(cursor.moveToNext()){
String str_name = cursor.getString(cursor.getColumnIndex(Database_helper_class.QUES_COLUMN));
String str_id = cursor.getString(cursor.getColumnIndex(Database_helper_class.ANS_COLUMN));
//double str_gpa = cursor.getDouble(cursor.getColumnIndex(Database_helper_class.GPA_COLUMN));
// Finish reading one raw, now we have to pass them to the POJO
nameclass nameclassobj1=new nameclass();
nameclassobj1.setname(str_name);
nameclassobj1.setid(str_id);
//nameclassobj1.setgpa(str_gpa);
// Lets pass that POJO to our ArrayList which contains undergraduates as type
pojo_namelist.add(nameclassobj1);
// But we need a List of String to display in the ListView also.
//That is why we create "nameList"
namelist.add(str_name);
}
sqlitedatabase.close();
sqlitedatabase.query() returns a cursor which is positioned before the first record. make sure to call moveToFirst() before trying to access any data from it.
verify your database path in DBHelper.class. And after that Write below line before you call while loop.
cursor.moveToFirst();
This will point to your first record and then your while loop will work.
Try it like this:
// Cursor object read all the fields. So we make sure to check it will not miss any by looping through a while loop
cursor.moveToFirst();
while(!cursor.isAfterLast()){
String str_name = cursor.getString(cursor.getColumnIndex(Database_helper_class.QUES_COLUMN));
String str_id = cursor.getString(cursor.getColumnIndex(Database_helper_class.ANS_COLUMN));
//double str_gpa = cursor.getDouble(cursor.getColumnIndex(Database_helper_class.GPA_COLUMN));
// Finish reading one raw, now we have to pass them to the POJO
nameclass nameclassobj1=new nameclass();
nameclassobj1.setname(str_name);
nameclassobj1.setid(str_id);
//nameclassobj1.setgpa(str_gpa);
// Lets pass that POJO to our ArrayList which contains undergraduates as type
pojo_namelist.add(nameclassobj1);
// But we need a List of String to display in the ListView also.
//That is why we create "nameList"
namelist.add(str_name);
}
Use the isAfterLast()-method to check, if your reached the end of your cursor.
Sorry for late reply, got busy in other application
Actually the data was not saved in the database, that is why i was not getting it on device.
It works now.