Database accesses one variable correctly, but not the other - java

So I have two variables that I am currently trying to access. waterAmt and bucketExp. I am not certain why the waterAmt variable is working correctly but the other is not. It seems that bucketExp is not being stored the way it should, even though it is being stored the same was as waterAmt. thanks in advance for the help.
Code for accessing the database:
//pull data
data = new Database(SetupTimerPC1.this);
data.open();
bucketExpTotal = data.getBucketExp();
totalWater = data.getWaterAmt();
data.close();
//add new data to old
bucketExpTotal += bucketExp;
totalWater += waterAmt;
//push data
data.open();
data.bucketExpEntry(bucketExpTotal);
data.waterAmountEntry(totalWater);
data.close();
Code for entering waterAmt into database:
public long waterAmountEntry(int waterAmt)
{
ContentValues cv = new ContentValues();
cv.put(KEY_WATER, waterAmt);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}//end waterAmountEntry function
Code for entering bucketExp into database:
public long bucketExpEntry(int bucketExp)
{
ContentValues cv = new ContentValues();
cv.put(KEY_BUCKETEXP, bucketExp);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}//end bucketExpEntry function
Code for pulling waterAmt from database:
public int getWaterAmt()
{
int waterAmount = 0, iWaterAmount = 0;
String[] columns = new String[] {KEY_ROWID, KEY_ROCK, KEY_METEORROCK, KEY_WATER,
KEY_POPULATION, KEY_SHOVEL, KEY_BUCKET, KEY_PICKAXE, KEY_SHOVELEXP,
KEY_BUCKETEXP, KEY_PICKAXEEXP};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
if (c != null && c.getCount() > 0)
{
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
iWaterAmount = c.getColumnIndex(KEY_WATER);
waterAmount = c.getInt(iWaterAmount);
}//end for
c.close();
return waterAmount;
}//end if
return 0;
}//end getWaterAmt function
code for pulling bucketExp from database:
public int getBucketExp()
{
int bucketExp = 0, iBucketExp = 0;
String[] columns = new String[] {KEY_ROWID, KEY_ROCK, KEY_METEORROCK, KEY_WATER,
KEY_POPULATION, KEY_SHOVEL, KEY_BUCKET, KEY_PICKAXE, KEY_SHOVELEXP,
KEY_BUCKETEXP, KEY_PICKAXEEXP};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
if (c != null && c.getCount() > 0)
{
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
iBucketExp = c.getColumnIndex(KEY_BUCKETEXP);
bucketExp = c.getInt(iBucketExp);
}//end for
c.close();
return bucketExp;
}//end if
return 0;
}//end getBucketExp function

Right now your query amounts to this:
"SELECT [columns] FROM [table];"
This returns all the rows in your table. Next you are iterating over the entire set of results, and in each iteration you set the value to return equal to some column in the result row.
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
bucketExp = cursor.getInt(...);
}
Essentially this means bucketExp will equal the value of this column from the very last row in the results.
What I think you want is the value for a particular row/record. You need to change your query to return just the row you are looking for, and get rid of the for loop. Here's an example that will look up a specific row by an ID and return bucketExp:
public int getBucketExp(long id) {
String[] columns = new String[] { KEY_BUCKETEXP };
String where = KEY_ROWID + " = ?";
String[] whereArgs = new String[] { Long.toString(id) };
Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, where, whereArgs,
null, null, null);
int bucketExp = 0;
if (cursor.moveToFirst()) {
bucketExp = cursor.getInt(cursor.getColumnIndex(KEY_BUCKETEXP));
}
return bucketExp;
}

Related

Get selected row of number and return it into Integer format

How should I implement into getRow2() to get the selected row of number? So that I can moveToPosition(x);
MainActivity.java as below:
Database db = new Database(this);
int x = db.getRow2();
Cursor cursor = db.getName();
cursor.moveToPosition(x);
tvName.setText(cursor.getString(0));
Database.java as below:
public int getRow2(){
SQLiteDatabase db = this.getReadableDatabase();
int rows = -1;
try {
rows = (int) db.compileStatement("SELECT COUNT(*) FROM " + TBL_USER).simpleQueryForLong();
} catch (NullPointerException e) {
return -1;
}
return rows;
}
public Cursor getName(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select name from TBL_USER",null);
return cursor;
}
Solved:
Use moveToNext() instead of moveToPosition()
What a simple question 😚

