How to save firebase notification insert data sqlite database android - java

title, post_id, link How to take these three to DbHandler notification. 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 void notification(Recipe p) { Data should be saved in all of these
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();
}
}
}
}
save firebase notification insert data sqlite database

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.

Generating a file to store a receipt in android studios

Hello I am new to android studios. I am working on an airline reservation project. One of the requirements of the project is to generate a receipt that is stored on an external file every time a customer makes a payment. I have tried looking around trying to figure out how one might accomplish this with no success. In the app I am using SQLite as a database where every user is assigned a balance once they create an account.
Here is my DBHelper class:
package com.example.shashank.fffffffffffffffffffffffffff;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "Login.db";
public static final String FLIGHTS = "FLIGHTS";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_DESTINATION = "DESTINATION";
public static final String COLUMN_PRICE = "PRICE";
public static final String COLUMN_DEPARTURE_TIME = "DEPARTURE_TIME";
public static final String COLUMN_ARRIVAL_TIME = "ARRIVAL_TIME";
public static final String COLUMN_DURATION = "DURATION";
public static final String COLUMN_AVAILABLE_SEATS = "AVAILABLE_SEATS";
public static final String USERS = "users";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String EMAIL = "email";
public static final String BALANCE = "balance";
public static final String BOOKING = "booking";
public DBHelper(Context context) {
super(context, "Login.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase MyDB) {
String createTable1 = ("create Table " + USERS + "(" + USERNAME + " TEXT primary key, " + PASSWORD + " TEXT, " + EMAIL + " TEXT UNIQUE, " + BALANCE + " REAL, " + BOOKING + " INTEGER)");
MyDB.execSQL(createTable1);
MyDB.execSQL("CREATE TABLE " + FLIGHTS + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_DESTINATION + " TEXT, " + COLUMN_PRICE + " REAL, " + COLUMN_DEPARTURE_TIME + " TEXT, " + COLUMN_ARRIVAL_TIME + " TEXT, " + COLUMN_DURATION + " TEXT, " + COLUMN_AVAILABLE_SEATS + " INTEGER)");
ContentValues insertValues = new ContentValues();
insertValues.put(COLUMN_DESTINATION, "Cape Town");
insertValues.put(COLUMN_PRICE, 2000);
insertValues.put(COLUMN_DEPARTURE_TIME, "1200");
insertValues.put(COLUMN_ARRIVAL_TIME, "1400");
insertValues.put(COLUMN_DURATION, "2");
insertValues.put(COLUMN_AVAILABLE_SEATS, 10);
MyDB.insert(FLIGHTS, null, insertValues);
ContentValues insertValues2 = new ContentValues();
insertValues2.put(COLUMN_DESTINATION, "Johannesburg");
insertValues2.put(COLUMN_PRICE, 1000);
insertValues2.put(COLUMN_DEPARTURE_TIME, "1400");
insertValues2.put(COLUMN_ARRIVAL_TIME, "1600");
insertValues2.put(COLUMN_DURATION, "2");
insertValues2.put(COLUMN_AVAILABLE_SEATS, 22);
MyDB.insert(FLIGHTS, null, insertValues2);
ContentValues insertValues3 = new ContentValues();
insertValues3.put(COLUMN_DESTINATION, "Cape Town");
insertValues3.put(COLUMN_PRICE, 500);
insertValues3.put(COLUMN_DEPARTURE_TIME, "1200");
insertValues3.put(COLUMN_ARRIVAL_TIME, "1400");
insertValues3.put(COLUMN_DURATION, "2");
insertValues3.put(COLUMN_AVAILABLE_SEATS, 0);
MyDB.insert(FLIGHTS, null, insertValues3);
}
#Override
public void onUpgrade(SQLiteDatabase MyDB, int i, int i1) {
MyDB.execSQL("drop Table if exists " + USERS);
MyDB.execSQL("drop Table if exists " + FLIGHTS);
onCreate(MyDB);
}
public Boolean insertData(String username, String password, String email, Double balance){
SQLiteDatabase MyDB = this.getWritableDatabase();
ContentValues contentValues= new ContentValues();
contentValues.put(USERNAME, username);
contentValues.put(PASSWORD, password);
contentValues.put(EMAIL, email);
contentValues.put(BALANCE, balance);
long result = MyDB.insert(USERS, null, contentValues);
if(result==-1) return false;
else
return true;
}
public Boolean checkusername(String username) {
SQLiteDatabase MyDB = this.getWritableDatabase();
Cursor cursor = MyDB.rawQuery("Select * from " + USERS + " where " + USERNAME + " = ?", new String[]{username});
if (cursor.getCount() > 0)
return true;
else
return false;
}
public Boolean checkusernamepassword(String username, String password){
SQLiteDatabase MyDB = this.getWritableDatabase();
Cursor cursor = MyDB.rawQuery("Select * from " + USERS + " where " + USERNAME + " = ? and " + PASSWORD + " = ?", new String[] {username,password});
if(cursor.getCount()>0)
return true;
else
return false;
}
public List<FlightsModel> getEveryone(){
List<FlightsModel> returnList = new ArrayList<>();
String queryString = "SELECT * FROM " + FLIGHTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(queryString, null);
if(cursor.moveToFirst()){
do {
int id = cursor.getInt(0);
String destination = cursor.getString(1);
double price = cursor.getDouble(2);
String departure = cursor.getString(3);
String arrival = cursor.getString(4);
String duration = cursor.getString(5);
int space = cursor.getInt(6);
FlightsModel newFlight = new FlightsModel(id, destination, price, departure, arrival, duration, space);
returnList.add(newFlight);
}while (cursor.moveToNext());
}
else{
}
cursor.close();
db.close();
return returnList;
}
#SuppressLint("Range") // suppress Bug/issue with getColumnIndex
public FlightsModel getFlightById(int id) {
FlightsModel rv;
SQLiteDatabase db = this.getWritableDatabase();
// Uses the query convenience method rather than raw query
Cursor csr = db.query(FLIGHTS,null,COLUMN_ID+"=?",new String[]{String.valueOf(id)},null,null,null);
if (csr.moveToFirst()) {
rv = new FlightsModel(
csr.getInt(csr.getColumnIndex(COLUMN_ID)),
csr.getString(csr.getColumnIndex(COLUMN_DESTINATION)),
csr.getDouble(csr.getColumnIndex(COLUMN_PRICE)),
csr.getString(csr.getColumnIndex(COLUMN_DEPARTURE_TIME)),
csr.getString(csr.getColumnIndex(COLUMN_ARRIVAL_TIME)),
csr.getString(csr.getColumnIndex(COLUMN_DURATION)),
csr.getInt(csr.getColumnIndex(COLUMN_AVAILABLE_SEATS))
);
} else {
rv = new FlightsModel();
}
csr.close();
// No need to close the database (inefficient to keep opening and closing db)
return rv;
}
#SuppressLint("Range")
public UsersModel getPasswordByName(String name){
UsersModel rv;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cr = db.query(USERS, null, USERNAME+"=?", new String[]{name}, null, null, null);
if (cr.moveToFirst()) {
rv = new UsersModel(
cr.getString(cr.getColumnIndex(USERNAME)),
cr.getString(cr.getColumnIndex(PASSWORD)),
cr.getString(cr.getColumnIndex(EMAIL)),
cr.getDouble(cr.getColumnIndex(BALANCE)),
cr.getInt(cr.getColumnIndex(BOOKING))
);
} else rv = new UsersModel();
cr.close();
return rv;
}
public int setBookingByUserName(int bookingAmount, String userName) {
ContentValues cv = new ContentValues();
cv.put(BOOKING,bookingAmount);
return this.getWritableDatabase().update(USERS,cv,USERNAME+"=?",new String[]{userName});
}
public double makingPayment(double balance, String userName){
ContentValues cv = new ContentValues();
cv.put(BALANCE,balance);
return this.getWritableDatabase().update(USERS,cv,USERNAME+"=?",new String[]{userName});
}
public int setAvailableSeatsAfterPayment(int seats, int flightID){
ContentValues cv = new ContentValues();
cv.put(COLUMN_AVAILABLE_SEATS,seats);
return this.getWritableDatabase().update(FLIGHTS,cv,COLUMN_ID+"=?",new String[]{String.valueOf(flightID)});
}
public int cancelBooking(int bookingAmount, String userName){
ContentValues cv = new ContentValues();
cv.put(BOOKING,bookingAmount);
return this.getWritableDatabase().update(USERS,cv,USERNAME+"=?",new String[]{String.valueOf(userName)});
}
}
The making payment method is used to update the database with a new balance when a customer books for a flight.
Here is the booking activity:
package com.example.shashank.fffffffffffffffffffffffffff;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class BookingActivity extends AppCompatActivity {
TextView textView;
TextView departure, arrival, duration, price, seats;
DBHelper dbHelper; //<<<<< ADDED
Button book, accountBtn;
FlightsModel flightsModel; //<<<<< ADDED
UsersModel userModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
dbHelper = new DBHelper(this); //<<<<< ADDED
textView = findViewById(R.id.textView);
departure = findViewById(R.id.departure);
arrival = findViewById(R.id.arrival);
duration = findViewById(R.id.duration);
price = findViewById(R.id.price);
seats = findViewById(R.id.seats);
book = findViewById(R.id.button2);
accountBtn = findViewById(R.id.accountBtn);
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
Intent nameIntent = getIntent();
String name = nameIntent.getStringExtra("userName");
flightsModel = dbHelper.getFlightById(intValue + 1);
intValue = intValue + 1;
textView.setText(flightsModel.getDestination());
departure.setText(flightsModel.getDeparture_time());
arrival.setText(flightsModel.getArrival_time());
duration.setText(flightsModel.getDuration());
price.setText("R" + Double.toString(flightsModel.getPrice()));
seats.setText(Integer.toString(flightsModel.getAvailable_space()));
book.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int intValue, seats;
Intent mIntent = getIntent();
intValue = mIntent.getIntExtra("intVariableName", 0);
intValue = intValue + 1;
dbHelper = new DBHelper(BookingActivity.this);
flightsModel = dbHelper.getFlightById(intValue);
double price;
price = flightsModel.getPrice();
userModel = dbHelper.getPasswordByName(name);
double balance;
balance = userModel.getBalance();
String name = nameIntent.getStringExtra("userName");
seats = flightsModel.getAvailable_space();
if(seats == 0){
Toast.makeText(BookingActivity.this, "Booking unsuccessful, no available seats", Toast.LENGTH_SHORT).show();
}else{
if(price <= balance){
dbHelper.setBookingByUserName(intValue, name);
Toast.makeText(BookingActivity.this, "Payment successful, booking has been made", Toast.LENGTH_SHORT).show();
double newBalance;
newBalance = balance - price;
dbHelper.makingPayment(newBalance, name);
seats = seats - 1;
dbHelper.setAvailableSeatsAfterPayment(seats, intValue);
}else{
Toast.makeText(BookingActivity.this, "Payment unsuccessful, not enough funds", Toast.LENGTH_SHORT).show();
}
}
}
});
accountBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BookingActivity.this, AccountActivity.class);
intent.putExtra("userName", name);
startActivity(intent);
}
});
}
}
So once a customer makes his booking a receipt file needs to be generated, say for instance with the flight details, time, date and the price of the flight. Any help will be appreciated thank you.
The following is an example that saves a file in the App's Files directory in a sub directory of receipts. The filename being composed of values e.g.
Fred-Cape Town-1200-1400
Stored at /data/user/0/the_package_name/files/receipts/Fred-Cape Town-1200-1400
The file itself, in the example containing :-
Fred
Cape Town
1200
1400
Some supportive methods added to DBHelper :-
public UsersModel getUsersModelByName(String userName) {
UsersModel rv = new UsersModel();
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(USERS,null,USERNAME+"=?", new String[]{userName},null,null,null);
if (csr.moveToFirst()) {
rv = new UsersModel(
csr.getString(csr.getColumnIndex(USERNAME)),
csr.getString(csr.getColumnIndex(PASSWORD)),
csr.getString(csr.getColumnIndex(EMAIL)),
csr.getDouble(csr.getColumnIndex(BALANCE)),
csr.getInt(csr.getColumnIndex(BOOKING))
);
}
csr.close();
return rv;
}
public boolean makeBooking(String userName, int bookingId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(BOOKING,bookingId);
return db.update(USERS,cv,USERNAME + "=?", new String[]{userName}) > 0;
}
Now the makeBookReceiptFile method, also placed in the DBHelper class:-
public String makeBookReceiptFile(String userName, Context context) {
String rcpts_directory = "receipts";
String rv = "";
SQLiteDatabase db = this.getWritableDatabase();
UsersModel currentUser = getUsersModelByName(userName);
FlightsModel currentFlightsModel = new FlightsModel();
if (currentUser.booking > 0) {
currentFlightsModel = getFlightById(currentUser.booking);
if (currentFlightsModel.id < 1) {
rv = "INVALID - unable to extract booking for id " + currentUser.booking;
}
} else {
rv = "INVALID - unable to extract user who's name is " + userName;
}
if (rv.length() > 0) return rv;
String rcpt_filename =
currentUser.username + "-" +
currentFlightsModel.destination + "-" +
currentFlightsModel.departure + "-" +
currentFlightsModel.arrival
;
File rcpt = new File(context.getFilesDir().getPath() + File.separatorChar + rcpts_directory + File.separatorChar + rcpt_filename);
rcpt.getParentFile().mkdirs();
try {
FileWriter fw = new FileWriter(rcpt);
fw.write(userName +
"\n" + currentFlightsModel.destination+
"\n" + currentFlightsModel.departure +
"\n" + currentFlightsModel.arrival
);
fw.flush();
fw.close();
rv = rcpt.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
rv = "IOERROR - " + e.getMessage();
}
return rv;
}
First it retrieves the UsersModel according to the UserName, the it retrieves the FlightsModel according to the booking id.
If either was not obtained then it returns a String starting with INVALID
It then obtains the Files directory via the Context.
Generates the path for the file.
Makes any missing directories.
Write data to the file, flushes and closes the file returning the path or if there was an io error the error message.
The above was tested using :-
db = new DBHelper(this);
db.insertData("Fred","password","fed#email",0.00);
UsersModel fred = db.getUsersModelByName("Fred");
db.makeBooking(fred.username,1);
Log.d("RESULTINFO",db.makeBookReceiptFile("Fred",this));
Resulting in (via Device Explorer) :-
If you have issues with the location of the file then you will have to read https://developer.android.com/training/data-storage/

