Null pointer exception SQLite Alarm database - java

Hey devs I am new to android development I am facing a problem I m creating a alarm app which timings I myself insert into the database and I want the alarm to trigger at that time.
Here is my code for MainActivity
public class MainActivity extends Activity {
final String PREF_NAME = "Preferences";
Context context;
static PendingIntent pendingIntent;
static AlarmManager alarmManager;
Switch switch1;
Intent intentAlarm;
DatabaseHandler dhb = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Calendar cal = Calendar.getInstance();
intentAlarm = new Intent(context, AlarmReciver.class);
// setting Time!
Log.d("Insert: ", "Inserting...");
dhb.createAlarm(new AlarmModel(1, 1, 21, 5));
context = MainActivity.this;
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
switch1 = (Switch) findViewById(R.id.tgButton);
switch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (seherBtn.isChecked()) {
List<AlarmModel> alarms = dhb.getAlarms();
for (AlarmModel al : alarms) {
pendingIntent = PendingIntent.getBroadcast(context,
al.getId(), intentAlarm,
PendingIntent.FLAG_UPDATE_CURRENT);
cal.set(Calendar.MONTH, 6);
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.DAY_OF_MONTH, al.getDay());
cal.set(Calendar.HOUR_OF_DAY, al.getTimeHour());
cal.set(Calendar.MINUTE, al.getTimeMinute());
cal.set(Calendar.SECOND, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), pendingIntent);
}
} else {
alarmManager.cancel(pendingIntent);
}
}
});
}
And my DatabaseHelper class
Please help me if I m going wrong somewhere and please suggest me the possible solution
Thanks...
public class DatabaseHandler extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "alarmClock.db";
public static final String TABLE_NAME = "alarm";
public static final String COLUMN_NAME_ALARM_NAME = "name";
public static final String COLUMN_NAME_ALARM_TIME_HOUR = "hour";
public static final String COLUMN_NAME_ALARM_TIME_MINUTE = "minute";
public static final String COLUMN_NAME_ALARM_DAYS = "days";
public static final String ID = "id";
private static final String SQL_CREATE_ALARM = "CREATE TABLE " + TABLE_NAME
+ " (" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME_ALARM_NAME + " TEXT," + COLUMN_NAME_ALARM_TIME_HOUR
+ " INTEGER," + COLUMN_NAME_ALARM_TIME_MINUTE + " INTEGER,"
+ COLUMN_NAME_ALARM_DAYS + " INTEGER," + " )";
private static final String SQL_DELETE_ALARM = "DROP TABLE IF EXISTS "
+ TABLE_NAME;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ALARM);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_ALARM);
}
private AlarmModel populateModel(Cursor c) {
AlarmModel model = new AlarmModel();
model.id = c.getInt(c.getColumnIndex(ID));
model.timeHour = c
.getInt(c.getColumnIndex(COLUMN_NAME_ALARM_TIME_HOUR));
model.timeMinute = c.getInt(c
.getColumnIndex(COLUMN_NAME_ALARM_TIME_MINUTE));
model.day = c.getInt(c.getColumnIndex(COLUMN_NAME_ALARM_DAYS));
return model;
}
private ContentValues populateContent(AlarmModel model) {
ContentValues values = new ContentValues();
values.put(COLUMN_NAME_ALARM_TIME_HOUR, model.timeHour);
values.put(COLUMN_NAME_ALARM_TIME_MINUTE, model.timeMinute);
values.put(COLUMN_NAME_ALARM_DAYS, model.day);
return values;
}
public long createAlarm(AlarmModel model) {
ContentValues values = populateContent(model);
return getWritableDatabase().insert(TABLE_NAME, null, values);
}
public AlarmModel getAlarm(long id) {
SQLiteDatabase db = this.getReadableDatabase();
String select = "SELECT * FROM " + TABLE_NAME + " WHERE " + ID + " = "
+ id;
Cursor c = db.rawQuery(select, null);
if (c.moveToNext()) {
return populateModel(c);
}
return null;
}
public long updateAlarm(AlarmModel model) {
ContentValues values = populateContent(model);
return getWritableDatabase().update(TABLE_NAME, values, ID + " = ?",
new String[] { String.valueOf(model.id) });
}
public int deleteAlarm(long id) {
return getWritableDatabase().delete(TABLE_NAME, ID + " = ?",
new String[] { String.valueOf(id) });
}
public List<AlarmModel> getAlarms() {
SQLiteDatabase db = this.getReadableDatabase();
String select = "SELECT * FROM " + TABLE_NAME;
Cursor c = db.rawQuery(select, null);
List<AlarmModel> alarmList = new ArrayList<AlarmModel>();
while (c.moveToNext()) {
alarmList.add(populateModel(c));
}
if (!alarmList.isEmpty()) {
return alarmList;
}
return null;
}
}

Related

How to save sqlite database firebase notification android