How to check existing SQLite db in Android

I want to check SQLite database table record . Whether table row is exist then update or delete my table row or.When I run my app the table row insert duplicate.How to avoid it . I want to insert newly record when I run first time , when open the activity second time my database is update. I have tried but db is not show record there.Please help me.Thanks to appreciates
Here is my code
public boolean Exists(String _id)
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select Company_Id from Company where Company_Id = ?",
new String[]{_id});
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
My fragment code
if(jsonStr != null)
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String jsonResult = jsonObj.toString().trim();
Log.e("jsonResult ", " = " + jsonResult);
JSONObject companyList = jsonObj.getJSONObject("Get_CompanyResult");
Log.e("companyList ", " = " + companyList.toString());
JSONArray jarr = companyList.getJSONArray("CompanylList");
Log.e("jarr ", " = " + jarr.toString());
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobCompanyDetails = jarr.getJSONObject(i);
str_CompanyId = jobCompanyDetails.getString("Company_ID");
str_CompanyName = jobCompanyDetails.getString("Company_Name");
Log.e("str_CompanyId ", " = " + str_CompanyId);
Log.e("str_CompanyName ", " = " + str_CompanyName);
if(dbhelper.Exists(str_CompanyId))
{
Log.e("Row is Already ","Exist");
}
else
{
dbhelper.insertCompany(str_CompanyId, str_CompanyName);
Log.e("Data insert into ", " Company Table Succesively !!! = ");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Use below method
public boolean isIDExist(String _id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Company, new String[] { KEY_your_id}, KEY_your_id + "=?" ,
new String[] { String.valueOf( _id)}, null, null, null, null);
if (cursor != null){
if(cursor.getCount() == 0){
cursor.close();
db.close();
return false;
}else{
cursor.close();
db.close();
return true;
}
}
return false;
}
Change your code to this
public boolean Exists(String _id)
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select Company_Id from Company where Company_Id ='"+ String _id + "'", null);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return true;
}
I think the simplest way to do this is to create a Primary Key in the table, and then use INSERT OR REPLACE command instead of just using INSERT.
INSERT OR REPLACE will automatically REPLACE the existing row when it encounters a Primary Key violation, with the new data being inserted.
In this case, you can have OrgId as the Primary Key and if you have some record like:
ORGID ORGNAME
1 ABC
and you insert like INSERT OR REPLACE INTO ORG_MASTER(1,'EFG'), the table will now have one row like
ORGID ORGNAME
1 EFG
Hope this helps :)

How do I within SQLite, return a row based on 3 values rather than just one? (Already done code for 1)

