Increment a counter in database SQLite - java

I'm doing a project on estimote shoe sticker and I'm now doing database for the sticker. My issue is now how to set counter in database sqlite. Every once the sticker is picked up or clicked, in the database it will show an increment in count. I have post the codes for database and main activity below.
NearablesDemoActivity.java
private void displayCurrentNearableInfo() {
stickerdb = new Database_sticker(this);
dbRow = stickerdb.getResult(currentNearable.identifier);
dbRow.getId();
dbRow.getIdentifier();
count = stickerdb.getCount(currentNearable.identifier);
dbRow.getCount();
String desc = dbRow.getDesc().toString();
dbRow.getCa().toString();
dbRow.getSa().toString();
String coo = dbRow.getCoo().toString();
String sm = dbRow.getSm().toString();
String price = dbRow.getPrice().toString();
//Set the text to the TextView
Desc.setText(desc);
COO.setText(coo);
SM.setText(sm);
Price.setText("$" + price);
}
Database_sticker.java
public int getCount(String identifier) {
String countQuery = "UPDATE" + TABLE_SRESULT + " SET " + KEY_COUNT + "=" + KEY_COUNT + "+1"
+ " WHERE " + KEY_IDENTIFIER + "='" + identifier + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
if(cursor != null && !cursor.isClosed()){
cursor.close();
}
return cursor.getCount();
}
public Sresult getResult(String identifier) {
String selectQuery = "SELECT * FROM " + TABLE_SRESULT + " WHERE " + KEY_IDENTIFIER + "='" + identifier + "'";
SQLiteDatabase db = this.getWritableDatabase(); //open database
Cursor cursor = db.rawQuery(selectQuery, null);
//looping through all rows and adding to list
Sresult sresult = new Sresult();
if (cursor.moveToFirst()) {
do {
sresult.setId(Integer.parseInt(cursor.getString(0)));
sresult.setIdentifier(cursor.getString(1));
sresult.setDesc(cursor.getString(2));
sresult.setSa(cursor.getString(3));
sresult.setCa(cursor.getString(4));
sresult.setCoo(cursor.getString(5));
sresult.setSm(cursor.getString(6));
sresult.setPrice(Float.parseFloat(cursor.getString(7)));
sresult.setCount(Integer.parseInt(cursor.getString(8)));
} while (cursor.moveToNext());
}
return sresult;
}
ListNearablesActivity.java
beaconManager.setNearableListener(new BeaconManager.NearableListener() {
#Override
public void onNearablesDiscovered(List<Nearable> nearables) {
toolbar.setSubtitle("Found shoes: " + nearables.size());
adapter.replaceWith(nearables);
for (Nearable nearable : nearables) {
if (nearable.isMoving) {
try {
Class<?> clazz = Class.forName(getIntent().getStringExtra(EXTRAS_TARGET_ACTIVITY));
Intent intent = new Intent(ListNearablesActivity.this, clazz);
intent.putExtra(EXTRAS_NEARABLE, adapter.getItem(nearables.indexOf(nearable)));
startActivity(intent);
} //close for try
catch (ClassNotFoundException e) {
Log.e(TAG, "Finding class by name failed", e);
} //close for catch (ClassNotFoundException e)
}
}
} //for override
}); //for beaconManager.setNearable
private AdapterView.OnItemClickListener createOnItemClickListener() {
return new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
if (getIntent().getStringExtra(EXTRAS_TARGET_ACTIVITY) != null){
try {
Class<?> clazz = Class.forName(getIntent().getStringExtra(EXTRAS_TARGET_ACTIVITY));
Intent intent = new Intent(ListNearablesActivity.this, clazz);
intent.putExtra(EXTRAS_NEARABLE, adapter.getItem(position));
startActivity(intent);
} //close for try
catch (ClassNotFoundException e) {
Log.e(TAG, "Finding class by name failed", e);
} //close for catch (ClassNotFoundException e)
} //close for getintent.getStringExtra()
} //close for public void onitemclick
}; //close for return new adapterview
} //close for private adapter
Solution
Database_sticker.java
public int getStickerCount(String identifier) {
String countQuery = "UPDATE " + TABLE_SRESULT + " SET " + KEY_SCOUNT + " = " + KEY_SCOUNT + "+1" + " WHERE " + KEY_IDENTIFIER + "= '" + identifier + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int scount = 0;
if (cursor.moveToFirst())
{
do
{
scount = Integer.parseInt(cursor.getString(8));
} while(cursor.moveToNext());
}
return scount; }

