Why does the variable return 0 always? - android

I am trying to retrieve the count from a Sqlite database. But the variable number is always returning zero even if I adda values in the database. can anyone tell me step by step what am I doing wrong. Here is my code.
public int isUserAvailable(Double latitude,Double longitude)
{
int number = 0;
Cursor c = null;
try
{
c = db.rawQuery("select latitude,longitude from savedlocation where latitude = ? and longitude = ? ", new String[] {String.valueOf(latitude),String.valueOf(longitude)});
if(c.getCount() != 0)
number = c.getCount();
}
catch(Exception e) {
e.printStackTrace();
} finally {
if(c!=null) c.close();
}
return number;
}
I think its because I have initialized number=0; so its returning that value. I am not able to access number outside try.

{String.valueOf(latitude),String.valueOf(longitude)} may be the problem
it doesnt happen EVERY time, but sometimes String.valueOf returns an unexpected value
something like u - s - e - r - a - r - r - y
try latitude+"" , longitude+"" to convert them to string.
cursor.moveToFirst should not affect cursor.getCount()
public int isUserAvailable(Double latitude,Double longitude)
{
int number = 0;
Cursor c = null;
try
{
c = db.rawQuery("select latitude,longitude from savedlocation where latitude = ? and longitude = ? ", new String[] {latitude+"",longitude+""});
if(c.getCount() != 0)
number = c.getCount();
}
catch(Exception e) {
e.printStackTrace();
} finally {
if(c!=null) c.close();
}
return number;
}
On a side note, if you want to just get the number of rows that match a query try this:
public int isUserAvailable(Double latitude,Double longitude)
{
int number = 0;
Cursor c = null;
try
{
c = db.rawQuery("select count(*) from savedlocation where latitude = ? and longitude = ? ", new String[] {latitude+"",longitude+""});
if(c.moveToFirst())
number = c.getInt(0);
}
catch(Exception e) {
e.printStackTrace();
} finally {
if(c!=null) c.close();
}
return number;
}

Related

how to fix an "IllegalStateException" error?

I want to ask that why it isn't working so I can better help myself next time. How to fix IllegalStateException error in android studio. I'm getting this error while the data is being retrieved from the database. The error I'm getting is an Illegal State Exception as described below.
Fatal Exception: java.lang.IllegalStateException
Couldn't read row 6023, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
com.navdemo.ui.forms.FormDetailViewModel$10.run
The code, I'm getting this error on is:
private void initScansForForm() {
if (form == null) {
return;
}
final String formId = form.getFormId();
new Thread() {
public void run() {
List<Scan> scans = new ArrayList<>();
Cursor c = db.fetchFormScans(formId);
int id = 0;
while (c.moveToNext()) {
if (!c.isNull(0)){
id = c.getInt(0);
}
else {
Log.d(TAG, "run: "+id);
}
int formId = c.getInt(1);
String scanTime = c.getString(2);
String locationName = c.getString(3);
double latitude = c.getDouble(4);
double longitude = c.getDouble(5);
scans.add(new Scan(id, formId, scanTime, locationName, latitude, longitude));
}
setScans(scans);
}
}.start();
}
public Cursor fetchFormScans(#NonNull String formId) {
return fetchFormScans(Integer.parseInt(formId));
}
public Cursor fetchFormScans(#NonNull String formId) `enter code here`{
return fetchFormScans(Integer.parseInt(formId));
}
Try to check that !cursor.isAfterLast() before doing moveToNext
Kindly make sure that you are getting a number in
String formId = form.getFormId();
As your fetchFormScans() method is parsing string formId to integer so it can be problematic if your formId contains alphabets in it.

How to return all value from a function

I want to return all values of dbManagement.ORIGINATING_ADDRESS from this function but it just gives me last one value to blockedNumber. I know it'll give last one value but how can i get all value. kindly help
public String selectBlockedNumbers() {
Cursor cursor = dbManagement.selectBlockedNumbers();
String blockedNumber = null;
cursor.moveToFirst();
for(int i = 0; i < cursor.getCount(); i++) {
blockedNumber = cursor.getString(cursor.getColumnIndex(dbManagement.ORIGINATING_ADDRESS));
cursor.moveToNext();
}
Toast.makeText(this, blockedNumber, Toast.LENGTH_LONG).show();
return blockedNumber;
}
In
Cursor cursor = dbManagement.selectBlockedNumbers();
the function selectBlockedNumbers() consist of following query:
cursor = db.rawQuery("SELECT " + ORIGINATING_ADDRESS + " FROM " + TABLE_BLOCK_LIST, null);
When the for-loop runs for the last time, blockedNumbers will contain the last number retrieved. So, instead of returning a String, rather returns a List<String>. In that case your code should change into
public List<String> selectBlockedNumbers() {
Cursor cursor = dbManagement.selectBlockedNumbers();
List<String> blockedNumbers = new ArrayList<String>();
cursor.moveToFirst();
for(int i = 0; i < cursor.getCount(); i++) {
String blockedNumber = cursor.getString(cursor.getColumnIndex(dbManagement.ORIGINATING_ADDRESS));
blockedNumbers.add(blockedNumber);
cursor.moveToNext();
}
Toast.makeText(this, blockedNumber, Toast.LENGTH_LONG).show();
return blockedNumbers;
}

Get next value from Cursor in Android

