Update SQLite Database Android Application - java

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) {
}

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.

App is not fetching mysql db in release version in Android Pie 9

I am facing a weird issue in my app. App works smooth in all devices but not fetching data from mysql database in android pie in release version. In emulator its fine but not working on real device. I am a teacher and the app is quiz for my students any help will be appreciated
Thanks in advance
Here is my DB helper class
I have added network_secrity xml file.
Here is my db helper
public class DBHelper extends SQLiteOpenHelper {
//database version
private static int db_version = 1;
//database name
private static String db_name = "quiz_level.db";
//database path string
private String db_path;
private SQLiteDatabase db;
private final Context context;
//table name
public static String TABLE_NAME = "level";
//column names
public static String CATE_ID = "cat_id";
public static String SUB_CATE_ID = "sub_cat_id";
public static String LEVEL_NO = "level_no";
public DBHelper(Context context) {
super(context, db_name, null, db_version);
this.context = context;
File database = context.getDatabasePath(db_name);
if (!database.exists()) {
// Database does not exist so copy it from assets here
db_path = context.getDatabasePath(db_name).toString().replace(db_name, "");
} else {
db_path = context.getDatabasePath(db_name).toString();
}
}
#Override
public SQLiteDatabase getReadableDatabase() {
return super.getReadableDatabase();
}
#Override
public SQLiteDatabase getWritableDatabase() {
return super.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
db.disableWriteAheadLogging();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
//delete database
public void db_delete() {
File file = new File(db_path + db_name);
if (file.exists()) {
file.delete();
}
}
//Create a empty database on the system
public void createDatabase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
Log.v("DB Exists", "db exists");
}
boolean dbExist1 = checkDataBase();
if (!dbExist1) {
this.getWritableDatabase();
try {
this.close();
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
//Check database already exist or not
private boolean checkDataBase() {
boolean checkDB = false;
try {
String myPath = db_path + db_name;
File dbfile = new File(myPath);
checkDB = dbfile.exists();
} catch (SQLiteException e) {
}
return checkDB;
}
//Copies your database from your local assets-folder to the just created empty database in the system folder
private void copyDataBase() throws IOException {
String outFileName = db_path + db_name;
OutputStream myOutput = new FileOutputStream(outFileName);
InputStream myInput = context.getAssets().open(db_name);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
myOutput.flush();
myOutput.close();
}
/*
* insert level no
*/
public void insertIntoDB(int cat_id, int sub_cat_id, int level_no) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "INSERT INTO " + TABLE_NAME + " (" + CATE_ID + "," + SUB_CATE_ID + "," + LEVEL_NO + ") VALUES('" + cat_id + "', '" + sub_cat_id + "', '" + level_no + "');";
db.execSQL(query);
}
/*
*with this method we check if categoryId & subCategoryId is already exist or not in our database
*/
public boolean isExist(int cat_id, int sub_cat_id) {
db = this.getReadableDatabase();
Cursor cur = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE ( " + CATE_ID + " = " + cat_id + " AND " + SUB_CATE_ID + " = " + sub_cat_id + ")", null);
boolean exist = (cur.getCount() > 0);
cur.close();
System.out.println("---isExit " + (cur.getCount() > 0));
return exist;
}
/*
* get level
*/
public int GetLevelById(int cat_id, int sub_cat_id) {
int level = 1;
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE (" + CATE_ID + "=" + cat_id + " AND " + SUB_CATE_ID + "=" + sub_cat_id + ")";
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
level = c.getInt(c.getColumnIndex(LEVEL_NO));
} while (c.moveToNext());
}
return level;
}
/*
* Update lavel
*/
public void UpdateLevel(int cat_id, int sub_cat_id, int level_no) {
db = this.getReadableDatabase();
db.execSQL("update " + TABLE_NAME + " set level_no=" + level_no + " where (cat_id =" + cat_id + " and " + sub_cat_id + " = " + sub_cat_id + ")");
}}