For incrementing value by one in counter , you need to fire UPDATE query to Table.
Like below :
UPDATE "Your tablename"
SET "counter column name"= "counter column name"+ 1
WHERE id= "pass your reference id";
Hope it will help you.

Related

How to correctly display user's info among multiple users?

The command to retrieve user data doesn't display correctly, it shows the information of the last registered user.
MainActivity/login
public class MainActivity extends AppCompatActivity {
Button btnRegister, btnLogin;
EditText edtAccount, edtPassword;
Database db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRegister = (Button) findViewById(R.id.buttonSignup);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(i);
}
});
edtAccount = (EditText) findViewById(R.id.editTextAccount);
edtPassword = (EditText) findViewById(R.id.editTextPassword);
btnLogin = (Button) findViewById(R.id.buttonLogin);
db=new Database(this);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String account = edtAccount.getText().toString();
String password = edtPassword.getText().toString();
if (account.equals("") || password.equals("")){
Toast.makeText(MainActivity.this,
"Account and password are empty",Toast.LENGTH_SHORT).show();
}
else {
Boolean result = db.checkUserNamePassword(account, password);
if(result==true) {
Intent intent = new Intent(MainActivity.this, TestActivity.class);
intent.putExtra("account", account);
startActivity(intent);
}
else{
Boolean userCheckResult = db.checkUserName(account);
if(userCheckResult == true){
Toast.makeText(MainActivity.this,
"invalid password!", Toast.LENGTH_SHORT).show();
edtPassword.setError("invalid password!");
} else{
Toast.makeText(MainActivity.this,
"Account does not exist", Toast.LENGTH_SHORT).show();
edtAccount.setError("Account does not exist!");
}
}
}
}
});
}
}
Database
public class Database extends SQLiteOpenHelper {
public static final String TB_USER = "USER";
public static final String TB_PERSONAL = "PERSONAL";
public static final String TB_GROUPSCHEDULE = "GROUPSCHEDULE";
public static String TB_USER_ACCOUNT = "ACCOUNT";
public static String TB_USER_PASSWORD = "PASSWORD";
public static String TB_USER_ID = "USERID";
public static String TB_USER_FIRSTNAME = "USERFIRSTNAME";
public static String TB_USER_LASTNAME = "USERLASTNAME";
public static String TB_USER_PHONENUMBER = "PHONENUMBER";
public static String TB_USER_EMAIL = "EMAIL";
public static String TB_PERSONAL_ID = "PERSONALID";
public static String TB_PERSONAL_TIME = "PERSONALTIME";
public static String TB_PERSONAL_EVENT = "PERSONALEVENT";
public static String TB_GROUP_ID = "GROUPID";
public static String TB_GROUP_MEMBERS = "GROUPMEMBERS";
public static String TB_GROUP_LEADER = "GROUPLEADER";
public static String TB_GROUP_EVENT = "GROUPEVENT";
public static String TB_GROUP_TIME = "GROUPTIME";
public Database(Context context) {
super(context, "Mysche", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String tbUSER = " CREATE TABLE " + TB_USER + " ( "
+ TB_USER_ACCOUNT + " TEXT , "
+ TB_USER_PASSWORD + " TEXT , "
+ TB_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ TB_USER_FIRSTNAME + " TEXT, "
+ TB_USER_LASTNAME + " TEXT, "
+ TB_USER_EMAIL + " TEXT, "
+ TB_USER_PHONENUMBER + " TEXT )";
String tbPERSONAL = " CREATE TABLE " + TB_PERSONAL + " ( "
+ TB_PERSONAL_ID + " TEXT PRIMARY KEY , "
+ TB_PERSONAL_EVENT + " TEXT, "
+ TB_PERSONAL_TIME + " DATE )";
String tbGROUP = " CREATE TABLE " + TB_GROUPSCHEDULE + " ( "
+ TB_GROUP_ID + "INTEGER PRIMARY KEY , "
+ TB_GROUP_LEADER + " TEXT, "
+ TB_GROUP_MEMBERS + " TEXT, "
+ TB_GROUP_EVENT + " TEXT, "
+ TB_GROUP_TIME + " TEXT )";
db.execSQL(tbUSER);
db.execSQL(tbPERSONAL);
db.execSQL(tbGROUP);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TB_USER);
db.execSQL("DROP TABLE IF EXISTS " + TB_PERSONAL);
db.execSQL("DROP TABLE IF EXISTS " + TB_GROUPSCHEDULE);
onCreate(db);
}
public Boolean insertData(String ACCOUNT, String PASSWORD, String USERFIRSTNAME, String USERLASTNAME, String PHONENUMBER, String EMAIL) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("ACCOUNT", ACCOUNT);
contentValues.put("PASSWORD", PASSWORD);
contentValues.put("USERFIRSTNAME", USERFIRSTNAME);
contentValues.put("USERLASTNAME", USERLASTNAME);
contentValues.put("PHONENUMBER", PHONENUMBER);
contentValues.put("EMAIL", EMAIL);
long result = db.insert("USER", null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
public Boolean checkUserName(String ACCOUNT) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM USER WHERE ACCOUNT = ?"
, new String[]{ACCOUNT});
if (cursor.getCount() > 0) {
return true;
} else {
return false;
}
}
public Boolean checkUserNamePassword(String ACCOUNT, String PASSWORD) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from USER where ACCOUNT = ? and PASSWORD = ?"
, new String[]{ACCOUNT, PASSWORD});
if (cursor.getCount() > 0) {
return true;
} else {
return false;
}
}
public Cursor getInfo() {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(" SELECT * FROM " + TB_USER
+ " WHERE " + TB_USER_ACCOUNT, null);
return cursor;
}
}
TestActivity
public class TestActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Database database = new Database(this);
TextView textViewName = findViewById(R.id.textViewUserName);
TextView textViewEmail = findViewById(R.id.textViewUserEmail);
TextView textViewPhone = findViewById(R.id.textViewPhone);
TextView textViewAccount = findViewById(R.id.textViewAccount);
String account = getIntent().getStringExtra("account");
textViewPhone.setText(account);
Cursor cursor = database.getInfo();
while (cursor.moveToNext()){
textViewName.setText(cursor.getString(4 ) + " " +(cursor.getString(3)));
textViewPhone.setText(cursor.getString(5));
textViewEmail.setText(cursor.getString(6));
textViewAccount.setText(account);
}
}
}
I think I need to change this command:
public Cursor getInfo() {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(" SELECT * FROM " + TB_USER
+ " WHERE " + TB_USER_ACCOUNT, null);
return cursor;
}
to:
public Cursor getInfo() {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(" SELECT * FROM " + TB_USER
+ " WHERE " + TB_USER_ACCOUNT + "=" + loggingAccount();, null);
return cursor;
}
But I don't know how to create and insert that loggingAccount() function. I was able to display username by getIntent() in TestActivity.
String account = getIntent().getStringExtra("account");
textViewPhone.setText(account);
Or if anyone knows another way please guide me.
You could create an overloaded method getInfo(String acct) and invoke as follows:
Cursor cursor = database.getInfo(account);
and define it as such:
public Cursor getInfo(String account) {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(" SELECT * FROM " + TB_USER
+ " WHERE " + TB_USER_ACCOUNT + " = '" + account + "'", null);
return cursor;
}
An overloaded method means methods within a class can have the same name (e.g. getInfo) but differ in method signature (parameters). And of course their implementation can differ.
Since your query is formed using data from user input you should use prepared statements. Check out PreparedStatement for more discussion on that.