I need to save the title, post id message in firebase in sqlite database. I have tried many times but I don't get any answer. If you know please let me know.For me notification title, post_id, link these three are coming as array. If you send firebase notification, it should be automatic or save
`public class MyFirebaseMessageService extends FirebaseMessagingService {
#Override
public void onNewToken(#NonNull String token) {
super.onNewToken(token);
}
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getData().size() > 0) {
Map<String, String> data = remoteMessage.getData();
Log.d("onMessageFirebase: ", remoteMessage.getData().toString());
if (data.get("post_id") != null) {
String _unique_id = data.get("unique_id");
String title = data.get("title");
String message = data.get("message");
String big_image = data.get("big_image");
String link = data.get("link");
String _post_id = data.get("post_id");
assert _unique_id != null;
long unique_id = Long.parseLong(_unique_id);
assert _post_id != null;
long post_id = Long.parseLong(_post_id);
createNotification(unique_id, title, message, big_image, link, post_id);
}
}
}
private void createNotification(long unique_id, String title, String message, String image_url, String link, long post_id) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("unique_id", unique_id);
intent.putExtra("post_id", post_id);
intent.putExtra("title", title);
intent.putExtra("link", link);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = getApplicationContext().getString(R.string.app_name);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(getNotificationIcon(notificationBuilder))
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_notification_large_icon))
.setContentTitle(title)
.setContentText(message)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
notificationBuilder.setPriority(Notification.PRIORITY_MAX);
} else {
notificationBuilder.setPriority(NotificationManager.IMPORTANCE_HIGH);
}
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationBuilder.setSound(alarmSound).setVibrate(new long[]{100, 200, 300, 400});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.shouldShowLights();
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(false);
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);
}
if (image_url != null && !image_url.isEmpty()) {
Bitmap image = fetchBitmap(image_url);
if (image != null) {
notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image));
}
}
//assert notificationManager != null;
notificationManager.notify((int) post_id, notificationBuilder.build());
}
private int getNotificationIcon(NotificationCompat.Builder notificationBuilder) {
notificationBuilder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
return R.drawable.ic_stat_onesignal_default;
}
private Bitmap fetchBitmap(String src) {
try {
if (src != null) {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setConnectTimeout(1200000);
connection.setReadTimeout(1200000);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
}
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
}``
DBHELPER
public class DbHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "db_recipes_favorite";
private static final String TABLE_NAME = "tbl_recipes_favorite";
private static final String notification = "tbl_notification";
private static final String KEY_ID = "id";
private static final String KEY_CAT_NAME = "category_name";
private static final String KEY_RECIPE_ID = "recipe_id";
private static final String KEY_RECIPE_TITLE = "recipes_title";
private static final String KEY_calories = "calories";
private static final String KEY_servings = "servings";
private static final String KEY_RECIPE_TIME = "recipe_time";
private static final String KEY_RECIPE_IMAGE = "recipe_image";
private static final String KEY_RECIPE_DESCRIPTION = "recipe_description";
private static final String KEY_RECIPE_DESCRIPTION2 = "recipe_description2";
private static final String KEY_RECIPE_DESCRIPTION3 = "recipe_description3";
private static final String KEY_VIDEO_URL = "video_url";
private static final String KEY_VIDEO_ID = "video_id";
private static final String KEY_CONTENT_TYPE = "content_type";
private static final String KEY_FEATURED = "featured";
private static final String KEY_TAGS = "tags";
private static final String KEY_TOTAL_VIEWS = "total_views";
public DbHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_CAT_NAME + " TEXT,"
+ KEY_RECIPE_ID + " TEXT,"
+ KEY_RECIPE_TITLE + " TEXT,"
+ KEY_calories + " TEXT,"
+ KEY_servings + " TEXT,"
+ KEY_RECIPE_TIME + " TEXT,"
+ KEY_RECIPE_IMAGE + " TEXT,"
+ KEY_RECIPE_DESCRIPTION + " TEXT,"
+ KEY_RECIPE_DESCRIPTION2 + " TEXT,"
+ KEY_RECIPE_DESCRIPTION3 + " TEXT,"
+ KEY_VIDEO_URL + " TEXT,"
+ KEY_VIDEO_ID + " TEXT,"
+ KEY_CONTENT_TYPE + " TEXT,"
+ KEY_FEATURED + " TEXT,"
+ KEY_TAGS + " TEXT,"
+ KEY_TOTAL_VIEWS + " TEXT"
+ ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
// Create tables again
onCreate(db);
}
//Adding Record in Database
public void AddtoFavorite(Recipe p) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_CAT_NAME, p.getCategory_name());
values.put(KEY_RECIPE_ID, p.getRecipe_id());
values.put(KEY_RECIPE_TITLE, p.getRecipe_title());
values.put(KEY_calories, p.getcalories());
values.put(KEY_servings, p.getservings());
values.put(KEY_RECIPE_TIME, p.getRecipe_time());
values.put(KEY_RECIPE_IMAGE, p.getRecipe_image());
values.put(KEY_RECIPE_DESCRIPTION, p.getRecipe_description());
values.put(KEY_RECIPE_DESCRIPTION2, p.getRecipe_description());
values.put(KEY_RECIPE_DESCRIPTION3, p.getRecipe_description());
values.put(KEY_VIDEO_URL, p.getVideo_url());
values.put(KEY_VIDEO_ID, p.getVideo_id());
values.put(KEY_CONTENT_TYPE, p.getContent_type());
values.put(KEY_FEATURED, p.getFeatured());
values.put(KEY_TAGS, p.getTags());
values.put(KEY_TOTAL_VIEWS, p.getTotal_views());
// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close(); // Closing database connection
}
public void notification(Recipe p) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_RECIPE_ID, p.getRecipe_id());
values.put(KEY_RECIPE_TITLE, p.getRecipe_title());
values.put(KEY_RECIPE_IMAGE, p.getRecipe_image());
// Inserting Row
db.insert(notification, null, values);
db.close(); // Closing database connection
}
// Getting All Data
public List<Recipe> getAllData() {
List<Recipe> dataList = new ArrayList<Recipe>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME + " ORDER BY id DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Recipe values = new Recipe();
values.setId(Integer.parseInt(cursor.getString(0)));
values.setCategory_name(cursor.getString(1));
values.setRecipe_id(cursor.getString(2));
values.setRecipe_title(cursor.getString(3));
values.setcalories(cursor.getString(4));
values.setservings(cursor.getString(5));
values.setRecipe_time(cursor.getString(6));
values.setRecipe_image(cursor.getString(7));
values.setRecipe_description(cursor.getString(8));
values.setRecipe_description2(cursor.getString(9));
values.setRecipe_description3(cursor.getString(10));
values.setVideo_url(cursor.getString(11));
values.setVideo_id(cursor.getString(12));
values.setContent_type(cursor.getString(13));
values.setFeatured(cursor.getString(14));
values.setTags(cursor.getString(15));
values.setTotal_views(cursor.getLong(16));
// Adding contact to list
dataList.add(values);
} while (cursor.moveToNext());
}
// return contact list
return dataList;
}
//getting single row
public List<Recipe> getFavRow(String id) {
List<Recipe> dataList = new ArrayList<Recipe>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE recipe_id=" + id;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Recipe values = new Recipe();
values.setId(Integer.parseInt(cursor.getString(0)));
values.setCategory_name(cursor.getString(1));
values.setRecipe_id(cursor.getString(2));
values.setRecipe_title(cursor.getString(3));
values.setcalories(cursor.getString(4));
values.setservings(cursor.getString(5));
values.setRecipe_time(cursor.getString(6));
values.setRecipe_image(cursor.getString(7));
values.setRecipe_description(cursor.getString(8));
values.setRecipe_description2(cursor.getString(9));
values.setRecipe_description3(cursor.getString(10));
values.setVideo_url(cursor.getString(11));
values.setVideo_id(cursor.getString(12));
values.setContent_type(cursor.getString(13));
values.setFeatured(cursor.getString(14));
values.setTags(cursor.getString(15));
values.setTotal_views(cursor.getLong(16));
// Adding contact to list
dataList.add(values);
} while (cursor.moveToNext());
}
// return contact list
return dataList;
}
//for remove favorite
public void RemoveFav(Recipe contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_RECIPE_ID + " = ?",
new String[]{String.valueOf(contact.getRecipe_id())});
db.close();
}
public enum DatabaseManager {
INSTANCE;
private SQLiteDatabase db;
private boolean isDbClosed = true;
DbHandler dbHelper;
public void init(Context context) {
dbHelper = new DbHandler(context);
if (isDbClosed) {
isDbClosed = false;
this.db = dbHelper.getWritableDatabase();
}
}
public boolean isDatabaseClosed() {
return isDbClosed;
}
public void closeDatabase() {
if (!isDbClosed && db != null) {
isDbClosed = true;
db.close();
dbHelper.close();
}
}
}
}`
How to save sqlite database firebase notification android