Increment a counter in database SQLite

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.

Updating Database in Android

I am updating a record in Sqlite database through the function given below.Their is only 1 Table and a number of columns.Initially i am updating 3 columns. Problem i am facing :
1) The Problem is that in Logcat initial data is shown but updated data is not showing. Also Logcat not showing any error.
2) When i am displaying in Toast only last value which i added in database statically is showing. Initial two are not present in Toast.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class ContractSqlite extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "thorcontract_Db";
// TABLE NAME
private static final String TABLE_NAME = "contract";
// COLUMN
private static final String PRIMARY_COLUMN = "heading";
private static final String CONTRACT_TITLES_TITLE = "cnttitle";
private static final String CONTRACT_TITLES_SUBTITLE = "cntSUBTITLE";
private static final String CONTRACT_TITLES_BIDID = "cntbidid";
private static final String LOADSUMMARY_HEADER = "lsheader";
private static final String LOADSUMMARY_FOOTER = "lsfooter";
private static final String SECTION1_TITLE = "s1title";
private static final String SECTION1_BODY = "s1body";
private static final String SECTION2_TITLE = "s2title";
private static final String SECTION2_BODY = "s2body";
private static final String SECTION3_TITLE = "s3title";
private static final String SECTION3_BODY = "s3body";
private static final String SECTION4_TITLE = "s4title";
private static final String SECTION4_BODY = "s4body";
private static final String SECTION5_TITLE = "s5title";
private static final String SECTION5_BODY = "s5body";
private static final String SECTION6_TITLE = "s6title";
private static final String SECTION6_BODY = "s6body";
private static final String SECTION7_TITLE = "s7title";
private static final String SECTION7_BODY = "s7body";
private static final String SECTION8_TITLE = "s8title";
private static final String SECTION8_BODY = "s8body";
private static final String SECTION9_TITLE = "s9title";
private static final String SECTION9_BODY = "s9body";
private String title = null, subtitle = null, bidid = null;
public ContractSqlite(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_CONTRACT_TABLE = " CREATE TABLE " + TABLE_NAME + "("
+ PRIMARY_COLUMN + " INTEGER PRIMARY KEY,"
+ CONTRACT_TITLES_TITLE + " TEXT ," + CONTRACT_TITLES_SUBTITLE
+ " TEXT ," + CONTRACT_TITLES_BIDID + " TEXT,"
+ LOADSUMMARY_HEADER + " TEXT," + LOADSUMMARY_FOOTER + " TEXT,"
+ SECTION1_TITLE + " TEXT," + SECTION1_BODY + " TEXT,"
+ SECTION2_TITLE + " TEXT," + SECTION2_BODY + " TEXT,"
+ SECTION3_TITLE + " TEXT," + SECTION3_BODY + " TEXT,"
+ SECTION4_TITLE + " TEXT," + SECTION4_BODY + " TEXT,"
+ SECTION5_TITLE + " TEXT," + SECTION5_BODY + " TEXT,"
+ SECTION6_TITLE + " TEXT," + SECTION6_BODY + " TEXT,"
+ SECTION7_TITLE + " TEXT," + SECTION7_BODY + " TEXT,"
+ SECTION8_TITLE + " TEXT," + SECTION8_BODY + " TEXT,"
+ SECTION9_TITLE + " TEXT," + SECTION9_BODY + " TEXT" + ")";
db.execSQL(CREATE_CONTRACT_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE" + TABLE_NAME);
onCreate(db);
}
public void addRecord(String title, String subtitle, String bidid) {
SQLiteDatabase db = this.getWritableDatabase();
// String title1 = title;
// String subtitle1 = subtitle;
// String bidid1 = bidid;
ContentValues values = new ContentValues();
try {
values.put(CONTRACT_TITLES_TITLE, title);
values.put(CONTRACT_TITLES_SUBTITLE, subtitle);
values.put(CONTRACT_TITLES_BIDID, bidid);
db.insert(TABLE_NAME, null, values);
Log.i("Initial Data", " " + title + " " + subtitle + " " + bidid);
db.close();
} catch (Exception e) {
db.close();
}
}
public String[] getrecord() {
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.moveToFirst()) {
title = cursor.getString(cursor
.getColumnIndex(CONTRACT_TITLES_TITLE));
subtitle = cursor.getString(cursor
.getColumnIndex(CONTRACT_TITLES_SUBTITLE));
bidid = cursor.getString(cursor
.getColumnIndex(CONTRACT_TITLES_BIDID));
// Dumps "Title: Test Title Content: Test Content"
Log.i("CONTRACTTITLES", "Title: " + title + " Content: " + subtitle);
cursor.close();
}
return new String[] { title, subtitle, bidid };
}
public int update(String title, String subtitle, String id) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CONTRACT_TITLES_TITLE, title);
values.put(CONTRACT_TITLES_SUBTITLE, subtitle);
values.put(CONTRACT_TITLES_SUBTITLE, id);
return db.update(TABLE_NAME, values, PRIMARY_COLUMN + " =?",
new String[] { String.valueOf(1) });
}
}
Method Calling From Main Activity.
csq is database class object
for adding a record
csq.addRecord("abc", "xyz", "1234");
for updating
csq.update(cnttitle_str, cntsubtitle_str, cntbid_str);
for getting a record
String[] str = csq.getrecord();
Toast.makeText(getActivity(),
" " + str[0] + " " + str[1] + "" + str[2], Toast.LENGTH_LONG).show();
Updated data is not showing because you don't have a Log line there (if I understand you correctly).
You only get one line because you need to iterate through the Cursor and return a list or some such.
this sulotion is :
if you want to see all record , do this in your Database class :
public void showAllDBcells() {
String selectQuery = "SELECT * FROM " + TABLE_DB;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Log.d("your tag",cursor.getString(0));
Log.d("your tag",cursor.getString(1));
Log.d("your tag",cursor.getString(2));
// and for another data , just extends code for 3 4 5 ... columns
} while (cursor.moveToNext());
}
//
cursor.close();
db.close();
}
you can call method in your activity , and see your stored data from Database in Logcat .