database records not updating android studio , sql-lite

Could someone help me? my records are not updating.
I guess the edittext stay the same but not too sure.
How to change the view values that is being put in the edittext to change to the values in updating edittexts.
Would appreciate some help with this
Thank you.
DatabaseManager
public Cursor selectRow(String ID) {
String query = "Select * from " + TABLE_NAME + " where studentID = " + ID;
Cursor cursor = db.rawQuery(query, null);
return cursor;
}
public boolean updateData(String id, String fn, String ln, String ge, String cs, String a, String loc) {
ContentValues contentValues = new ContentValues();
contentValues.put("studentID", id);
contentValues.put("first_name", fn);
contentValues.put("last_name", ln);
contentValues.put("gender", ge);
contentValues.put("course_study", cs);
contentValues.put("age", a);
contentValues.put("location", loc);
db.update(TABLE_NAME, contentValues, "studentID = ?", new String[]{id});
return true;
}
The above is parts of my database that I use in this activity.
activity main.java
private void UpdateData() {
u.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
uptable.setVisibility(View.VISIBLE);
again.setVisibility(View.VISIBLE);
Cursor res = mydManager.selectRow(text);
if (res != null && res.moveToFirst()) {
String id = Integer.toString(res.getInt(0));
String nme = res.getString(1);
String lnme = res.getString(2);
String gen = res.getString(3);
String corse = res.getString(4);
String ag = Integer.toString(res.getInt(5));
String lo = res.getString(6);
studid.setText(id);
fname.setText(nme);
lname.setText(lnme);
gender.setText(gen);
course.setText(corse);
age.setText(ag);
loc.setText(lo);
}
}
}
);
}
public void UpdateData1() {
again.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
uptable.setVisibility(View.GONE);
String id = studid.getText().toString();
String nme = fname.getText().toString();
String lnme = lname.getText().toString();
String gen = gender.getText().toString();
String corse = course.getText().toString();
String ag = age.getText().toString();
String lo = loc.getText().toString();
boolean isUpdated = mydManager.updateData(id, nme , lnme, gen, corse ,ag , lo);
if (isUpdated == true)
Toast.makeText(Main4Activity.this, "Data Updated", Toast.LENGTH_LONG).show();
else
Toast.makeText(Main4Activity.this, "Data Not Updated", Toast.LENGTH_LONG).show();
}
}
);
}
I tried having a button to set the data but it still stays the same.
Sorry din't read the code, take the sample if it helps
Just the logic..
public long updateNote(NoteModel noteModel) {
if (LOG_DEBUG) UtilLogger.showLogUpdate(TAG, noteModel, noteModel.getRow_pos());
long updatedRow = 0;
try {
ContentValues contentValues = new ContentValues();
contentValues.put(DBSchema.DB_TITLE, noteModel.getTitle());
contentValues.put(DBSchema.DB_IMAGE_PATH, noteModel.getImgUriPath());
contentValues.put(DBSchema.DB_SUB_TEXT, noteModel.getSub_text());
contentValues.put(DBSchema.DB_CREATE_DATE, noteModel.getCreateDate());
contentValues.put(DBSchema.DB_UPDATE_DATE, noteModel.getUpdateDate());
contentValues.put(DBSchema.DB_SCHEDULED_TIME_LONG, noteModel.getScheduleTimeLong());
contentValues.put(DBSchema.DB_SCHEDULED_TIME_WHEN, noteModel.getScheduledWhenLong());
contentValues.put(DBSchema.DB_SCHEDULED_TITLE, noteModel.getScheduledTitle());
contentValues.put(DBSchema.DB_IS_ALARM_SCHEDULED, noteModel.getIsAlarmScheduled());
contentValues.put(DBSchema.DB_IS_TASK_DONE, noteModel.getIsTaskDone());
contentValues.put(DBSchema.DB_IS_ARCHIVED, noteModel.getIsArchived());
updatedRow = mSqLiteDatabase.updateWithOnConflict(
DBSchema.DB_TABLE_NAME,
contentValues,
DBSchema.DB_ROW_ID + " =?", new String[]{String.valueOf(noteModel.get_id())}, mSqLiteDatabase.CONFLICT_REPLACE);
return updatedRow;
} catch (SQLException e) {
e.printStackTrace();
}
return updatedRow;
}
then take the cursor
public Cursor getCursorForAlarmScheduled(String passAlarmScheduledStatus) {
if (LOG_DEBUG)
Log.w(TAG, " pick all record with alarmScheduled 1 : " + passAlarmScheduledStatus);
return mSqLiteDatabase.rawQuery(DBSchema.DB_SELECT_ALL +
" WHERE " + DBSchema.DB_IS_ALARM_SCHEDULED + " = " + passAlarmScheduledStatus, null);
}
and then extract
//common operation for all,
public static List<NoteModel> extractCommonData(Cursor cursor, List<NoteModel> noteModelList) {
noteModelList = new ArrayList<>();
if (LOG_DEBUG) Log.i(TAG, "inside extractCommonData()");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
NoteModel noteModel = new NoteModel();
noteModel.set_id(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_ROW_ID)));
noteModel.setTitle(cursor.getString(cursor.getColumnIndex(DBSchema.DB_TITLE)));
noteModel.setImgUriPath(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IMAGE_PATH)));
noteModel.setSub_text(cursor.getString(cursor.getColumnIndex(DBSchema.DB_SUB_TEXT)));
noteModel.setCreateDate(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_CREATE_DATE)));
noteModel.setUpdateDate(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_UPDATE_DATE)));
noteModel.setScheduleTimeLong(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TIME_LONG)));
noteModel.setScheduledWhenLong(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TIME_WHEN)));
noteModel.setScheduledTitle(cursor.getString(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TITLE)));
noteModel.setIsAlarmScheduled(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_ALARM_SCHEDULED)));
noteModel.setIsTaskDone(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_TASK_DONE)));
noteModel.setIsArchived(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_ARCHIVED)));
noteModelList.add(noteModel);
} while (cursor.moveToNext());
}
cursor.close();
}
return noteModelList;
}
Again, I din't read,just copied from my old samples
Please do find the needful, cheers