Get value from cursor everytime when database is updated

I've got two activities. One is updating value in database from edittext and in the second activity i want put this value from database into textview. At the first time when i update value everything goes well but at the second time textview cant be updated and i see in the Textview value "0". When i gave breakpoints i see that my cursor didnt want to take value second time. Any suggestion what should i do ? It's problem with lifecycle of activity or what? There is my code. Any example or suggestion will be very helpful for me.
public class DzienPierwszy extends AppCompatActivity {
Button button;
OpenHelper1 mDb;
TextView pp1,pp2,pp3,s1,s2,s3,p1,p2,p3,pn,sr,pt,nd;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.dzien_treningu);
p1 = (TextView) findViewById(R.id.p1);
p2 = (TextView) findViewById(R.id.p2);
p3 = (TextView) findViewById(R.id.p3);
s1 = (TextView) findViewById(R.id.s1);
s2 = (TextView) findViewById(R.id.s2);
s3 = (TextView) findViewById(R.id.s3);
pp1 = (TextView) findViewById(R.id.pp1);
pp2 = (TextView) findViewById(R.id.pp2);
pp3 = (TextView) findViewById(R.id.pp3);
pn = (TextView) findViewById(R.id.pn);
sr = (TextView) findViewById(R.id.sr);
pt = (TextView) findViewById(R.id.pt);
nd = (TextView) findViewById(R.id.nd);
Intent i = getIntent();
final String product = i.getStringExtra("cwiczenie ");
int lol1=0;
mDb = new OpenHelper1(this);
mDb.open();
// fetch data about 1 row in database table
Cursor test = mDb.fetchOneCwiczenie(product);
mDb.close();
if( test != null && test.moveToFirst() ){
//get value from column
lol1 = test.getInt(test.getColumnIndex("score"));
test.close();
}
p1.setText(String.valueOf(Math.round(lol1*0.55)));
p2.setText(String.valueOf(Math.round(lol1*0.79)));
p3.setText(String.valueOf(Math.round(lol1*0.67)));
s1.setText(String.valueOf(Math.round(lol1*0.67)));
s2.setText(String.valueOf(Math.round(lol1*0.91)));
s3.setText(String.valueOf(Math.round(lol1*0.79)));
pp1.setText(String.valueOf(Math.round(lol1*0.79)));
pp2.setText(String.valueOf(Math.round(lol1*1.03)));
pp3.setText(String.valueOf(Math.round(lol1*0.91)));
}
public void open(View view) {
Intent intent = new Intent(getApplicationContext(),TestActivity.class);
startActivity(intent);
}
}
public class OpenHelper1{
private static final String TAG = "TreningDbAdapter";
public DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private final ContentResolver resolver =null;
private final Context mCtx;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "menadzerCwiczen1";
public static final String TABLE_CWICZENIA = "cwiczenia";
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_KIND = "kind";
public static final String KEY_URL = "url";
public static final String KEY_SCORE = "score";
public static final String KEY_SERIES = "series";
static final String PROVIDER_NAME = "com.example.jacek.gympartner.SQLite";
static final String URL = "content://" + PROVIDER_NAME + "/cwiczenia";
static final Uri CONTENT_URI = Uri.parse(URL);
private static HashMap<String, String> CWICZENIA_PROJECTION_MAP;
static final int CWICZENIA = 1;
static final int CWICZENIE_ID = 2;
static final UriMatcher uriMatcher;
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "cwiczenie", CWICZENIA);
uriMatcher.addURI(PROVIDER_NAME, "cwiczenia/#", CWICZENIE_ID);
}
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + TABLE_CWICZENIA + " (" +
KEY_ID + " integer PRIMARY KEY autoincrement," +
KEY_NAME + " TEXT," +
KEY_KIND + " TEXT," +
KEY_URL + " TEXT," +
KEY_SCORE + " TEXT," +
KEY_SERIES + " integer" +
");";
/*
#Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
mDb = dbHelper.getWritableDatabase();
return (mDb == null)? false:true;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return null;
}
#Nullable
#Override
public String getType(Uri uri) {
return null;
}
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
db.execSQL(DATABASE_CREATE);
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Pompki','Klatka piersiowa','https://www.youtube.com/watch?v=bwnidT3CB_Q',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Pompki na poręczach','Triceps','https://www.youtube.com/watch?v=Cufsu3IHhCo',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Odwrotne wiosłowanie','Plecy','https://www.youtube.com/watch?v=8qCn76yKhro',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Spięcia brzucha leżąc','Górna część mięśni brzucha','https://www.youtube.com/watch?v=VVcm4LdmIwM',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Unoszenie kolan','Dolna część mięśni brzucha','https://www.youtube.com/watch?v=Htx9Z8ZkiCg',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Skręty tułowia','Mięśnie skośne brzucha','https://www.youtube.com/watch?v=i7smKA3mgBU',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Przysiady','Uda','https://www.youtube.com/watch?v=NEduXlZ8zSk&t',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Wspięcia na palce','Mięśnie łydek','https://www.youtube.com/watch?v=Wri0VppFWCY',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Podciąganie na drążku','Mięśnie łydek','https://www.youtube.com/watch?v=7hM1iriAxx8',0,3)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CWICZENIA);
onCreate(db);
}
}
public OpenHelper1(Context ctx) {
this.mCtx = ctx;
}
public OpenHelper1 open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public OpenHelper1 read() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getReadableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createCwiczenie(String name,
String kind,
String url,
int score,
int series) {
mDbHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_KIND, kind);
initialValues.put(KEY_URL, url);
initialValues.put(KEY_SCORE, score);
initialValues.put(KEY_SERIES, series);
return mDb.insert(TABLE_CWICZENIA, null, initialValues);
}
public void deleteCwiczenie(String name) {
mDb.execSQL("DELETE FROM " + TABLE_CWICZENIA + " WHERE " + KEY_NAME + "=\"" + name + "\";" );
}
public void updateScore1(Uri uri,String name, int wynik) {
String str = "UPDATE "+TABLE_CWICZENIA+" SET "+KEY_SCORE+" = "+wynik+" WHERE "+KEY_NAME+" = '"+name+"'";
mDb.execSQL(str);
}
public void updateScore(String name, int wynik) {
String str = "UPDATE "+TABLE_CWICZENIA+" SET "+KEY_SCORE+" = "+wynik+" WHERE "+KEY_NAME+" = '"+name+"'";
mDb.execSQL(str);
}
public boolean deleteAllCwiczenia() {
int doneDelete = 0;
doneDelete = mDb.delete(TABLE_CWICZENIA, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public Cursor fetchCwiczeniaByName(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(TABLE_CWICZENIA, new String[] {KEY_ID,
KEY_NAME, KEY_KIND, KEY_URL, KEY_SCORE, KEY_SERIES},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, TABLE_CWICZENIA, new String[] {KEY_ID,
KEY_NAME, KEY_KIND, KEY_URL, KEY_SCORE, KEY_SERIES},
KEY_NAME + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllcwiczenia() {
Cursor mCursor = mDb.query(TABLE_CWICZENIA, new String[] {KEY_ID,
KEY_NAME, KEY_KIND, KEY_URL, KEY_SCORE, KEY_SERIES},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchOneCwiczenie(String name) {
String query = "SELECT * FROM " + TABLE_CWICZENIA + " WHERE name='"+name+"'";
Cursor c = mDb.rawQuery(query,null);
if(c != null) {
c.moveToFirst();
}
return c;
}
public Cursor fetchOneCwiczenie1(Uri uri,String name) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(TABLE_CWICZENIA);
String query = "SELECT * FROM " + TABLE_CWICZENIA + " WHERE name='"+name+"'";
Cursor c = mDb.rawQuery(query,null);
if (c != null) {
// c.setNotificationUri(getContext().getContentResolver(), ContactsContract.AUTHORITY_URI);
}
return c;
}
public void insertSomeCwiczenia() {
createCwiczenie("Pompki","Klatka piersiowa","https://www.youtube.com/watch?v=bwnidT3CB_Q",20,3);
createCwiczenie("Pompki na poręczach","Triceps","https://www.youtube.com/watch?v=Cufsu3IHhCo",0,3);
createCwiczenie("Odwrotne wiosłowanie","Plecy","https://www.youtube.com/watch?v=8qCn76yKhro",0,3);
createCwiczenie("Spięcia brzucha leżąc","Górna część mięśni brzucha","https://www.youtube.com/watch?v=VVcm4LdmIwM",0,3);
createCwiczenie("Unoszenie kolan","Dolna część mięśni brzucha","https://www.youtube.com/watch?v=Htx9Z8ZkiCg",0,3);
createCwiczenie("Skręty tułowia","Mięśnie skośne brzucha","https://www.youtube.com/watch?v=i7smKA3mgBU",0,3);
createCwiczenie("Przysiady","Uda","https://www.youtube.com/watch?v=NEduXlZ8zSk&t",0,3);
createCwiczenie("Wspięcia na palce","Mięśnie łydek","https://www.youtube.com/watch?v=Wri0VppFWCY",0,3);
createCwiczenie("Podciąganie na drążku","Mięśnie łydek","https://www.youtube.com/watch?v=7hM1iriAxx8",0,3);
}
}
public class TestActivity extends AppCompatActivity {
TextView textView;
EditText editText;
Button button,button1;
OpenHelper1 mDb;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.test_layout);
textView = (TextView) findViewById(R.id.polecenie);
editText = (EditText) findViewById(R.id.wartosc);
button = (Button) findViewById(R.id.treningactivity);
button1 = (Button) findViewById(R.id.zapisz);
//button2 = (Button) findViewById(R.id.button);
mDb = new OpenHelper1(this);
Intent i = getIntent();
// getting attached intent data
final String product = i.getStringExtra("cwiczenie ");
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int wynik = Integer.parseInt(editText.getText().toString());
mDb.open();
mDb.updateScore(product,wynik);
mDb.close();
}
});
/*
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDb.open();
Cursor t = mDb.fetchOneCwiczenie(product);
int c = t.getInt(t.getColumnIndex("score"));
String k = Integer.toString(c);
textView1.setText(k);
mDb.close();
}
});
*/
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext().getApplicationContext(), DzienPierwszy.class);
i.putExtra("cwiczenie ", product);
startActivity(i);
}
});
}
}
There are more than couple of things that you need to do -
In your content provider, you need to attach a notification Uri before the Cursor is being returned to client (in this case your Activity). The code would look something like this (Here the Authority URI need to be changed as per your provider) -
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(),ContactsContract.AUTHORITY_URI);
}
return c;
Every time there is a update in data, the following line needs to be called -
getContext().getContentResolver().notifyChange(ContactsContract.AUTHORITY_URI, null,
syncToNetwork);
Basically what point 1 & 2 does is that it notifies the underlying data layer that there is currently a client with an active cursor and needs to be notified if there is a change in the underlying data. If you are using any of the inbuilt data providers in Android like ContactsProvider/SmsProvider to read contacts/SMS data, point 1 &2 would have been taken care.
ContactsProvider
And on your activity code you need to do something like
cursor.registerContentObserver(mChangeObserver). If you instead use a Cursor adapter which wraps around your cursor, then this would have been taken care. Have a look at the Cursor Adapter source code -
CursorAdapter Sample