Within SQLite, I can search a table for a particular row which contains 1 values for instance a player name but I want to return a row based on 3 values for instance Player name, Team name and favorite color etc.
How do I alter below code to do this?
Code for searching based upon one value is below:
public BackupDatastore getentry(String value, String columnName) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_Name,
new String[] { KEY_ID,
KEY_Team_Name,
KEY_Ref_Name,
KEY_Date,
KEY_Player_1,
KEY_Player_2,
KEY_Player_3,
KEY_Player_4,
KEY_Player_5,
KEY_Player_6,
KEY_Player_7 ,
KEY_Player_8},
columnName + "=?",
new String[] { value }, null, null, null, null);
if (cursor != null)
{
boolean move = cursor.moveToFirst();
//false value means the query returned 0 results
if(!move)
{
return BackupDatastore.kEmptyData;
}
}
BackupDatastore entry = new BackupDatastore(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10), cursor.getString(11));
// return entry
return entry;
}
You need to change what you're passing as the 3rd and 4th parameters - the column names and values passed to the WHERE clause.
For example, to filter across 3 columns you'd do:
Cursor cursor = db.query(TABLE_Name,
new String[] { KEY_ID,
KEY_Team_Name,
KEY_Ref_Name,
KEY_Date,
KEY_Player_1,
KEY_Player_2,
KEY_Player_3,
KEY_Player_4,
KEY_Player_5,
KEY_Player_6,
KEY_Player_7 ,
KEY_Player_8},
column1Name + "=? AND " +
column2Name + "=? AND " +
column3Name + "=? ",
new String[] { value1, value2, value3 }, null, null, null, null);
This will build an expression similar to SELECT Player1, Player2, ... FROM TeamName WHERE FirstName = 'X' AND LastName = 'Y' AND TeamName = 'Z'
You could build this dynamically using variable length args, or passing in string arrays, rather than simply a method defined to take 3 columns & 3 values as parameters, for example:
public BackupDatastore getentry(String[] values, String[] columns) {
if (values.length != columns.length) {
throw new IllegalArgumentException("Number of columns does not match number of values provided.");
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < columns.length; i++) {
sb.append(columns[i]);
sb.append("=?");
if (i != columns.length - 1) {
sb.append(" AND ");
}
}
String whereColumns = sb.toString();
Cursor cursor = db.query(TABLE_Name,
new String[] { KEY_ID,
KEY_Team_Name,
KEY_Ref_Name,
KEY_Date,
KEY_Player_1,
KEY_Player_2,
KEY_Player_3,
KEY_Player_4,
KEY_Player_5,
KEY_Player_6,
KEY_Player_7 ,
KEY_Player_8},
whereColumns,
values, null, null, null, null);
...

insert song to playlist returns null

I was trying to build a music player application , and I wanted to add a feature in order to add a song to a playlist.Here is the code:
public static void addToPlaylist(ContentResolver resolver,SongDetails songDetails,int playlistId) {
String[] cols = new String[] {
"count(*)"
};
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
Cursor cur = resolver.query(uri, cols, null, null, null);
cur.moveToFirst();
final int base = cur.getInt(0);
cur.close();
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, Integer.valueOf(base + songDetails.getId()));
values.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, songDetails.getId());
values.put(MediaStore.Audio.Playlists.Members.DISPLAY_NAME, songDetails.getSongTitle());
values.put(MediaStore.Audio.Playlists.Members.ARTIST, songDetails.getArtistName());
values.put(MediaStore.Audio.Playlists.Members.DATA, songDetails.getSongData());
Log.i("URI:",resolver.insert(uri, values)+"");
}
and in the logs I always get:
URI: null
which means that the song is not added to the playlist.Does anybody have any idea why the song is not added?
I've been using this method and it worked for me.
public static String addTracksToPlaylist(final long id, List<MediaData> tracks, final Context context) {
int count = getPlaylistSize(id, context);
ContentValues[] values = new ContentValues[tracks.size()];
for (int i = 0; i < tracks.size(); i++) {
values[i] = new ContentValues();
values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, i + count + 1);
values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, tracks.get(i).getId());
}
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", id);
ContentResolver resolver = context.getContentResolver();
int num = resolver.bulkInsert(uri, values);
resolver.notifyChange(Uri.parse("content://media"), null);
return String.format(context.getString(R.string.ADDED_TO_PLAYLIST), num, context.getString(R.string.CURRENT));
}
Retrieving tracks from playlist:
public static Cursor getTrackListFromPlaylist(Context context, long plid) {
String[] MEDIA_COLUMNS = new String[] {
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Playlists.Members.AUDIO_ID,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.DATA,
MINUTES + "||':'||" + SECONDS + " as " + FORMATTED_DURATION,
MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media._ID
};
return query(context, MediaStore.Audio.Playlists.Members.getContentUri("external", plid),
MEDIA_COLUMNS, null, null, MediaStore.Audio.Playlists.Members.DEFAULT_SORT_ORDER);
}

Looking for a appropraite logic