Set radio buttons based on table in Database

I have 2 activities, the first one is the DataBase helper and the second one is the main activity.
Now, I am trying to set radio buttons based on the name that are on table DATABASE_TABLE_SETTINGS in the column KEY_b_NAME.
I tried to set the following code on the main activity and get a cursor that checks if !c.isAfterLast, and if this is true I want it to set new radio button with the id of KEY_ROW_b_ID and the name of KEY_b_NAME.
after lunching it, I get this error:
05-27 19:33:44.055: E/AndroidRuntime(2189): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tamar.efrat/com.tamar.efrat.Tamar_appActivity}: java.lang.NullPointerException
The for loop in the main activity is:
DatBas dbc = new DatBas(Tamar_appActivity.this);
dbc.open();
SQLiteDatabase tdb = null;
String[] columns = new String[] { DatBas.KEY_ROW_B_ID, DatBas.KEY_B_NAME };
Cursor c = tdb.query(DatBas.DATABASE_TABLE_SETTINGS, columns, null, null, null, null,
null);
int iRawBId = c.getColumnIndex(DatBas.KEY_ROW_B_ID);
int iBName = c.getColumnIndex(DatBas.KEY_B_NAME);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
RadioGroup radiogroup = (RadioGroup)
findViewById(R.id.bNameSelectGroup);
RadioButton rdbtn = new RadioButton(this);
rdbtn.setId(iRawBId);
rdbtn.setText(iBName);
radiogroup.addView(rdbtn);
}
dbc.close();
The code of the DataBase helper is:
public class DatBas {
public static final String KEY_ROWID = "_id";
public static final String KEY_SHOURS = "start_hour";
public static final String KEY_SMINUTE = "start_minute";
public static final String KEY_SDATE = "start_date";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_SIDE = "side";
public static final String KEY_KIND = "kind";
public static final String KEY_ROW_b_ID = "_id";
public static final String KEY_b_IMAGE_PATH = "uri_b";
public static final String KEY_b_NAME = "b_name";
public static final String KEY_b_GENDER = "b_gender";
public static final String KEY_b_BORN_DATE_YEAR = "b_age_year";
public static final String KEY_b_BORN_DATE_MONTH = "b_age_month";
public static final String KEY_b_BORN_DATE_DAY = "b_age_day";
private static final String DATABASE_NAME = "TamatDB";
private static final String DATABASE_TABLE = "stop_watch_records";
private static final String DATABASE_TABLE_SETTINGS = "settings";
private static final int DATABASE_VERSION = 3 ;
private TamarDatabase thdb;
private static Context tcontext;
private SQLiteDatabase tdb;
private static class TamarDatabase extends SQLiteOpenHelper {
public TamarDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String ctData = "CREATE TABLE " + DATABASE_TABLE + " ( "
+ KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_SHOURS + " TEXT, " + KEY_SMINUTE
+ " TEXT, " + KEY_SDATE + " TEXT, "
+ KEY_AMOUNT + " TEXT, " + KEY_SIDE
+ " TEXT, " + KEY_KIND + " TEXT );";
db.execSQL(ctData);
String ctSettings = "CREATE TABLE " + DATABASE_TABLE_SETTINGS
+ " ( " + KEY_ROW_b_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_b_IMAGE_PATH + " TEXT, " + KEY_b_NAME
+ " TEXT, " + KEY_b_GENDER + " TEXT, "
+ KEY_b_BORN_DATE_YEAR + " TEXT, "
+ KEY_b_BORN_DATE_MONTH + " TEXT, "
+ KEY_b_BORN_DATE_DAY + " TEXT);";
db.execSQL(ctSettings);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_SETTINGS);
onCreate(db);
}
}
public DatBas(Context c) {
tcontext = c;
}
public DatBas open() throws SQLiteException {
thdb = new TamarDatabase(tcontext);
tdb = thdb.getWritableDatabase();
return this;
}
public SQLiteDatabase getReadableDatabase() throws SQLiteException {
thdb = new TamarDatabase(tcontext);
tdb = thdb.getReadableDatabase();
return tdb;
}
public void close() {
tdb.close();
}
public long createEntry(String sh, String sm, String sd, String at,
String tside, String tkind) {
ContentValues cv = new ContentValues();
cv.put(KEY_SHOURS, sh);
cv.put(KEY_SMINUTE, sm);
cv.put(KEY_SDATE, sd);
cv.put(KEY_AMOUNT, at);
cv.put(KEY_SIDE, tside);
cv.put(KEY_SIDE, tkind);
return tdb.insert(DATABASE_TABLE, null, cv);
}
public long createEntrySettings(String pt, String bn, String bg,
String bbdy, String bbdm, String bbdd) {
ContentValues cv2 = new ContentValues();
cv2.put(KEY_b_IMAGE_PATH, pt);
cv2.put(KEY_b_NAME, bn);
cv2.put(KEY_b_GENDER, bg);
cv2.put(KEY_b_BORN_DATE_YEAR, bbdy);
cv2.put(KEY_b_BORN_DATE_MONTH, bbdm);
cv2.put(KEY_b_BORN_DATE_DAY, bbdd);
return tdb.insert(DATABASE_TABLE_SETTINGS, null, cv2);
}
public String getData() {
String[] columns = new String[] { KEY_ROWID, KEY_SHOURS, KEY_SMINUTE,
KEY_SDATE, KEY_AMOUNT, KEY_SIDE, KEY_KIND };
Cursor c = tdb.query(DATABASE_TABLE, columns, null, null, null, null,
null);
String results = "";
int iRaw = c.getColumnIndex(KEY_ROWID);
int iShours = c.getColumnIndex(KEY_SHOURS);
int iSminute = c.getColumnIndex(KEY_SMINUTE);
int iDate = c.getColumnIndex(KEY_SDATE);
int iAmount = c.getColumnIndex(KEY_AMOUNT);
int iSide = c.getColumnIndex(KEY_SIDE);
int iKind = c.getColumnIndex(KEY_KIND);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
results = results + "the id is " + c.getString(iRaw)
+ " the sart hour is " + " " + c.getString(iShours)
+ " the start minute is " + " " + c.getString(iSminute)
+ " the start date is " + " " + c.getString(iDate)
+ " the amount is " + " " + c.getString(iAmount)
+ " the side is " + " " + c.getString(iSide)
+ " the kind is " + " " + c.getString(iKind) + "\n";
}
return results;
}
public String getDataSettings() {
String[] columns = new String[] { KEY_ROW_b_ID, KEY_b_IMAGE_PATH,
KEY_b_NAME, KEY_b_GENDER, KEY_b_BORN_DATE_YEAR,
KEY_b_BORN_DATE_MONTH, KEY_b_BORN_DATE_DAY };
Cursor c = tdb.query(DATABASE_TABLE_SETTINGS, columns, null, null,
null, null, null);
String results = "";
int iRawbId = c.getColumnIndex(KEY_ROW_b_ID);
int iBIPath = c.getColumnIndex(KEY_b_IMAGE_PATH);
int iBName = c.getColumnIndex(KEY_b_NAME);
int iGender = c.getColumnIndex(KEY_b_GENDER);
int iBBDateYear = c.getColumnIndex(KEY_b_BORN_DATE_YEAR);
int iBBDateMonth = c.getColumnIndex(KEY_b_BORN_DATE_MONTH);
int iBBDateDay = c.getColumnIndex(KEY_b_BORN_DATE_DAY);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
results = results + " id " + " " + c.getString(iRawbId)
+ " path " + " " + c.getString(iBIPath)
+ " name " + " " + c.getString(iBName)
+ " gender " + " " + c.getString(iGender)
+ " year " + " " + c.getString(iBBDateYear)
+ " month " + " " + c.getString(iBBDateMonth)
+ " day " + " " + c.getString(iBBDateDay) + "\n";
}
return results;
}
public String getDataSettingsbName() {
String[] columns = new String[] { KEY_ROW_b_ID, KEY_b_NAME };
Cursor c = tdb.query(DATABASE_TABLE_SETTINGS, columns, null, null,
null, null, null);
String results = "";
int iRawbId = c.getColumnIndex(KEY_ROW_b_ID);
int iBName = c.getColumnIndex(KEY_b_NAME);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
results = c.getString(iRawbId)+ c.getString(iBName)+ "\n";
}
return results;
}
public DatBas delete() {
tdb.delete(DATABASE_TABLE, null, null);
tdb.delete(DATABASE_TABLE_SETTINGS, null, null);
return null;
}
}
Your Sqlitedatabase instance is null so it throws a NullPointerException when you try to do a query on it:
SQLiteDatabase tdb = null; // this is null so when you query the database it will throw an exception
String[] columns = new String[] { DatBas.KEY_ROW_B_ID, DatBas.KEY_B_NAME };
Cursor c = tdb.query(DatBas.DATABASE_TABLE_SETTINGS, columns, null, null, null, null,
null);
Instead get a reference to a valid SQLiteDatabase:
SQLiteDatabase tdb = dbc.getDatabase();
String[] columns = new String[] { DatBas.KEY_ROW_B_ID, DatBas.KEY_B_NAME };
Cursor c = tdb.query(DatBas.DATABASE_TABLE_SETTINGS, columns, null, null, null, null,
null);
where getDatabase() is a method in your DatBas class like this:
public SQliteDatabase getDatabase() {
return tdb;
}
Also, remove the method getReadableDatabase() from your DatBas class.

Categories

Resources