Display Data from SQL in custom ListView via SimpleCursorAdapter

i created a SQL Database and was able to safe data from three EditText Views and display it in a single TextView.
Then i thought it would be way better to display the data in a custom ListView, so i followed the developer guide and tried to display the data by a simpleCursorAdapter. But it did not work...i do not get any errors or anything, the data is just not shown...I guess there must be some missing connection between the Cursor, the Adapter or the DB...
i know that this kind of question is asked quite frequently, but i am unable to find my mistake, any help would be greatly appreciated:
MyDBHandlerFaecher.java:
public class MyDBHandlerFaecher extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "faecher.db";
public static final String TABLE_FAECHER = "Faechertable";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "_faechername";
public static final String COLUMN_RAUM = "_faecherraum";
public static final String COLUMN_COLOR = "_faecherfarbe";
public MyDBHandlerFaecher(FaecherActivity context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
//Create the table
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_FAECHER + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_RAUM + " TEXT, " +
COLUMN_COLOR + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAECHER);
onCreate(db);
}
//Add a new row to the DB
public void addFach(Faecher fach){
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, fach.get_faechername());
values.put(COLUMN_RAUM, fach.get_faecherraum());
values.put(COLUMN_COLOR, fach.get_faecherfarbe());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_FAECHER, null, values);
db.close();
}
//Delete row from DB
public void deleteFach(String name){
SQLiteDatabase db = getWritableDatabase();
//Delete the line in which the COLUMN_NAME is equal to the input
db.execSQL("DELETE FROM " + TABLE_FAECHER + " WHERE " + COLUMN_NAME + "=" + "\"" + name + "\"" + ";");
}
FaecherActivity.java
public class FaecherActivity extends AppCompatActivity{
EditText et_facheintrag;
EditText et_raumeintrag;
EditText et_farbeintrag;
ListView lv_faecher;
MyDBHandlerFaecher dbHandlerFaecher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faecher);
et_facheintrag = (EditText) findViewById(R.id.et_facheintrag);
et_raumeintrag = (EditText) findViewById(R.id.et_raumeintrag);
et_farbeintrag = (EditText) findViewById(R.id.et_farbeintrag);
lv_faecher = (ListView) findViewById(R.id.lv_faecher);
dbHandlerFaecher = new MyDBHandlerFaecher(this, null, null, 1);
printDatabase();
}
//Add fach to database
public void addButtonClicked(View view){
Faecher fach = new Faecher(et_facheintrag.getText().toString(), et_raumeintrag.getText().toString(), et_farbeintrag.getText().toString());
dbHandlerFaecher.addFach(fach);
printDatabase();
}
//delete fach from database
public void deleteButtonClicked(View view){
String inputText = et_facheintrag.getText().toString();
dbHandlerFaecher.deleteFach(inputText);
printDatabase();
}
public void printDatabase(){
String[] fromColumns = new String[]{"_faechername", "_faecherraum", "_faecherfarbe"};
int[] toViews = new int[]{R.id.facheintrag, R.id.raumeintrag, R.id.farbeintrag};
Cursor cursor;
cursor = getContentResolver().query(Uri.parse(MyDBHandlerFaecher.TABLE_FAECHER),null, null, null, null);
SimpleCursorAdapter fachadapter = new SimpleCursorAdapter(this, R.layout.faecher_row, cursor, fromColumns,toViews, 0);
lv_faecher.setAdapter(fachadapter);
}
}
i found code that works for me: i found out that the cursor in my DBHandler class was not empty, but it was empty in my FaecherActivity...so i created a custom SimpleCursorAdapter, and modified my code this way:
FaecherActivity:
public class FaecherActivity extends AppCompatActivity{
EditText et_facheintrag;
EditText et_raumeintrag;
EditText et_farbeintrag;
ListView lv_faecher;
MyDBHandlerFaecher dbHandlerFaecher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faecher);
et_facheintrag = (EditText) findViewById(R.id.et_facheintrag);
et_raumeintrag = (EditText) findViewById(R.id.et_raumeintrag);
et_farbeintrag = (EditText) findViewById(R.id.et_farbeintrag);
lv_faecher = (ListView) findViewById(R.id.lv_faecher);
dbHandlerFaecher = new MyDBHandlerFaecher(this, null, null, 1);
printDatabase();
}
//Add fach to database
public void addButtonClicked(View view){
Faecher fach = new Faecher(et_facheintrag.getText().toString(), et_raumeintrag.getText().toString(),
et_farbeintrag.getText().toString());
dbHandlerFaecher.addFach(fach);
printDatabase();
}
public void deleteButtonClicked(View view){
String inputText = et_facheintrag.getText().toString();
dbHandlerFaecher.deleteFach(inputText);
printDatabase();
}
public void printDatabase(){
String[] fromColumns = dbHandlerFaecher.databaseToStringArray();
int[] toViews = new int[]{R.id.facheintrag, R.id.raumeintrag, R.id.farbeintrag};
Cursor cursor;
cursor = dbHandlerFaecher.getWritableDatabase().rawQuery(" SELECT * FROM " + MyDBHandlerFaecher.TABLE_FAECHER + " WHERE 1 ", null);
//check if cursor is empty
if (cursor != null && cursor.getCount()>0) {
Log.d("Event", "Records do exist2");
}
else {
Log.d("Event", "Records do not exist2");
}
SimpleCursorAdapter fachadapter = new FaecherRowAdapter(this, R.layout.faecher_row, cursor, fromColumns,toViews, 0);
lv_faecher.setAdapter(fachadapter);
MyDBHandlerFaecher:
public class MyDBHandlerFaecher extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "faecher.db";
public static final String TABLE_FAECHER = "Faechertable";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "_faechername";
public static final String COLUMN_RAUM = "_faecherraum";
public static final String COLUMN_COLOR = "_faecherfarbe";
public MyDBHandlerFaecher(FaecherActivity context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
//Create the table
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_FAECHER + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_RAUM + " TEXT, " +
COLUMN_COLOR + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAECHER);
onCreate(db);
}
//Add a new row to the DB
public void addFach(Faecher fach){
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, fach.get_faechername());
values.put(COLUMN_RAUM, fach.get_faecherraum());
values.put(COLUMN_COLOR, fach.get_faecherfarbe());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_FAECHER, null, values);
db.close();
}
//Delete row from DB
public void deleteFach(String name){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_FAECHER + " WHERE " + COLUMN_NAME + "=" + "\"" + name + "\"" + ";");
}
public String[] databaseToStringArray() {
String[] fromColumns = new String[]{COLUMN_NAME, COLUMN_RAUM, COLUMN_COLOR};
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery(" SELECT * FROM " + TABLE_FAECHER + " WHERE 1 ", null);
//check if cursor is empty or not
if (cursor != null && cursor.getCount()>0) {
Log.d("Event", "Records do exist");
}
else {
Log.d("Event", "Records do not exist");
}
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
cursor.moveToNext();
}
db.close();
return fromColumns;
}
}
FaecherRowAdapter:
public class FaecherRowAdapter extends SimpleCursorAdapter {
private int layout;
private Context context;
public FaecherRowAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
this.layout = layout;
this.context = context;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
Cursor c = getCursor();
final LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.faecher_row, parent, false);
bindView(v, context, c);
return v;
}
#Override
public void bindView(View v, Context context, Cursor c) {
int fachNameColumn = c.getColumnIndex(MyDBHandlerFaecher.COLUMN_NAME);
int fachRaumColumn = c.getColumnIndex(MyDBHandlerFaecher.COLUMN_RAUM);
int fachFarbeColumn = c.getColumnIndex(MyDBHandlerFaecher.COLUMN_COLOR);
String fachName = c.getString(fachNameColumn);
String fachRaum = c.getString(fachRaumColumn);
String fachFarbe = c.getString(fachFarbeColumn);
//set the name of the entry
TextView facheintrag = (TextView) v.findViewById(R.id.facheintrag);
if (facheintrag != null){
facheintrag.setText(fachName);
}
TextView raumeintrag = (TextView) v.findViewById(R.id.raumeintrag);
if (raumeintrag != null){
raumeintrag.setText(fachRaum);
}
TextView farbeintrag = (TextView) v.findViewById(R.id.farbeintrag);
if (farbeintrag != null){
farbeintrag.setText(fachFarbe);
}
}
}