How to add quantity if item already exist

I would like to check whether a record exists or not.If exist , i want to add the quantity.
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = etCode.getText().toString();
String product = etProduct.getText().toString();
String qty = etQty.getText().toString();
try {
if (isExist(code)) {
rQty = Integer.parseInt(rQty + etQty.getText().toString());
} else {
myDB.addData(code, product, Integer.parseInt(qty));
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
});
}
public boolean isExist(String code) {
boolean result;
SQLiteDatabase db = myDB.getReadableDatabase();
try {
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE " + code + "'", null);
if (cursor.getCount() > 0 ){
while (cursor.moveToFirst()){
rQty = cursor.getInt(cursor.getColumnIndex("QTY"));
}
result = true;
}else {
result = false;
}
}
catch (Exception ex){
result = false;
}
return result;
}
}
Here is the code.if insert the same code of item , the data become duplicate and it not add the quantity for the same code.Please help me to solve this problem .
There are multiple errors and bugs in your code. One problem is this code
rQty = Integer.parseInt(rQty + etQty.getText().toString());
It won't add qQty with input quantity. because here strings concatenated.
You have to use
rQty += Integer.parseInt (qty);
Second one is your sqlite query is not right and it is incomplete
so change
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE " + code + "'", null);
to
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE = '" + code + "'", null);
Try below code
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = etCode.getText().toString();
String product = etProduct.getText().toString();
String qty = etQty.getText().toString();
try {
if (isExist(code)) {
rQty += Integer.parseInt (qty);
} else {
myDB.addData(code, product, Integer.parseInt(qty));
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
});
}
public boolean isExist(String code) {
boolean result;
SQLiteDatabase db = myDB.getReadableDatabase();
try {
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE = '" + code + "'", null);
if (cursor.getCount() > 0 ){
while (cursor.moveToFirst()){
rQty = cursor.getInt(cursor.getColumnIndex("QTY"));
}
result = true;
}else {
result = false;
}
}
catch (Exception ex){
result = false;
}
return result;
}