Com.example path with errors

When I was releasing an apk on google play I had to use a different package name cause of "com.example". I tried this and I get crash after testing an application. Before that everything was ok. I can send a manifest.
There are my errors.
My classes
Details.java
public class Details extends AppCompatActivity {
NoteDatabase db;
Note note;
TextView mDetails;
TextView clientDetails;
TextView timeDetails;
TextView nameDetails;
TextView detailsDetails;
ImageView noteDetails;
private Bitmap getImageFromByte(byte[] zdjecie){
return BitmapFactory.decodeByteArray(zdjecie, 0, zdjecie.length);
}
#SuppressLint("WrongThread")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDetails = findViewById(R.id.detailsOfNote);
mDetails.setMovementMethod(new ScrollingMovementMethod());
clientDetails = findViewById(R.id.clientOfNote);
timeDetails = findViewById(R.id.timeofNote);
nameDetails = findViewById(R.id.nameOfNote);
detailsDetails = findViewById(R.id.detailsOfNote);
noteDetails = findViewById(R.id.noteImage);
Intent i = getIntent();
Long id = i.getLongExtra("ID", 0);
db = new NoteDatabase(this);
note = db.getNote(id);
getSupportActionBar().setTitle(note.getTitle());
mDetails.setText(note.getContent());
clientDetails.setText(note.getTitle());
timeDetails.setText(note.getTime());
nameDetails.setText(note.getName());
detailsDetails.setText(note.getDetails());
noteDetails.setImageBitmap(stringToImage(note.getImage()));
Toast.makeText(this, "Podgląd klienta", Toast.LENGTH_SHORT).show();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
db.deleteNote(note.getID());
Toast.makeText(getApplicationContext(), "Klient usunięty", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),klienci.class));
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.edit_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == R.id.editNote){
Toast.makeText(this, "Edytowanie notatki", Toast.LENGTH_SHORT).show();
Intent i = new Intent(this,Edit.class);
i.putExtra("ID",note.getID());
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
private void goToMain() {
Intent i = new Intent(this,klienci.class);
startActivity(i);
}
private Bitmap stringToImage(String imgString){
byte[] decodedString = Base64.decode(imgString,Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString,0,decodedString.length);
return decodedByte;
}
NoteDatabase.java
public class NoteDatabase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 42;
private static final String DATABASE_NAME = "notedbs";
private static final String DATABASE_TABLE = "notestables";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_CONTENT = "content";
private static final String KEY_DATE = "date";
private static final String KEY_TIME = "time";
private static final String KEY_PHONE = "phone";
private static final String KEY_CLIENT = "client";
private static final String KEY_DETAILS = "details";
private static final String KEY_IMAGE = "image";
NoteDatabase(Context context) {
super(context, DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE "+ DATABASE_TABLE + "("+ KEY_ID+" INT PRIMARY KEY,"+
KEY_TITLE + " TEXT,"+
KEY_CONTENT + " TEXT,"+
KEY_DATE + " TEXT,"+
KEY_TIME + " TEXT,"+
KEY_CLIENT + " TEXT,"+
KEY_DETAILS + " TEXT,"+
KEY_PHONE + " TEXT,"+
KEY_IMAGE + " TEXT"+")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(oldVersion >= newVersion)
return;
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public long addNote(Note note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues c = new ContentValues();
c.put(KEY_TITLE,note.getTitle());
c.put(KEY_CONTENT,note.getContent());
c.put(KEY_PHONE,note.getPhone());
c.put(KEY_CLIENT,note.getClient());
c.put(KEY_DETAILS,note.getDetails());
c.put(KEY_DATE,note.getDate());
c.put(KEY_TIME,note.getTime());
c.put(KEY_IMAGE,note.getImage());
long ID = db.insert(DATABASE_TABLE,null, c);
Log.d("Inserted", "ID -> " + ID);
return ID;
}
public Note getNote(long id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(DATABASE_TABLE,new String[] {KEY_ID,KEY_TITLE,KEY_CONTENT,KEY_PHONE,KEY_CLIENT,KEY_DETAILS,KEY_DATE,KEY_TIME,KEY_IMAGE}, KEY_ID+"=?",
new String[]{String.valueOf(id)}, null, null,null);
if (cursor != null)
cursor.moveToFirst();
return new Note
(cursor.getLong(0)
,cursor.getString(1)
,cursor.getString(2)
,cursor.getString(3)
,cursor.getString(4)
,cursor.getString(5)
,cursor.getString(6)
,cursor.getString(7)
,cursor.getString(8));
}
public List<Note> getNotes() {
SQLiteDatabase db = this.getReadableDatabase();
List<Note> allNotes = new ArrayList<>();
String query = "SELECT * FROM " + DATABASE_TABLE + " ORDER BY "+KEY_TITLE+" ASC";
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()){
do{
Note note = new Note();
note.setID(cursor.getLong(0));
note.setTitle(cursor.getString(1));
note.setDetails(cursor.getString(2));
note.setPhone(cursor.getString(3));
note.setClient(cursor.getString(4));
note.setContent(cursor.getString(5));
note.setDate(cursor.getString(6));
note.setTime(cursor.getString(7));
note.setImage(cursor.getString(8));
allNotes.add(note);
}while(cursor.moveToNext());
}
return allNotes;
}
public int editNote(Note note){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues c = new ContentValues();
Log.d("Edited", "Edited Title: -> "+ note.getTitle() + "\n ID -> "+note.getZdjecie());
c.put(KEY_TITLE,note.getTitle());
c.put(KEY_CONTENT,note.getContent());
c.put(KEY_PHONE,note.getPhone());
c.put(KEY_CLIENT,note.getClient());
c.put(KEY_DETAILS,note.getDetails());
c.put(KEY_DATE,note.getDate());
c.put(KEY_TIME,note.getTime());
c.put(KEY_IMAGE,note.getImage());
return db.update(DATABASE_TABLE,c,KEY_ID +"=?",new String[]{String.valueOf(note.getID())});
}
void deleteNote(long id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(DATABASE_TABLE, KEY_ID + "=?", new String[]{String.valueOf(id)});
db.close();
}
You are trying to get 0 index in the database. Every time you add a new Note its ID will be 0. So, change your database KEY_ID to AUTOINCREMENT.
String query = "CREATE TABLE " + DATABASE_TABLE + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
KEY_TITLE + " TEXT," +
KEY_CONTENT + " TEXT," +
KEY_DATE + " TEXT," +
KEY_TIME + " TEXT," +
KEY_PIES + " TEXT," +
KEY_RASAPSA + " TEXT," +
KEY_TEL + " TEXT," +
KEY_ZDJECIE + " TEXT" + ")";
db.execSQL(query);
Then check your cursor not null in
getNote()

How to Figure out the MAX and MIN of Groups that have been Added together

How do would you get the MAX value of a column that has been grouped and add together by _id.
So something like this:
I then want to display the MAX value of the four groups, as well as the MIN value of the four groups.
Something like this Scratch High = 702 / Scratch Low = 325
Is this possible with the built in Math functions of SQLite or would I need to write specific code to accomplish this? The actual number of groups will be more than 4, it will depend on how often the bowler actually bowls a series.
I haven't written any code for this as of yet, I am attempting to figure out if this is even possible before attempting to do so. Any suggestions would be welcome.
My attempt to integrate into my Project:
DatabaseHelper.java
public static final String DERIVEDCOL_MAXSCORE = "max_score";
public static final String DERIVEDCOl_MINSCORE = "min_score";
public Cursor getMaxMinScoresAllAndroid() {
SQLiteDatabase db = this.getWritableDatabase();
String tmptbl = "summed_scores";
String tmptblcol = "sum_score";
String crttmptbl = "CREATE TEMP TABLE IF NOT EXISTS " + tmptbl + "(" +
tmptblcol + " INTEGER" +
")";
String empttmptbl = "DELETE FROM " + tmptbl;
db.execSQL(crttmptbl);
db.execSQL(empttmptbl);
String[] columns = new String[]{"sum(score) AS " + tmptblcol};
Cursor csr = db.query(Game.TABLE_NAME,columns,null,null,Game.COLUMN_BOWLER_ID,null,null);
DatabaseUtils.dumpCursor(csr);
while (csr.moveToNext()) {
ContentValues cv = new ContentValues();
cv.put(tmptblcol,csr.getInt(csr.getColumnIndex(tmptblcol)));
db.insert(tmptbl,null,cv);
}
csr.close();
columns = new String[]{"max(" +
tmptblcol +
") AS " + DERIVEDCOL_MAXSCORE,
"min(" +
tmptblcol +
") AS " + DERIVEDCOl_MINSCORE};
return csr = db.query(tmptbl,columns,null,null,null,null,null);
}
public MaxMin getMaxAndminScoresAll() {
MaxMin rv = new MaxMin(0,0);
Cursor csr = getMaxMinScoresAllAndroid();
if (csr.moveToFirst()) {
rv.setMin(csr.getInt(csr.getColumnIndex(DERIVEDCOl_MINSCORE)));
rv.setMax(csr.getInt(csr.getColumnIndex(DERIVEDCOL_MAXSCORE)));
}
csr.close();
return rv;
}
BowlerProfileViewActivity.java
public class BowlerProfileViewActivity extends AppCompatActivity {
Bowler bowler;
private DatabaseHelper db;
private static final String PREFS_NAME = "prefs";
private static final String PREF_BLUE_THEME = "blue_theme";
private static final String PREF_GREEN_THEME = "green_theme";
private static final String PREF_ORANGE_THEME = "purple_theme";
private static final String PREF_RED_THEME = "red_theme";
private static final String PREF_YELLOW_THEME = "yellow_theme";
#Override
protected void onResume() {
super.onResume();
db = new DatabaseHelper(this);
//mAdapter.notifyDatasetChanged(db.getAllLeagues());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
//Use Chosen Theme
SharedPreferences preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
boolean useBlueTheme = preferences.getBoolean(PREF_BLUE_THEME, false);
if (useBlueTheme) {
setTheme(R.style.AppTheme_Blue_NoActionBar);
}
boolean useGreenTheme = preferences.getBoolean(PREF_GREEN_THEME, false);
if (useGreenTheme) {
setTheme(R.style.AppTheme_Green_NoActionBar);
}
boolean useOrangeTheme = preferences.getBoolean(PREF_ORANGE_THEME, false);
if (useOrangeTheme) {
setTheme(R.style.AppTheme_Orange_NoActionBar);
}
boolean useRedTheme = preferences.getBoolean(PREF_RED_THEME, false);
if (useRedTheme) {
setTheme(R.style.AppTheme_Red_NoActionBar);
}
boolean useYellowTheme = preferences.getBoolean(PREF_YELLOW_THEME, false);
if (useYellowTheme) {
setTheme(R.style.AppTheme_Yellow_NoActionBar);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bowler_profile_view);
Intent intent = getIntent();
Boolean shouldUpdate = getIntent().getExtras().getBoolean("shouldUpdate");
String savedLeagueId = intent.getStringExtra("leagueId");
String savedBowlerId = String.valueOf(getIntent().getIntExtra("bowlerId",2));
int bowlerId = Integer.valueOf(savedBowlerId);
getBowlerProfile(savedLeagueId, bowlerId);
// Get The min and max score
MaxMin bowlerMaxMin = db.getMaxAndminScoresAll();
Log.d("SCORES",
"\n\tMaximum Score is " + String.valueOf(bowlerMaxMin.getMax()) +
"\n\tMinimum Score is " + String.valueOf(bowlerMaxMin.getMin()));
}
public void getBowlerProfile(String savedLeagueId, int savedBowlerId) {
String bn, ba, bh;
SQLiteOpenHelper database = new DatabaseHelper(this);
SQLiteDatabase db = database.getReadableDatabase();
Cursor viewBowlerProfile = db.query( Bowler.TABLE_NAME,
new String[]{Bowler.COLUMN_ID, Bowler.COLUMN_LEAGUE_ID, Bowler.COLUMN_NAME, Bowler.COLUMN_BOWLER_AVERAGE, Bowler.COLUMN_BOWLER_HANDICAP, Bowler.COLUMN_TIMESTAMP},
Bowler.COLUMN_ID + "=?",
new String[]{String.valueOf(savedBowlerId)}, null, null, null, null);
if (viewBowlerProfile.moveToFirst()) {
//Prepare League Object
bowler = new Bowler(
viewBowlerProfile.getInt(viewBowlerProfile.getColumnIndex(Bowler.COLUMN_ID)),
viewBowlerProfile.getString(viewBowlerProfile.getColumnIndex(Bowler.COLUMN_LEAGUE_ID)),
bn = viewBowlerProfile.getString(viewBowlerProfile.getColumnIndex(Bowler.COLUMN_NAME)),
ba = viewBowlerProfile.getString(viewBowlerProfile.getColumnIndex(Bowler.COLUMN_BOWLER_AVERAGE)),
bh = viewBowlerProfile.getString(viewBowlerProfile.getColumnIndex(Bowler.COLUMN_BOWLER_HANDICAP)),
viewBowlerProfile.getString(viewBowlerProfile.getColumnIndex(Bowler.COLUMN_TIMESTAMP)));
final TextView bowlerName = (TextView) findViewById(R.id.tvBowlerName);
final TextView bowlerAverage = (TextView) findViewById(R.id.tvBowlerAverageValue);
final TextView bowlerHandicap = (TextView) findViewById(R.id.tvBowlerHandicapValue);
bowlerName.setText(String.valueOf(bn));
bowlerAverage.setText(String.valueOf(ba));
bowlerHandicap.setText(String.valueOf(bh));
//Close Database Connection
viewBowlerProfile.close();
}
//View League Profile Cancel Button
final Button cancel_button = (Button) findViewById(R.id.bCancel);
cancel_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("SAVEDLEAGUEID_VAL", ">>" + String.valueOf(savedLeagueId) + "<<");
Intent intent = new Intent(getApplicationContext(), BowlerActivity.class);
intent.putExtra("leagueId", savedLeagueId);
startActivity(intent);
finish();
overridePendingTransition(0, 0);
/*Intent intent = new Intent(getApplicationContext(), BowlerActivity.class);
intent.putExtra("leagueId", savedLeagueId);
Log.d("LEAGUEID VALUE","value of leagueId = " + String.valueOf(savedLeagueId));
startActivity(intent);
finish();
overridePendingTransition(0, 0);*/
}
});
//Edit League Profile Cancel Button
final Button edit_button = (Button) findViewById(R.id.bEdit);
edit_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int bowlerId = bowler.getId();
Intent intent = new Intent(getApplicationContext(), BowlerProfileEditActivity.class);
intent.putExtra("bowlerId", bowlerId);
intent.putExtra("leagueId", savedLeagueId);
startActivity(intent);
finish();
overridePendingTransition(0, 0);
}
});
}
}
Logcat
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'ca.rvogl.tpbcui.utils.MaxMin ca.rvogl.tpbcui.database.DatabaseHelper.getMaxAndminScoresAll()' on a null object reference
at ca.rvogl.tpbcui.views.BowlerProfileViewActivity.onCreate(BowlerProfileViewActivity.java:79)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
Attempting to group by bowlerId and seriesId
public Cursor getMaxMinScoresAllAndroid(String bowlerId) {
SQLiteDatabase db = this.getWritableDatabase();
String tmptbl = "summed_scores";
String tmptblcol = "sum_score";
String tmpBowlerIdCol = "bowler_id";
String tmpSeriesIdCol = "series_id";
String crttmptbl = "CREATE TEMP TABLE IF NOT EXISTS " + tmptbl + "(" +
tmptblcol + " INTEGER," +
tmpBowlerIdCol + " TEXT," +
tmpSeriesIdCol + " TEXT)";
String empttmptbl = "DELETE FROM " + tmptbl;
db.execSQL(crttmptbl);
db.execSQL(empttmptbl);
String[] columns = new String[]{"sum(score) AS "};
Cursor csr = db.query(Game.TABLE_NAME,columns,null,null,Game.COLUMN_BOWLER_ID + " = '" + bowlerId + "'", Game.COLUMN_SERIES_ID,null,null);
DatabaseUtils.dumpCursor(csr);
while (csr.moveToNext()) {
ContentValues cv = new ContentValues();
cv.put(tmptblcol,csr.getInt(csr.getColumnIndex(tmptblcol)));
cv.put(tmpBowlerIdCol,csr.getInt(csr.getColumnIndex(tmpBowlerIdCol)));
cv.put(tmpSeriesIdCol,csr.getInt(csr.getColumnIndex(tmpSeriesIdCol)));
db.insert(tmptbl,null,cv);
}
csr.close();
columns = new String[]{"max(" +
tmptblcol +
") AS " + DERIVEDCOL_MAXSCORE,
"min(" +
tmptblcol +
") AS " + DERIVEDCOl_MINSCORE};
return csr = db.query(tmptbl,columns,null,null,null,null,null);
}
public MaxMin getMaxAndminScoresAll(String bowlerId) {
MaxMin rv = new MaxMin(0,0);
Cursor csr = getMaxMinScoresAllAndroid(bowlerId);
if (csr.moveToFirst()) {
rv.setMin(csr.getInt(csr.getColumnIndex(DERIVEDCOl_MINSCORE)));
rv.setMax(csr.getInt(csr.getColumnIndex(DERIVEDCOL_MAXSCORE)));
}
csr.close();
return rv;
}
You could do this (assuming the table is named myscores and the columns are _id and score) using :-
WITH cte1 AS
(
sum(score) AS sum_score
FROM myscores
GROUP BY _id
)
SELECT max(sum_score) AS min_score, min(sum_score) FROM cte1;
Using this would result in the following :-
Notes
AS is used to rename the output columns
without renaming the columns they would be named max(sum_score) and min(sum_score) respectively.
SQL As Understood By SQLite - Aggregate Functions
This utilises the SQLite aggregate functions max and min and the GROUP BY clause to aggregate the columns according to the _id column.
This also utilises a Common Table Expression (an intermediate/temporary table).
SQL As Understood By SQLite - WITH clause
Incorporating into an Android App (see note at end)
The following is an example App demonstrates how this can be incorporated fro Android :-
First a simple class for the Minimum and maximum vales (as used in the alternative getMaxAndMinScores method)
MaxMin.java (optional)
public class MaxMin {
private int min;
private int max;
public MaxMin(int min, int max) {
this.min = min;
this.max = max;
}
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
}
DBHelper.java
The subclass of SQLiteOpenHelper (just the one table name myscores)
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TB_SCORE = "myscores";
public static final String COL_SCORE = "score";
public static final String COL_ID = BaseColumns._ID;
public static final String DERIVEDCOL_MAXSCORE = "max_score";
public static final String DERIVEDCOl_MINSCORE = "min_score";
private static final String crt_myscores_sql = "CREATE TABLE IF NOT EXISTS " + TB_SCORE + "(" +
COL_ID + " INTEGER," +
COL_SCORE + " INTEGER" +
")";
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(crt_myscores_sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public long addScore(long id, int score) {
ContentValues cv = new ContentValues();
cv.put(COL_ID,id);
cv.put(COL_SCORE,score);
return this.getWritableDatabase().insert(TB_SCORE,null,cv);
}
public Cursor getMaxMinScores() {
String sum_score = "sum_score";
String cte1 = "cte1";
String rawqry = " WITH " + cte1 +
" AS " +
"(" +
"SELECT sum(" +
COL_SCORE +
") AS " + sum_score +
" FROM " + TB_SCORE + " GROUP BY " + COL_ID +
") " +
"SELECT " +
" max(" +
sum_score +
") AS " + DERIVEDCOL_MAXSCORE +
"," +
" min(" +
sum_score +
") AS " + DERIVEDCOl_MINSCORE +
" FROM " + cte1 + ";";
return this.getWritableDatabase().rawQuery(rawqry,null);
}
public MaxMin getMaxAndMinScores() {
MaxMin rv = new MaxMin(0,0);
Cursor csr = getMaxMinScores();
if (csr.moveToFirst()) {
rv.setMin(csr.getInt(csr.getColumnIndex(DERIVEDCOl_MINSCORE)));
rv.setMax(csr.getInt(csr.getColumnIndex(DERIVEDCOL_MAXSCORE)));
}
csr.close();
return rv;
}
}
MainActivity.java
The activity that a) adds some rows and then b) gets the maximum and minimum scores (twice using alternative methods) :-
public class MainActivity extends AppCompatActivity {
DBHelper mDBHlpr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBHlpr = new DBHelper(this);
// Add Some scores
mDBHlpr.addScore(1,112);
mDBHlpr.addScore(1,123);
mDBHlpr.addScore(1,144);
mDBHlpr.addScore(2,212);
mDBHlpr.addScore(2,190);
mDBHlpr.addScore(2,300);
mDBHlpr.addScore(3,234);
mDBHlpr.addScore(3,134);
mDBHlpr.addScore(3,122);
mDBHlpr.addScore(4,100);
mDBHlpr.addScore(4,111);
mDBHlpr.addScore(4,114);
// Get The min and max scores example 1
Cursor csr = mDBHlpr.getMaxMinScores();
if (csr.moveToFirst()) {
int max_score = csr.getInt(csr.getColumnIndex(DBHelper.DERIVEDCOL_MAXSCORE));
int min_score = csr.getInt(csr.getColumnIndex(DBHelper.DERIVEDCOl_MINSCORE));
Log.d("SCORES",
"\n\tMaximum Score is " + String.valueOf(max_score) +
"\n\tMinimum Score is " + String.valueOf(min_score)
);
}
//Alternative utilising the MaxMin object
MaxMin mymaxmin = mDBHlpr.getMaxAndMinScores();
Log.d("SCORES",
"\n\tMaximum Score is " + String.valueOf(mymaxmin.getMax()) +
"\n\tMinimum Score is " + String.valueOf(mymaxmin.getMin())
);
}
}
IMPORTANT
The WITH clause was introduced in SQL 3.8.3, some older versions of Android (below lollipop (but can be device independent)) will not
support the WITH clause.
The following methods, as equivalents of getMaxMinScores and getMaxAndMinScores could be used for any Android version :-
public Cursor getMaxMinScoresAllAndroid() {
SQLiteDatabase db = this.getWritableDatabase();
String tmptbl = "summed_scores";
String tmptblcol = "sum_score";
String crttmptbl = "CREATE TEMP TABLE IF NOT EXISTS " + tmptbl + "(" +
tmptblcol + " INTEGER" +
")";
String empttmptbl = "DELETE FROM " + tmptbl;
db.execSQL(crttmptbl);
db.execSQL(empttmptbl);
String[] columns = new String[]{"sum(score) AS " + tmptblcol};
Cursor csr = db.query(TB_SCORE,columns,null,null,COL_ID,null,null);
DatabaseUtils.dumpCursor(csr);
while (csr.moveToNext()) {
ContentValues cv = new ContentValues();
cv.put(tmptblcol,csr.getInt(csr.getColumnIndex(tmptblcol)));
db.insert(tmptbl,null,cv);
}
csr.close();
columns = new String[]{"max(" +
tmptblcol +
") AS " + DERIVEDCOL_MAXSCORE,
"min(" +
tmptblcol +
") AS " + DERIVEDCOl_MINSCORE};
return csr = db.query(tmptbl,columns,null,null,null,null,null);
}
public MaxMin getMaxAndminScoresAllAndroid() {
MaxMin rv = new MaxMin(0,0);
Cursor csr = getMaxMinScoresAllAndroid();
if (csr.moveToFirst()) {
rv.setMin(csr.getInt(csr.getColumnIndex(DERIVEDCOl_MINSCORE)));
rv.setMax(csr.getInt(csr.getColumnIndex(DERIVEDCOL_MAXSCORE)));
}
csr.close();
return rv;
}
These utilise an intermediate temporary table so bypass the restriction of using WITH