How to update a specific row in SQLite?

Im trying to update a users current credits, but I don't want to replace the value, just add on a selected amount from the spinner and add it on to the the users current credits? Thank you.
My database code?
package com.example.parkangel;
public class UDbHelper extends SQLiteOpenHelper
{
public static final String KEY_ROWID = "_id";
public static final String KEY_PFNAME = "payeeFname";
public static final String KEY_PSNAME = "payeeSname";
public static final String KEY_CARD = "card";
public static final String KEY_CREDITS = "credits";
private static final String DATABASE_NAME = "UserData.db";
private static final String DATABASE_TABLE = "UserTable";
private static final int DATABASE_VERSION = 1;
//private UDbHelper dbHelper;
//private final Context ourContext;
private static UDbHelper instance;
private SQLiteDatabase ourDatabase;
public UDbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static UDbHelper getInstance(Context context)
{
if (instance == null)
{
instance = new UDbHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_PFNAME + " TEXT NOT NULL, " + KEY_PSNAME + "
TEXT NOT NULL, " +
KEY_CARD + " INTEGER NOT NULL, " + KEY_CREDITS + "
INTEGER NOT NULL);");
ContentValues values = new ContentValues();
values.put(KEY_PFNAME, "Tutku");
values.put(KEY_PSNAME, "Erbil");
values.put(KEY_CARD, "12345677");
values.put(KEY_CREDITS, 5);
db.insert(DATABASE_TABLE, null, values);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public synchronized UDbHelper open() throws SQLException
{
System.out.println ("running open");
if(ourDatabase == null || !ourDatabase.isOpen())
ourDatabase = getWritableDatabase();
return this;
}
public String getData()
{
// TODO Auto-generated method stub
String[] columns = new String[] {KEY_ROWID, KEY_PFNAME, KEY_PSNAME,
KEY_CARD, KEY_CREDITS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null,
null, null, null);
String result = " ";
int iRow = c.getColumnIndexOrThrow(KEY_ROWID);
int iPFname = c.getColumnIndexOrThrow(KEY_PFNAME);
int iPSname = c.getColumnIndexOrThrow(KEY_PSNAME);
int iCard = c.getColumnIndexOrThrow(KEY_CARD);
int iCredits = c.getColumnIndexOrThrow(KEY_CREDITS);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " +
c.getString(iPFname) + " " +
c.getString(iPSname) + " " + c.getString(iCard) + " " +
c.getString(iCredits) + "\n";
}
return result;
}
public void upDateUser(String money) {
// TODO Auto-generated method stub
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_CREDITS, money);
ourDatabase.update(DATABASE_TABLE, cvUpdate, null, null);
}
}
Class that needs to perform the actoin:
package com.example.parkangel;
public class Balance extends Activity implements OnClickListener{
Button add;
TextView display;
Spinner spinner3;
Integer[] money = new Integer[] {1, 2, 5, 10};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.balance_layout);
TextView tv = (TextView) findViewById(R.id.firstn);
UDbHelper db = new UDbHelper(this);
db.open();
String data = db.getData();
//db.addUser();
db.close();
tv.setText(data);
ArrayAdapter<Integer> adapter3 = new ArrayAdapter<Integer>(Balance.this,
android.R.layout.simple_spinner_item, money);
spinner3 = (Spinner) findViewById (R.id.moneytoadd);
spinner3.setAdapter(adapter3);
add = (Button) findViewById(R.id.topup);
add.setOnClickListener(this);
//add = (Button) findViewById(R.id.topup);
}
public void onClick(View arg0)
{
switch (arg0.getId()){
case R.id.topup:
boolean work = true;
try{
String money = spinner3.getContext().toString();
UDbHelper ud = new UDbHelper(this);
ud.open();
ud.upDateUser(money);
ud.close();
}catch (Exception e){
work = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Unable To TopUp!");
TextView dg = new TextView(this);
dg.setText(error);
d.setContentView(dg);
d.show();
}finally{
if(work){
Dialog d = new Dialog(this);
d.setTitle("You Have ToppedUp!");
TextView dg = new TextView(this);
dg.setText("TopUp Successful");
d.setContentView(dg);
d.show();
}
}
break;
}
}
public void updateActivity(View view){
Intent book = new Intent(Balance.this, BookTicket.class);
startActivity(book);
}
public void addBalance(View view){
Intent addB = new Intent(Balance.this, Balance.class);
startActivity(addB);
}
public void doUpdate(View view){
Intent upd = new Intent(Balance.this, UpdateTicket.class);
startActivity(upd);
}
}
First of all you should have an ID that will let you find the user you are interested in. That do a select to get the current value that is stored in database. Parse the value to integer and add "new" money. And finally, update the value in database.
public void upDateUser(String ID, String money) {
String query = "Select money from TABLE_NAME where ID = " + ID;
SQLiteDatabase db = this.getWriteableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
int oldMoney = 0;
if (cursor.moveToFirst()) {
oldMoney = Integer.parseInt(cursor.getString(0)); //Cause we get only from money column
}
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_CREDITS, oldMoney + money);
String filter = "UID" + "=" + ID;
db.update(DATABASE_TABLE, cvUpdate, filter, null);
}
Of course you have to check if cursor returns exactly one row and do some other checks.

