Trying to scan my SQLite Database. Android - android

I have a save button that should basically create a new entry in my SQLite database IF there isn't already one with the same 'name and number'(both are stored as strings).
If there is already an entry with the same name and number, it should make a popup asking if they want to overwrite.
What actually happens is it creates a new entry whether or not the entry already exists.
Code that runs when you click save:
final String thename=TeamName.getText().toString()
final String thenum=TeamNum.getText().toString();
if ((thename.length()!=0) && (thenum.length()!=0)){
ScoutingFormData info1 = new ScoutingFormData(this);
info1.open();
final long returnedId=info1.scanFor(thename,thenum);
if (returnedId==-1){
info1.createEntry(thename,thenum);
}
else
{
final Dialog overw=new Dialog(this);
....//The code that goes here is unimportant to my question so I'm hiding it.
overw.show();
}
info1.close();
}
Code in ScoutingFormData.java:
public long scanFor(String thename, String thenum) {
String[] columns=new String[]{KEY_ROWID,KEY_NAME,KEY_NUM};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
int iID = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iNum = c.getColumnIndex(KEY_NUM);
for (c.moveToFirst(); !c.isAfterLast();c.moveToNext()){
if ((c.getString(iName)==thename) && (c.getString(iNum)==thenum)){
return Long.parseLong(c.getString(iID));
}
}
return -1;
}
I don't see how it could possibly return -1 if an entry already exists with the same name+number.

Use equals to compare String values.

Related

How to get specific value from DB by id

How to get specific value from DB by id.
This is my table: TABLE-RECORDS-(name of table) and KEY-ID , KEY-PRICE ... I'm trying to get KEY-PRICE by KEY-ID and can not. How to do it?
I don't know if this is exactly what you are looking for, but this is the query.
SELECT key-price FROM table-record WHERE key-id='id number you need';
// please change the column names of database if i have mistaken
public Cursor getCursor(int id) {
SQLiteDatabase db = this.getReadableDatabase();
String from[] = {"key-price"};//this is the edit1
String where = "key-id=?";//this is the edit2
String[] whereArgs = new String[]{String.valueOf(id)+""}; //this is the edit3
Cursor cursor = db.query(true, table-records, from, where, whereArgs, null, null, null, null);
return cursor;
}
//just call this function and see the magic
private int getPrice(int id) {
Cursor c = getCursor(id);
int price=-1;
if(c != null)
{
while(c.moveToNext){
//assuming price is an integer
price = c.getInt(0);//edit 4
// use these strings as you want
}
}
return price;
}

confused about how to use getContentResolver in android

I'm developing an application which reads browser history.I tried using managedQuery but I just got to know that it is deprecated.I found the following answer on a similiar question
Cursor cursor = this.context.getContentResolver().query(Browser.SEARCHES_URI, null, null, null, null);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
final int indexDate = cursor.getColumnIndex(Browser.SearchColumns.DATE);
final int indexTerm = cursor.getColumnIndex(Browser.SearchColumns.SEARCH);
String date = cursor.getString(indexDate);
String term = cursor.getString(indexTerm);
cursor.moveToNext();
}
}
cursor.close();
My doubt is,what is the role of the context variable over here? How do I get the Browser's context in that variable?

Update Contact Data by Data ID