I can't see the first item added to my ListView

I have a database made with OpenSQLiteHelper which where I am getting a String of names from and adding it to a ListView. I can never see the first item in the database and the ListView only starts from the second item in the Database.
I am getting Strings from COL_2 (names) in my database.
ListView Class
public class Castawaylist extends AppCompatActivity {
private static final String TAG = "CastList";
myDbAdapter mydb;
private ListView castview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_castawaylist);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
castview = (ListView) findViewById(R.id.listView);
mydb = new myDbAdapter(this);
populateCastList();
}
String score;
private void populateCastList()
{
//get the data and append to the list
Log.d(TAG, "populateCastList: Displaying List of Castaways.");
Cursor data = mydb.getData();
//int save = data.getInt(2);
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext())
{
listData.add(data.getString(1) +
" " + data.getInt(2)); //get value from database at column 1, then add it to array list
}
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData); //Creates the list adapter and set it
castview.setAdapter(adapter);
castview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String nametest = "";
int u = 0;
while(!adapterView.getItemAtPosition(i).toString().substring(u,u+1).equals(" "))
{
nametest = nametest + adapterView.getItemAtPosition(i).toString().substring(u, u+1);
u = u + 1;
}
Log.d(TAG, "onItemClick: You Clicked on " + nametest);
Cursor data = mydb.getItemID(nametest); //Get the ID associated with that name
int itemID = -1;
while(data.moveToNext())
{
itemID = data.getInt(0);
}
if(itemID > -1)
{
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editCastaway = new Intent(Castawaylist.this, EditCastaway.class);
editCastaway.putExtra("id", itemID);
editCastaway.putExtra("name", nametest);
//editCastaway.putExtra("score", data.getInt(2));
startActivity(editCastaway);
}else
{
toastText("No ID associated with that name");
}
}
});
}
private void toastText(String text)
{
Toast.makeText(this,text, Toast.LENGTH_SHORT).show();
}}
ListView XML Code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"/>
</LinearLayout>
Database Helper Class
public class myDbAdapter extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "Castaways.db";
public static final String TABLE_NAME = "Survivor_Table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "MARK";
public myDbAdapter(Context context) {
super(context, DATABASE_NAME, null, 2);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MARK INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean addData(String name,int score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,score);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public Cursor getItemID(String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL_1 + " FROM " + TABLE_NAME +
" WHERE " + COL_2 + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
public boolean updateData(String id,String name,String surname,int score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,id);
contentValues.put(COL_2,name);
contentValues.put(COL_3,score);
db.update(TABLE_NAME, contentValues, "ID = ?",new String[] { id });
return true;
}
public void updateName(String newName, int id, String oldName){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET " + COL_2 +
" = '" + newName + "' WHERE " + COL_1 + " = '" + id + "'" +
" AND " + COL_2 + " = '" + oldName + "'";
Log.d(TAG, "updateName: query: " + query);
Log.d(TAG, "updateName: Setting name to " + newName);
db.execSQL(query);
}
public Integer deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?",new String[] {id});
}
public void deleteName(int id, String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE "
+ COL_1 + " = '" + id + "'" +
" AND " + COL_2 + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query);
}
public void updateScore(int newScore, int id, int oldScore){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET " + COL_3 +
" = '" + newScore + "' WHERE " + COL_1 + " = '" + id + "'" +
" AND " + COL_3 + " = '" + oldScore + "'";
Log.d(TAG, "updateName: query: " + query);
Log.d(TAG, "updateName: Setting name to " + newScore);
db.execSQL(query);
}
public void clearData()
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME,null,null);
db.close();
}}
Thanks for the help!
Not sure but it seems that the problem is here:
while(data.moveToNext())
It could be that moveToNext() is triggered on the move to the next item after leaving the previous one in other words it will be triggered for the first time after leaving item #1 behind)
Try using indexed loop instead.i.e. for (int i=0; ....
In this code:
while(data.moveToNext())
{
itemID = data.getInt(0);
}
It will trigger the moveToNext() function and then do the while. So you could solve it using a do while instead
do{
itemID = data.getInt(0);
}while(data.moveToNext())
In my research of using Cursor your initial setup is correct
while(data.moveToNext())...
Cursor starts before the rows and the initial call moveToNext() moves it to the first row.
One glaring issue is that you are not closing the Cursor.
while(data.moveToNext())
{
listData.add(data.getString(1) +
" " + data.getInt(2)); //get value from database at column 1, then add it to array list
}
// Close the Cursor here and again after the second one you create
data.close();
The second thing I see being a potential issue is that you are not accessing the correct value in the onClick
// int i might not be 0 at some point
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
i--;// maybe try subtracting 1 from i. Alternative is to do that when i is being used
String nametest = "";
int u = 0;
// or subtract here
while(!adapterView.getItemAtPosition(i-1).toString().substring(u,u+1).equals(" "))
{
nametest = nametest + adapterView.getItemAtPosition(i-1).toString().substring(u, u+1);
u = u + 1;
}

Update SQLite Database Android Application

I have an android Quote application in which I have used SQLite Database for storing quotes. I have launched the first version of the application with this DatabaseHelper.
public class DataBaseHandler extends SQLiteOpenHelper {
private static String DB_PATH;
private static String DB_NAME = "SuccessQuotes";
private SQLiteDatabase myDataBase;
private static int DATABASE_VERSION = 1;
private final Context myContext;
public DataBaseHandler(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
DB_PATH = context.getDatabasePath(DB_NAME).toString();
Log.e("path", DB_PATH);
}
// ==============================================================================
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
// ==============================================================================
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
// ==============================================================================
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
// ==============================================================================
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
// ==============================================================================
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
// ==============================================================================
#Override
public void onCreate(SQLiteDatabase db) {
}
// ==============================================================================
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
and my Database Activity is :
public class DAO {
// All Static variables
private SQLiteDatabase database;
private DataBaseHandler dbHandler;
private static final String TABLE_QUOTES = "quotes";
private static final String TABLE_AUTHORS = "authors";
private static final String TABLE_SETTINGS = "settings";
// Pages Table Columns names
private static final String QU_ID = "_quid";
private static final String QU_TEXT = "qu_text";
private static final String QU_AUTHOR = "qu_author";
private static final String QU_FAVORITE = "qu_favorite";
private static final String QU_WEB_ID = "qu_web_id";
private static final String AU_ID = "_auid";
private static final String AU_NAME = "au_name";
private static final String AU_PICTURE = "au_picture";
private static final String AU_PICTURE_SDCARD = "au_picture_sdcard";
private static final String AU_WEB_ID = "au_web_id";
// ==============================================================================
public DAO(Context context) {
dbHandler = new DataBaseHandler(context);
try {
dbHandler.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
dbHandler.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
// Log.e("path2", context.getDatabasePath("SuccessQuotes").toString());
// open();
}
// ==============================================================================
// Getting All Quotes
public Cursor getQuotes(String start) {
// Select All Query
String limit = "15";
if (start.equals("5000")) {
String query_count = "SELECT COUNT(" + QU_ID + ") AS count FROM "
+ TABLE_QUOTES;
Cursor c_count = database.rawQuery(query_count, null);
c_count.moveToFirst();
Integer count = c_count.getInt(c_count.getColumnIndex("count"));
limit = String.valueOf(count);
}
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " ORDER BY " + QU_WEB_ID + " DESC "+ " LIMIT " + start + ", " + limit;
//Log.i("query",query);
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting All Quotes
public Cursor getFavoriteQuotes(String start) {
// Select All Query
String limit = "15";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_FAVORITE + " = " + "1"+" ORDER BY " + QU_WEB_ID + " DESC "+ " LIMIT " + start + ", " + limit;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
//======================================================================
// Getting Fav Quote from ID
public String getFavQuotes(String strkey_id) {
// Select All Query
String fav = "";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_FAVORITE + " = " + "1 AND " + QU_ID + " = " +strkey_id;
Cursor cursor = database.rawQuery(query, null);
if(cursor.getCount() != 0)
{
cursor.moveToFirst();
fav = cursor.getString(cursor.getColumnIndex(QU_FAVORITE));
}
return fav;
}
// ==============================================================================
// Getting All Author Quotes
public Cursor getAuthorQuotes(String authorID,String start) {
// Select All Query
String limit="15";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_AUTHOR + " = " + authorID + " ORDER BY "+ QU_WEB_ID +" DESC "+ " LIMIT " + start + ", " + limit;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting Selected Quote
public Cursor getOneQuote(String quoteID) {
// Select All Query
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_ID + " = '" + quoteID + "'";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
public void addOrRemoveFavorites(String id, String value) {
ContentValues values = new ContentValues();
values.put(QU_FAVORITE, value);
// Update Row
// database.update(TABLE_QUOTES, values, QU_ID + "=?", new String[] { id });
database.update(TABLE_QUOTES, values, QU_ID + "=?", new String[] { id });
}
// ==============================================================================
// Getting All Authors
public Cursor getAllAuthors() {
// Select All Query
String query = "SELECT *, COUNT(" + QU_AUTHOR + ") AS count FROM "
+ TABLE_AUTHORS + " LEFT JOIN " + TABLE_QUOTES + " ON " + AU_WEB_ID
+ " = " + QU_AUTHOR + " GROUP BY " + AU_NAME ;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting Quotes Count
public Integer getQuotesCount() {
String query = "SELECT COUNT(" + QU_TEXT + ") AS count FROM "
+ TABLE_QUOTES;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
Integer count = cursor.getInt(cursor.getColumnIndex("count"));
return count;
}
// ==============================================================================
// Getting Quote ID
public Integer getQotdId() {
String query = "SELECT " + QU_ID + " FROM " + TABLE_QUOTES
+ " ORDER BY RANDOM() LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
Integer id = cursor.getInt(cursor.getColumnIndex(QU_ID));
return id;
}
// ==============================================================================
public void updateSetting(String field, String value) {
open();
ContentValues values = new ContentValues();
values.put(field, value);
// Update Row
database.update(TABLE_SETTINGS, values, null, null);
}
// ==============================================================================
public Cursor getSettings() {
open();
String query = "SELECT * FROM " + TABLE_SETTINGS;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
public int getLastAuthor() {
String query = "SELECT " + AU_WEB_ID + " FROM " + TABLE_AUTHORS
+ " ORDER BY " + AU_WEB_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor.getInt(cursor.getColumnIndex(AU_WEB_ID));
}
// ==============================================================================
public int getLastQuote() {
String query = "SELECT " + QU_WEB_ID + " FROM " + TABLE_QUOTES
+ " ORDER BY " + QU_WEB_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor.getInt(cursor.getColumnIndex(QU_WEB_ID));
}
// ==============================================================================
public void addAuthor(String au_name, String au_picture, int au_web_id) {
open();
ContentValues v = new ContentValues();
v.put(AU_NAME, au_name);
v.put(AU_PICTURE, au_picture);
v.put(AU_PICTURE_SDCARD, 1);
v.put(AU_WEB_ID, au_web_id);
database.insert(TABLE_AUTHORS, null, v);
}
// ==============================================================================
public void addQuote(String qu_text, int qu_author, int qu_web_id) {
open();
ContentValues v = new ContentValues();
v.put(QU_TEXT, qu_text);
v.put(QU_AUTHOR, qu_author);
v.put(QU_FAVORITE, "0");
v.put(QU_WEB_ID, qu_web_id);
database.insert(TABLE_QUOTES, null, v);
}
// ==============================================================================
public void open() throws SQLException {
// database = dbHandler.getReadableDatabase();
database = dbHandler.getWritableDatabase();
}
// ==============================================================================
public void closeDatabase() {
dbHandler.close();
}
Now if I want to update application with more quotes, which changes should I make so that the new and old users don't face any issue ?
I am not expert Android developer, so Please explain me little more if possible, I will very thankful for it.
Thanks
Thanks
Try this just add quote to the database just like this here i add contact same way u can add quote to database
//Add new Contact by calling this method
public void addContact(Contact contact)
{
// getting db instance for writing the contact
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(Contact_fname,contact.getFname());
cv.put(Contact_lname,contact.getLname());
cv.put(Contact_number,contact.getContactnumber());
//inserting row
db.insert(Table_Name, null, cv);
//close the database to avoid any leak
db.close();
}
Refer here https://androidruler.wordpress.com/2016/02/22/android-working-with-sqlite-database/
simply increase your database version and onUpgrade() will call automatically
private static int DATABASE_VERSION = 2;
and add your database table field inside this function
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}

Categories

Resources