Access SQLiteOpenHelper onCreate Method from wrapping class

Right now i am calling an insertSomeContacts() function in the onCreate method of the MainActivity which obviously adds the given contacts every time the app is restarted (including screen roation)...since my SQLiteOpenHelper Sub-Class is part of my ContactsDBAdapter Class (which carries the insertSomeContacts() method) - how do i get this function to execute in the SQLiteOpenHelper onCreate so that it only executes once at creation of the database?
Really having problems understanding the scope of this and passing that scope around properly.
MainActivity.java:
public class MainActivity extends Activity {
Intent intent;
private ContactsDBAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new ContactsDBAdapter(this);
dbHelper.open();
//dbHelper.deleteAll();
//dbHelper.insertSomeContacts();
displayListView();
}
private void displayListView(){
Cursor cursor = dbHelper.getAll();
String[] fromColumns = new String[]{
ContactsDBAdapter.COLUMN_TYPE,
ContactsDBAdapter.COLUMN_CLTYP,
ContactsDBAdapter.COLUMN_NAME,
ContactsDBAdapter.COLUMN_VNAME
};
int[] toViews = new int[]{
R.id.contactType,
R.id.contactCltype,
R.id.contactName,
R.id.contactVname
};
dataAdapter = new SimpleCursorAdapter(this, R.layout.contact_entry, cursor, fromColumns, toViews, 0);
ListView listview = (ListView) findViewById(R.id.list);
listview.setAdapter(dataAdapter);
}
ContactsDBAdapter.java:
public class ContactsDBAdapter{
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_CLTYP = "cltyp";
public static final String COLUMN_MDT = "mdt";
public static final String COLUMN_OBJ = "obj";
public static final String COLUMN_VTR = "vtr";
public static final String COLUMN_FKZ = "fkz";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_VNAME = "vname";
public static final String COLUMN_TEL = "tel";
public static final String COLUMN_FAX = "fax";
public static final String COLUMN_MOBIL = "mobil";
public static final String COLUMN_EMAIL = "email";
private static final String TAG = "ContactsDBAdapter";
private DBTools mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "hvkontakte.db";
private static final String DATABASE = "hvkontakte";
private static final String TABLE_NAME = DATABASE;
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE =
"CREATE TABLE " + TABLE_NAME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_TYPE + ", " + COLUMN_CLTYP + ", " + COLUMN_MDT + ", " + COLUMN_OBJ + ", "
+ COLUMN_VTR + ", " + COLUMN_FKZ + ", " + COLUMN_NAME + ", " + COLUMN_VNAME + ", "
+ COLUMN_TEL + ", " + COLUMN_FAX + ", " + COLUMN_MOBIL + ", " + COLUMN_EMAIL + ")";
private static class DBTools extends SQLiteOpenHelper{
public DBTools(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
Log.w(TAG, DATABASE_CREATE);
database.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
database.execSQL("DROP TABLE IF EXISTS" + DATABASE);
onCreate(database);
}
}
public ContactsDBAdapter(Context ctx){
this.mCtx = ctx;
}
public ContactsDBAdapter open() throws SQLException{
mDbHelper = new DBTools(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close(){
if(mDbHelper != null){
mDbHelper.close();
}
}
public long createContact(String type, String cltyp, String mdt, String obj, String vtr,
String fkz, String name, String vname, String tel, String fax,
String mobil, String email) {
ContentValues initialValues = new ContentValues();
initialValues.put(COLUMN_TYPE, type);
initialValues.put(COLUMN_CLTYP, cltyp);
initialValues.put(COLUMN_MDT, mdt);
initialValues.put(COLUMN_OBJ, obj);
initialValues.put(COLUMN_VTR, vtr);
initialValues.put(COLUMN_FKZ, fkz);
initialValues.put(COLUMN_NAME, name);
initialValues.put(COLUMN_VNAME, vname);
initialValues.put(COLUMN_TEL, tel);
initialValues.put(COLUMN_FAX, fax);
initialValues.put(COLUMN_MOBIL, mobil);
initialValues.put(COLUMN_EMAIL, email);
return mDb.insert(TABLE_NAME, null, initialValues);
}
public boolean deleteAll() {
int doneDelete = 0;
doneDelete = mDb.delete(TABLE_NAME, null , null);
return doneDelete > 0;
}
public Cursor getAll() {
Cursor mCursor = mDb.query(TABLE_NAME, new String[] {COLUMN_ID,
COLUMN_TYPE, COLUMN_CLTYP, COLUMN_NAME, COLUMN_VNAME},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public void insertSomeContacts(){
createContact("vtr","Tenant","1","82","1","2","Bennett","Tony","0911-123456","0911-123457","01577-12345678","info#email.com");
createContact("vtr","Owner","1","82","","","Smith","Brad","0911-1234567","0911-1234567","01577-84368365","info#email.com");
//createContact("","","","","","","","","","","","");
//createContact("","","","","","","","","","","","");
//createContact("","","","","","","","","","","","");
//createContact("","","","","","","","","","","","");
}
}
work with SharedPreferences. Set a init boolean. if init is false insert the contacts -> set the init to true. after restarting do noting when init is true.
But this is maybe not the best solution for your usecase...

Categories