Actually I am using call logs as an input to database and then I am fetching it in a way that I can't get any duplicate values while displaying it and if i have any duplicate value in data base then it should be taken as integer value count. For example: john(6).
Here john must have entry 6 times in database. Don't get me wrong. I don't need a code.I need help. Here is code:
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(android.provider.CallLog.Calls.CONTENT_URI,null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String rawContactId = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls._ID));
Cursor callLogCursor = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, new String[]{
android.provider.CallLog.Calls.CACHED_NAME,
android.provider.CallLog.Calls.CACHED_NUMBER_LABEL,
android.provider.CallLog.Calls.NUMBER,
android.provider.CallLog.Calls.DATE,
android.provider.CallLog.Calls.DURATION,
android.provider.CallLog.Calls.TYPE
},android.provider.CallLog.Calls._ID + "=?", new String[] { rawContactId }, null);;
if (callLogCursor != null) {
while (callLogCursor.moveToNext()) {
//String id = callLogCursor.getString(0);
String name = callLogCursor.getString(0);
String cacheNumber = callLogCursor.getString(1);
String number = callLogCursor.getString(2);
long dateTimeMillis = callLogCursor.getLong(3);
long durationMillis = callLogCursor.getLong(4);
int callType = callLogCursor.getInt(5);
String duration = getDuration(durationMillis * 1000);
String dateString = getDateTime(dateTimeMillis);
if (cacheNumber == null)
cacheNumber = number;
if (name == null)
name = "Unknown";
Uri image = null;
try {
String conId = fetchContactIdFromPhoneNumber(cacheNumber);
long contId = Long.parseLong(conId);
image = getPhotoUri(contId);
}catch(Exception e) {
Log.e("Exception", e.getMessage());
}
//CallLogModel callLogModel = new CallLogModel(image, name, cacheNumber,
// duration, dateString);
ContentValues values = new ContentValues();
values.put(NAME, name);
values.put(NUMBER, cacheNumber);
values.put(DATE, dateString);
values.put(DURATION,duration );
database.insert(CALL_LOG_TABLE, null, values);
Cursor cursor = database.query(CALL_LOG_TABLE, new String [] {LOG_ID, NAME, NUMBER, DATE, DURATION}, null, null, null, null, null);
int row =0;
if(!cursor.isAfterLast()) {
cursor.moveToFirst();
do{
int pId=cursor.getInt(0);
String pName = cursor.getString(1);
String pNumber = cursor.getString(2);
String pDate = cursor.getString(3);
String pDuration = cursor.getString(4);
int value = 0;
CallLogModel callLogModel = new CallLogModel(image, name, cacheNumber, duration, dateString);
if (callType == CallLog.Calls.OUTGOING_TYPE) {
for(int i=0;i<outgoingList.size();i++){
------------------------------Actually i want Logic here what should i do here--------------
}
}
outgoingList.add(callLogModel);
} else if (callType == CallLog.Calls.INCOMING_TYPE) {
incomingList.add(callLogModel);
} else if (callType == CallLog.Calls.MISSED_TYPE) {
missedcallList.add(callLogModel);
}
cursor.moveToNext();
} while (!cursor.isAfterLast());
}
}
callLogCursor.close();
}
}
You could model the outgoing calls in a hashmap, something like:
Map<String, Integer> outgoingCallsMap = new HashMap<String, Integer>();
for (int i = 0; i < outgoingList.size(); i++) {
String nameOfCallee = outgoingList.get(i);
if (!outgoingCallsMap.containsKey(nameOfCallee)) {
outgoingCallsMap.put(nameOfCallee, 1);
} else {
//Increment calls to this person
outgoingCallsMap.put(nameOfCallee, outgoingCallsMap.get(nameOfCallee) + 1);
}
}
Remove the duplicates in your outGoingList, by iterating it and putting the result to a map, with contact name as key and list of CallLogModel object as value.
You can refer this method.
private void convertToOutGoingMap(List<CallLogModel > outGoingList) {
HashMap<String,List<CallLogModel>> outGoingMap = new HashMap<String, List<CallLogModel>>();//map which has CallLogModel.name as key and List<CallLogModel> as value.
for(CallLogModel model : outGoingList){//Iterate thru the list.
if(outGoingMap.containsKey(model.name))
{
outGoingMap.get(model.name).add(model);//if map contains key, add model to the list.
} else {
List<CallLogModel> modelList = new ArrayList<CallLogModel>();//if it does not contains, initialize a list and add model to it.
modelList.add(model);
outGoingMap.put(model.name, modelList);
}
}
}
}
The key set of this map gives you the unique call log names and corresponding value list gives all occurrences and its size gives you number of occurrences.
Hope this help you.

Categories