My application uses the Contacts ContentProvider to store some of its data. When I load a contact into memory, I want to save its ID (so that I know how to save changes later), and the ID of all data fields it is using (so they can be directly updated). Here is some of my code:
Uri entityUri = Uri.withAppendedPath(
ContentUris.withAppendedId(RawContacts.CONTENT_URI, id),
Entity.CONTENT_DIRECTORY);
Cursor resultData = context.getContentResolver().query(
entityUri,
new String[]{RawContacts.SOURCE_ID, Entity.DATA_ID, Entity.MIMETYPE, Entity.DATA1},
null, null, null);
resultData.moveToFirst();
this.id = id;
while (resultData.isAfterLast() == false) {
this.source_id = resultData.getInt(0);
if (!resultData.isNull(1)) {
if (resultData.getString(2).equals(Fields.DISPLAY_NAME)) {
this.display_name = resultData.getString(3);
this.display_name_id = resultData.getInt(1);
}
}
resultData.moveToNext();
}
resultData.close();
return this;
That queries the ContentProvider and gets the DISPLAY_NAME field from the data. The ID of the data record is stored in the display_name_id variable. It comes out as 4612 when I run it on my device.
I tried saving it, but it does not update as expected. In order to debug, I added a query that tries to find the correct data table record.
Cursor c = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
new String[] {ContactsContract.Data._ID, CommonDataKinds.StructuredName.DISPLAY_NAME},
ContactsContract.Data._ID + "=?",
new String[] {String.valueOf(this.display_name_id)}, null);
However, this cursor comes back as having a length of 0. How can this be? Why is the ID incorrect?
I tried locally and it works for me, here's my code slightly adapted from yours:
public void testContacts(final #Nonnull Context context, final int rawContactId, final #Nonnull String expectedDisplayName) {
Uri entityUri = Uri.withAppendedPath(
ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, rawContactId),
ContactsContract.RawContacts.Entity.CONTENT_DIRECTORY);
Cursor resultData = context.getContentResolver().query(
entityUri,
new String[]{
ContactsContract.RawContacts.SOURCE_ID,
ContactsContract.RawContacts.Entity.DATA_ID,
ContactsContract.RawContacts.Entity.MIMETYPE,
ContactsContract.RawContacts.Entity.DATA1
},
null, null, null);
int displayNameId = -1;
try {
final int columnIndexDataId = resultData.getColumnIndex(ContactsContract.RawContacts.Entity.DATA_ID);
final int columnIndexMimetype = resultData.getColumnIndex(ContactsContract.RawContacts.Entity.MIMETYPE);
final int columnIndexData = resultData.getColumnIndex(ContactsContract.RawContacts.Entity.DATA1);
while (resultData.moveToNext()) {
if (!resultData.isNull(columnIndexDataId)) {
if (ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE.equals(resultData.getString(columnIndexMimetype)) &&
expectedDisplayName.equals(resultData.getString(columnIndexData))) {
displayNameId = resultData.getInt(1);
break;
}
}
}
} finally {
resultData.close();
}
String reLookedUpDisplayName = null;
if (displayNameId != -1) {
Cursor reLookupCursor = context.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[] {
ContactsContract.Data._ID,
ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME
},
ContactsContract.Data._ID + "=?",
new String[] {String.valueOf(displayNameId)},
null);
try {
final int columnIndexId = reLookupCursor.getColumnIndex(ContactsContract.Data._ID);
final int columnIndexDisplayName = reLookupCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);
while (reLookupCursor.moveToNext()) {
reLookedUpDisplayName = reLookupCursor.getString(columnIndexDisplayName);
}
} finally {
reLookupCursor.close();
}
}
Toast.makeText(
context,
reLookedUpDisplayName != null ? "Found re-looked up name: " + reLookedUpDisplayName : "Didn't find name re-looking it up",
Toast.LENGTH_LONG)
.show();
}
There's no big difference from your code, so compare or try to replace bits of it to see where you have a problem. Make sure you use a fresh Cursor for each query, and close it correctly afterwards (in a finally clause).
Another thing, make sure that if (resultData.getString(2).equals(Fields.DISPLAY_NAME)) is really what you're wanting to do (it compares the entry mime type with Fields.DISPLAY_NAME), but since you're saying you get the data ID correctly this shouldn't be the problem.

Skip deleted/empty rows sqlite

I am populating AChartEngine from sqlite database and I need all of the data to be displayed. The problem I'm having is when I delete a record the graph series stops populating at the deleted record. I need to find a way to skip over deleted/empty records and continue populating my graph. I need it to do it the same way listview skips over deleted records and keeps on displaying all rows. I am very new to a lot of this and am having a very difficult time with this. I have tried to write if statements in order to skip deleted/empty rows but nothing seems to work. Thank you for helping!
in my graphing activity:
for (int i = 1; !c.isAfterLast(); i++) {
String value1 = db.getValue1(i);
String value2 = db.getValue2(i);
c.moveToNext();
double x7 = Double.parseDouble(value1);
double y7 = Double.parseDouble(value2);
myseries.add(x7, y7);
}
I am getting error: CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
If I surround with try and catch it will populate rows up until the deleted record.
"EDIT"
in my sqlite database:
public String getValue1(long l) {
String[] columns = new String[]{ EMP_DEPT };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value1 = c.getString(0);
return value1;
}
return null;
}
public String getValue2(long l) {
String[] columns = new String[]{ EMP_DATE1 };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value2 = c.getString(0);
return value2;
}
return null;
}
Your issue is that your safety net for commands on rows that don't exist is to use if (c != null){ and then perform your commands inside that block, but a Cursor request from a query will never come up null, it will instead result in a cursor object with no rows.
A more appropriate solution to use this as your safety net instead if (c.moveToFirst()){ Because the method itself returns a boolean for if the method actually carried itself out in the first place - true if it moved and false if not (which occurs when there's no rows to move into). another check, if you wish, would be to see how many rows the cursor has with c.getCount().
Additionally, you should combine your methods so that you don't make redundant queries to the database:
public String[] getValues(long l) {
String[] results = new String[2];
String[] columns = new String[]{ EMP_DEPT, EMP_DATE1 };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c.moveToFirst()) {
results[0] = c.getString(0);
results[1] = c.getString(1);
} else {
Log.d("GET_VALUES", "No results formed from this query!");
}
return results;
}
You should use a single query to get all values at once:
SELECT Date1 FROM MyTable WHERE id BETWEEN 1 AND 12345
or:
db.query(EMP_TABLE, columns, EMP_ID + " BETWEEN 1 AND " + ..., ...);
Then missing values will just not show up when you iterate over the cursor.

Android getting value of db key of sql

I'm trying to get the value in a specific column in my database and here's the code I have as of now to achieve it:
String id = db.KEY_ID;
but all I get now is the title of of the column, which in this case, id, instead of the value itself, such as 1, 2, etc. How do I grab the value and not the key of a database? Thanks!!!
You need to create a query statement and execute it against the data base. You use db.KEY_ID to specify in the query what column of data you want.
A simple example:
public String getEntry(long rowIndex){
String value = "";
Cursor c = db.query(DATABASE_TABLE, new String[] {KEY_NAME, VALUE}, KEY_NAME + "=" + rowIndex, null, null, null, null);
int columnIndex = c.getColumnIndex(VALUE);
int rowsCount = c.getCount();
if(rowsCount > 0){
String value = c.getString(columnIndex);
}
return value;
}

Categories

Resources