How to get data from database on click of an event?

I am generating an events dynamically. These events data I am storing in sqlite database. Now I want to retrieve data of the clicked event. I tried to retrieve data but always getting 0th id data.
Generating events function :
private void createEvent(LayoutInflater inflater, ViewGroup dayplanView, int fromMinutes, int toMinutes, String title) {
final View eventView = inflater.inflate(R.layout.event_view, dayplanView, false);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) eventView.getLayoutParams();
RelativeLayout container = (RelativeLayout) eventView.findViewById(R.id.container);
TextView tvTitle = (TextView) eventView.findViewById(R.id.textViewTitle);
if (tvTitle.getParent() != null)
((ViewGroup) tvTitle.getParent()).removeView(tvTitle);
tvTitle.setText(title);
int distance = (toMinutes - fromMinutes);
layoutParams.topMargin = dpToPixels(fromMinutes + 9);
layoutParams.height = dpToPixels(distance);
eventView.setLayoutParams(layoutParams);
dayplanView.addView(eventView);
container.addView(tvTitle);
eventView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getActivity(),AddEventActivity.class);
startActivity(i);
}
});
}
This is my attempt to get data:
db = new EventTableHelper(getApplication());
eventData = new EventData();
if(editMode)//true
{
eventData = events.get(id);
Toast.makeText(getApplicationContext(),String.valueOf(id),Toast.LENGTH_LONG).show();
title.setText(eventData.getTitle());
eventTitle = title.getText().toString();
db.updateEvent(eventData);
Toast.makeText(getApplicationContext(),"Edit mode",Toast.LENGTH_LONG).show();
Log.i("Log","save mode");
}
I have EventTableHelper in that i have created functions to get event,update and delete events.
public class EventTableHelper extends SQLiteOpenHelper {
private static final String TABLE = "event";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_FROM_DATE = "datefrom";
private static final String KEY_TO_DATE = "dateto";
private static final String KEY_LOCATION = "location";
private static final String KEY_DAY_OF_WEEK = "dayofweek";
public EventTableHelper(Context context) {
super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
public void createTable(SQLiteDatabase db){
String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE+ "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_TITLE + " TEXT,"
+ KEY_FROM_DATE + " DATE,"
+ KEY_TO_DATE + " DATE,"
+ KEY_DAY_OF_WEEK + " TEXT "
+ KEY_LOCATION + " TEXT" + ")";
db.execSQL(CREATE_EVENTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
// createTable(db);
// onCreate(db);
}
public void addEvent(EventData event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE,event.getTitle());
values.put(KEY_FROM_DATE, event.getFromDate());
values.put(KEY_TO_DATE,event.getToDate());
values.put(KEY_DAY_OF_WEEK,event.getDayOfWeek());
values.put(KEY_LOCATION,event.getLocation());
db.insert(TABLE, null, values);
db.close();
}
EventData getEvent(int id) {
SQLiteDatabase db = this.getReadableDatabase();
EventData eventData = new EventData();
Cursor cursor = db.query(TABLE, new String[]{KEY_ID,
KEY_TITLE, KEY_FROM_DATE, KEY_TO_DATE,KEY_DAY_OF_WEEK, KEY_LOCATION}, KEY_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if( cursor != null && cursor.moveToFirst() ) {
eventData = new EventData(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4), cursor.getString(5));
}
return eventData;
}
public List<EventData> getAllEvents() {
List<EventData> conList = new ArrayList<EventData>();
String selectQuery = "SELECT * FROM " + TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
EventData event = new EventData();
event.setId(Integer.parseInt(cursor.getString(0)));
event.setTitle(cursor.getString(1));
event.setFromDate(cursor.getString(2));
event.setToDate(cursor.getString(3));
event.setLocation(cursor.getString(4));
conList.add(event);
} while (cursor.moveToNext());
}
return conList;
}
}
I want to show data and update data if changes made.
Whats going wrong?

Categories

Resources