I have Option table which contains number of rows based on Question. So I want to display options in row wise. I also want onClick() event to check whether Option is right or wrong.
My Table is as below: Answer 1 means Right answer, 0 means Wrong answer.
Option QId Answer
test1 1 0
test2 1 1
test3 1 0
test4 1 0
My Code is as below :
public Cursor getOptions(String QId) {
try {
String sql = "Select * from tblOptions Where QId=" + QId + "";
Cursor mCur = mDb.rawQuery(sql, null);
if (mCur != null) {
mCur.moveToNext();
}
return mCur;
} catch (SQLException mSQLException) {
Log.e(TAG, "getOptions >>" + mSQLException.toString());
throw mSQLException;
}
}
ConnectionAdapter dbCon = new ConnectionAdapter(this);
dbCon.createDatabase();
dbCon.open();
Cursor question = dbCon.getQuestion();
Cursor option = dbCon.getOptions(Utility
.GetColumnValue(question, "QId"));
dbCon.close();
// SaveUserResponse();
String Question = question.getString(question
.getColumnIndex("Question"));
tvNote.setText(Question);
String Options = "";
for (int i = 0; i < option.getCount(); i++) {
Options = Options + Utility.GetColumnValue(option, "Option");
option.moveToNext();
}
tvRQOption.setText(Options);
tvRQOption is showing me only test4. What I am doing wrong ? And what should I do to check right or wrong option ?
public Cursor getOptions(String QId) {
try {
String sql = "Select * from tblOptions Where QId=" + QId + "";
Cursor mCur = mDb.rawQuery(sql, null);
} catch (SQLException mSQLException) {
Log.e(TAG, "getOptions >>" + mSQLException.toString());
throw mSQLException;
}
}
Getting values from db
Cursor cursor = db_obj.getoptions("Your_id")
{
cursor.moveToFirst();
if(cursor != null && cursor.getCount() > 0)
{
String string = cursor.getString(cursor.getColumnIndex("Column_Name"));
//Set this String value to Ui i.e your option
cursor.moveToNext();
}
}

Database retrieval in android

In my application i am showing data from database in a table view.My requirement is that from database i have to retrieve the data which will fall in the current month.I Have written the query but it is coming as 0.Actually i have 1 entry in the database with today's date,so my query should return that data,but it is showing as 0.Please help me.Thanks in advance.
My query is as follows:
public String addgroupincome(String grp) throws SQLException
{
long sum=0;
Cursor cursor1 = db.rawQuery(
"SELECT SUM("+(KEY_TOTAL)+") FROM incomexpense WHERE date= Strftime('%Y-%m','now') AND category='Income' AND groups='"+grp+"'",null);
if(cursor1.moveToFirst())
{
sum = cursor1.getLong(0);
}
cursor1.close();
String housetotal=String.valueOf((long)sum);
return housetotal;
}
I am getting that total and showing in atextview in table layout..
final String houtotal=db.addgroupincome(group1);
housetotal.setText(houtotal);
Most probably nothing wrong with the query but the way you pass the query result to ListView. Can you show how you do it? Perhaps I could help.
Or you could take a look here or here
public int getCount() {
DBHelper dbHelper = DBHelper.getDBAdapterInstance(this);
int count = 0;
try {
dbHelper.openDataBase();
String query = "select count(1) from t_model where upper(brandName) = upper('"
+ selectedBrand + "') order by modelName ASC";
Cursor cursor = dbHelper.selectRecordsCursor(query, null);
if (cursor.moveToFirst()) {
count = cursor.getInt(0);
}
cursor.close();
cursor = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
dbHelper.close();
}
return count;
}
and for the TextView should be as simple as
TextView tvCount = (TextView) findViewById(R.id.tvCount);
tvCount.setText("Count : " + getCount);
If you are having trouble debugging your query. Try http://sqlitebrowser.sourceforge.net/ or http://www.sqliteexpert.com/
Why don't you try by giving column names of your table in your query..might it work out for you..specify the columns which you want to retrive..
if (cursor.moveToNext()) {
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
Log.i(ID, cursor.getInt(0) + "");
cursor.moveToNext();
}
cursor.close();
} else {
cursor.close();
return null;
}
Try This Method....

getting "null" as an address for a draft sms

I want to get (TO)address of sms saved as draft. I have tried query on canonical_addresses table it is giving me message "Failed to find provider info for canonical_addresses" in logs.
Then I have tried query on sms/draft table it is giving me null as an address.
What is wrong in my code? How should I get information about draft sms? I have searched but didn't get any solution.Plz suggest me some solution.
The way is to get the thread_id that corresponds to the draft message. Find the to address by using thread_id
public String getPhoneNumbersFromThreadID(Context ctx, String threadId)
{
//System.out.println(threadId);
String phoneList = "";
ArrayList<String> phoneCheckList = new ArrayList<String>();
if(thread2Phone.containsKey(threadId))
{
return thread2Phone.get(threadId);
}
if(threadId == null || threadId.equals(""))
{
return "No Name";
}
if(threadId.trim().length() == 0) return "No Name";
Cursor c = ctx.getContentResolver().query(SMSMainListActivity.Sms_CONTENT_URI,
null,
"thread_id = '" + threadId + "'", null, "date ASC");
if (c != null) {
try {
if (c.moveToFirst()) {
while (c.isAfterLast() == false) {
String num = c.getString(c
.getColumnIndex("address"));
num = num.replaceAll(";", ",");
String[] thisNum = num.split(",");
for (int i=0; i<thisNum.length; i++)
{
phoneCheckList.add(formatNumber(thisNum[i])) ;
}
c.moveToNext();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
c.close();
}
}
try {
phoneCheckList = removeDuplicates(phoneCheckList);
Iterator it = phoneCheckList.iterator();
int i = 0;
while (it.hasNext()) {
String name = ""+it.next();
//System.out.println("Iterated "+name);
if(i==0)
phoneList = ""+name;
else
phoneList += ";"+name;
i++;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
phoneCheckList.clear();
thread2Phone.put(threadId, phoneList);
return phoneList;
}

Categories

Resources