database records not updating android studio , sql-lite - java

Could someone help me? my records are not updating.
I guess the edittext stay the same but not too sure.
How to change the view values that is being put in the edittext to change to the values in updating edittexts.
Would appreciate some help with this
Thank you.
DatabaseManager
public Cursor selectRow(String ID) {
String query = "Select * from " + TABLE_NAME + " where studentID = " + ID;
Cursor cursor = db.rawQuery(query, null);
return cursor;
}
public boolean updateData(String id, String fn, String ln, String ge, String cs, String a, String loc) {
ContentValues contentValues = new ContentValues();
contentValues.put("studentID", id);
contentValues.put("first_name", fn);
contentValues.put("last_name", ln);
contentValues.put("gender", ge);
contentValues.put("course_study", cs);
contentValues.put("age", a);
contentValues.put("location", loc);
db.update(TABLE_NAME, contentValues, "studentID = ?", new String[]{id});
return true;
}
The above is parts of my database that I use in this activity.
activity main.java
private void UpdateData() {
u.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
uptable.setVisibility(View.VISIBLE);
again.setVisibility(View.VISIBLE);
Cursor res = mydManager.selectRow(text);
if (res != null && res.moveToFirst()) {
String id = Integer.toString(res.getInt(0));
String nme = res.getString(1);
String lnme = res.getString(2);
String gen = res.getString(3);
String corse = res.getString(4);
String ag = Integer.toString(res.getInt(5));
String lo = res.getString(6);
studid.setText(id);
fname.setText(nme);
lname.setText(lnme);
gender.setText(gen);
course.setText(corse);
age.setText(ag);
loc.setText(lo);
}
}
}
);
}
public void UpdateData1() {
again.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
uptable.setVisibility(View.GONE);
String id = studid.getText().toString();
String nme = fname.getText().toString();
String lnme = lname.getText().toString();
String gen = gender.getText().toString();
String corse = course.getText().toString();
String ag = age.getText().toString();
String lo = loc.getText().toString();
boolean isUpdated = mydManager.updateData(id, nme , lnme, gen, corse ,ag , lo);
if (isUpdated == true)
Toast.makeText(Main4Activity.this, "Data Updated", Toast.LENGTH_LONG).show();
else
Toast.makeText(Main4Activity.this, "Data Not Updated", Toast.LENGTH_LONG).show();
}
}
);
}
I tried having a button to set the data but it still stays the same.

Sorry din't read the code, take the sample if it helps
Just the logic..
public long updateNote(NoteModel noteModel) {
if (LOG_DEBUG) UtilLogger.showLogUpdate(TAG, noteModel, noteModel.getRow_pos());
long updatedRow = 0;
try {
ContentValues contentValues = new ContentValues();
contentValues.put(DBSchema.DB_TITLE, noteModel.getTitle());
contentValues.put(DBSchema.DB_IMAGE_PATH, noteModel.getImgUriPath());
contentValues.put(DBSchema.DB_SUB_TEXT, noteModel.getSub_text());
contentValues.put(DBSchema.DB_CREATE_DATE, noteModel.getCreateDate());
contentValues.put(DBSchema.DB_UPDATE_DATE, noteModel.getUpdateDate());
contentValues.put(DBSchema.DB_SCHEDULED_TIME_LONG, noteModel.getScheduleTimeLong());
contentValues.put(DBSchema.DB_SCHEDULED_TIME_WHEN, noteModel.getScheduledWhenLong());
contentValues.put(DBSchema.DB_SCHEDULED_TITLE, noteModel.getScheduledTitle());
contentValues.put(DBSchema.DB_IS_ALARM_SCHEDULED, noteModel.getIsAlarmScheduled());
contentValues.put(DBSchema.DB_IS_TASK_DONE, noteModel.getIsTaskDone());
contentValues.put(DBSchema.DB_IS_ARCHIVED, noteModel.getIsArchived());
updatedRow = mSqLiteDatabase.updateWithOnConflict(
DBSchema.DB_TABLE_NAME,
contentValues,
DBSchema.DB_ROW_ID + " =?", new String[]{String.valueOf(noteModel.get_id())}, mSqLiteDatabase.CONFLICT_REPLACE);
return updatedRow;
} catch (SQLException e) {
e.printStackTrace();
}
return updatedRow;
}
then take the cursor
public Cursor getCursorForAlarmScheduled(String passAlarmScheduledStatus) {
if (LOG_DEBUG)
Log.w(TAG, " pick all record with alarmScheduled 1 : " + passAlarmScheduledStatus);
return mSqLiteDatabase.rawQuery(DBSchema.DB_SELECT_ALL +
" WHERE " + DBSchema.DB_IS_ALARM_SCHEDULED + " = " + passAlarmScheduledStatus, null);
}
and then extract
//common operation for all,
public static List<NoteModel> extractCommonData(Cursor cursor, List<NoteModel> noteModelList) {
noteModelList = new ArrayList<>();
if (LOG_DEBUG) Log.i(TAG, "inside extractCommonData()");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
NoteModel noteModel = new NoteModel();
noteModel.set_id(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_ROW_ID)));
noteModel.setTitle(cursor.getString(cursor.getColumnIndex(DBSchema.DB_TITLE)));
noteModel.setImgUriPath(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IMAGE_PATH)));
noteModel.setSub_text(cursor.getString(cursor.getColumnIndex(DBSchema.DB_SUB_TEXT)));
noteModel.setCreateDate(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_CREATE_DATE)));
noteModel.setUpdateDate(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_UPDATE_DATE)));
noteModel.setScheduleTimeLong(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TIME_LONG)));
noteModel.setScheduledWhenLong(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TIME_WHEN)));
noteModel.setScheduledTitle(cursor.getString(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TITLE)));
noteModel.setIsAlarmScheduled(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_ALARM_SCHEDULED)));
noteModel.setIsTaskDone(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_TASK_DONE)));
noteModel.setIsArchived(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_ARCHIVED)));
noteModelList.add(noteModel);
} while (cursor.moveToNext());
}
cursor.close();
}
return noteModelList;
}
Again, I din't read,just copied from my old samples
Please do find the needful, cheers

Related

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/

Android studio: I am trying to change the shared preferences and want to store the data in the SQLite database [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am new in Java Programming.
Now, I am facing the problem that I want to change the shared preferences and want to use the SQLite database to store these data. I had created the table for store these data and I am trying to save these data in SQLite.
How can I do? Anyone can help me ????
MyDatabase-Table
This is my code that using shared preferences :
public class Login extends AppCompatActivity {
InputStream inputStream;
ACDatabase db;
SharedPreferences prefs;
ActivityLoginBinding binding;
AC_Class.Connection connection;
AC_Class.Register reg;
String versionNo;
String url;
String urlStr;
String id;
String pwd;
private static String uniqueID = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
getSupportActionBar().hide();
// Placeholder
versionNo = "3.1.6";
reg = new AC_Class.Register();
connection = new AC_Class.Connection();
binding.setConSettings(connection);
db = new ACDatabase(this);
// Check preferences/create if nonexistent
prefs = this.getSharedPreferences("com.presoft.androidmobilestock", Context.MODE_PRIVATE);
uniqueID = prefs.getString("UUID", null);
if (uniqueID == null)
{
uniqueID = UUID.randomUUID().toString();
//uniqueID = "3FDE9813F93A47CBA6CD4F5DAAECEE01";
prefs.edit().putString("UUID", uniqueID).commit();
}
binding.lblUUID.setText(uniqueID);
binding.lblVersion.setText(versionNo);
if (prefs.getString("ID", id) != null) {
binding.rmbCheckBox.setChecked(true);
url = prefs.getString("URL", url);
binding.txtURL.setText(prefs.getString("URLstr", urlStr));
binding.txtID.setText(prefs.getString("ID", id));
binding.txtpw.setText(prefs.getString("pwd", pwd));
}
if (prefs.getString("Default_curr", null) == null) {
prefs.edit().putString("Default_curr", "RM").apply();
}
if (prefs.getString("Default_loc", null) == null) {
Cursor tempCursor = db.getLocation();
if (tempCursor.moveToNext()) {
prefs.edit().putString("Default_loc", tempCursor
.getString(tempCursor.getColumnIndex("Location"))).apply();
}
}
// Version number
if (prefs.getString("Version ", null) == null) {
prefs.edit().putString("Version", versionNo).apply();
}
// Tax Inclusive
if (!prefs.getBoolean("taxInclusive", false)) {
prefs.edit().putBoolean("taxInclusive", false).apply();
}
if (Build.MODEL.equals("HC720"))
{
Snackbar.make(findViewById(android.R.id.content), "RFID Detected.", Snackbar.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
finish();
}
//On return of intent
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 7) {
url = data.getStringExtra("URLKey");
urlStr = data.getStringExtra("URLStr");
Log.i("custDebug", url + ", " + urlStr);
binding.txtURL.setText(urlStr);
if (!TextUtils.isEmpty(binding.txtURL.getText().toString())) {
new GetModules(Login.this).execute(url);
new GetLoginList(Login.this).execute(url);
new SetDevice(Login.this).execute(url);
}
}
}
//Open connection settings
public void btnSetClicked(View view) {
Intent intent = new Intent(Login.this, ConnectionSettings.class);
startActivityForResult(intent, 7);
}
//Reset Database
public void btnResetDbClicked(final View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Reset DB");
builder.setMessage("Are you sure you want to reset the Database?");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (input.getText().toString().equals("presoftmobile")) {
db.close();
deleteDatabase("AutoCountDatabase");
} else {
// Toast.makeText(getApplicationContext(), "Incorrect Password", Toast.LENGTH_SHORT);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
//Login button
public void btnLoginBtnClicked(View view) {
if (TextUtils.isEmpty(binding.txtURL.getText().toString())) {
binding.txtURL.setError("This field can't be blank.");
//return;
}
if (TextUtils.isEmpty(binding.txtID.getText().toString())) {
binding.txtID.setError("This field can't be blank.");
//return;
}
if (TextUtils.isEmpty(binding.txtpw.getText().toString())) {
binding.txtpw.setError("This field can't be blank.");
//return;
}
//Non-empty fields
else {
Cursor checkData = db.loginValidate(binding.txtID.getText().toString(),
binding.txtpw.getText().toString().toUpperCase());
if (checkData.getCount() > 0) {
checkData.moveToNext();
//Shared Preferences
prefs.edit().putString("URL", url).apply();
prefs.edit().putString("URLstr", binding.txtURL.getText().toString()).apply();
if (binding.rmbCheckBox.isChecked()) {
prefs.edit().putString("ID", binding.txtID.getText().toString()).apply();
prefs.edit().putString("pwd", binding.txtpw.getText().toString()).apply();
}
prefs.edit().putInt("EnableSetting", checkData.getInt(checkData.getColumnIndex("EnableSetting"))).apply();
prefs.edit().putInt("FilterByAgent", checkData.getInt(checkData.getColumnIndex("FilterByAgent"))).apply();
prefs.edit().putInt("Sales", checkData.getInt(checkData.getColumnIndex("Sales"))).apply();
prefs.edit().putInt("Purchase", checkData.getInt(checkData.getColumnIndex("Purchase"))).apply();
prefs.edit().putInt("Transfer", checkData.getInt(checkData.getColumnIndex("Transfer"))).apply();
if (url != null) {
try {
// Check Connection
new SetDevice(Login.this).execute(url);
// Go to main
Intent intent = new Intent(Login.this, Dashboard.class);
intent.putExtra("URLKey", url);
intent.putExtra("URLStr", binding.txtURL.getText().toString());
startActivity(intent);
finish();
} catch (Exception e) {
Log.i("custDebug", e.getMessage());
Toast.makeText(this, "Unable to connect to server", Toast.LENGTH_SHORT).show();
}
}
} else {
Toast.makeText(this, "Invalid login credentials", Toast.LENGTH_SHORT).show();
binding.txtpw.setText(null);
}
checkData.close();
}
}
This is the code that to save the data in SQLite database (but getting error):
public class Login extends AppCompatActivity {
InputStream inputStream;
ACDatabase db;
SharedPreferences prefs;
ActivityLoginBinding binding;
AC_Class.Connection connection;
AC_Class.Register reg;
String versionNo;
String url;
String urlStr;
String id;
String pwd;
private static String uniqueID = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
getSupportActionBar().hide();
// Placeholder
versionNo = "3.1.6";
connection = new AC_Class.Connection();
binding.setConSettings(connection);
db = new ACDatabase(this);
db = new ACDatabase(this);
uniqueID = db.getReg("8");
uniqueID = prefs.getString("UUID", null);
if (uniqueID == null)
{
uniqueID = UUID.randomUUID().toString();
//uniqueID = "3FDE9813F93A47CBA6CD4F5DAAECEE01";
db.updateREG("8", uniqueID);
}
binding.lblUUID.setText(uniqueID);
binding.lblVersion.setText(versionNo);
if (prefs.getString("ID", id) != null) {
binding.rmbCheckBox.setChecked(true);
url = prefs.getString("URL", url);
binding.txtURL.setText(prefs.getString("URLstr", urlStr));
binding.txtID.setText(prefs.getString("ID", id));
binding.txtpw.setText(prefs.getString("pwd", pwd));
}
if (prefs.getString("Default_curr", null) == null) {
prefs.edit().putString("Default_curr", "RM").apply();
}
if (prefs.getString("Default_loc", null) == null) {
Cursor tempCursor = db.getLocation();
if (tempCursor.moveToNext()) {
prefs.edit().putString("Default_loc", tempCursor
.getString(tempCursor.getColumnIndex("Location"))).apply();
}
}
// Version number
if (prefs.getString("Version ", null) == null) {
prefs.edit().putString("Version", versionNo).apply();
}
// Tax Inclusive
if (!prefs.getBoolean("taxInclusive", false)) {
prefs.edit().putBoolean("taxInclusive", false).apply();
}
if (Build.MODEL.equals("HC720"))
{
Snackbar.make(findViewById(android.R.id.content), "RFID Detected.", Snackbar.LENGTH_SHORT).show();
}
}
mydatabasehelper
//GET value by id
public Cursor getReg(String id) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT Value FROM " + TABLE_NAME_REG + " WHERE ID ='" + id + "'",null);
return data;
}
//update value
public boolean updateREG(String ID, String Value) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("Value", Value);
String[] args = new String[]{ID};
database.update("Reg", cv, "ID = ?", args);
return true;
}
The following is a working example that acts very similar to shared prefs but stores the prefs in an SQLite database.
The table is very simple 2 columns. The key (name of the stored value) and the value itself. Which can be String, boolean, int, long or Float.
It includes methods to; insert (add) a key/value pair, update a key/value pair and to get a value according to the key and also to return a default value as passed (making it easy to detect if the value was retrieved).
The DatabaseHelper (sub class of SQLiteOpenHelper) has most of the code and is :-
class DBHelper extends SQLiteOpenHelper {
private static volatile DBHelper instance = null;
private SQLiteDatabase db = null;
public static final String DBNAME = "sharedpreferences.db";
public static final int DBVERSION = 1;
public static final String TBLNAME_SP = "_shared_preferences";
public static final String COLNAME_SP_KEY = "_key";
public static final String COLNAME_SP_VALUE = "_value";
private DBHelper(#Nullable Context context) {
super(context, DBNAME, null, DBVERSION);
db = this.getWritableDatabase();
}
public static DBHelper getInstance(Context context) {
if (instance == null) {
instance = new DBHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TBLNAME_SP +
"(" +
COLNAME_SP_KEY + " PRIMARY KEY," +
COLNAME_SP_VALUE + " TEXT" +
")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
private long insertPrefsRow(ContentValues cv, String key) {
cv.put(COLNAME_SP_KEY,key);
return db.insertWithOnConflict(TBLNAME_SP,null,cv, SQLiteDatabase.CONFLICT_IGNORE);
}
public long insertPrefsValue (String key, int value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, String value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, long value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, boolean value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, float value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
private long updatePrefs(String key, ContentValues cv) {
return db.update(TBLNAME_SP,cv,COLNAME_SP_KEY + "=?",new String[]{key} );
}
public long updatePrefsStringValue(String key, String newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, boolean newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, int newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, long newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, Float newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
private Cursor getPrefsValue(String key) {
return db.query(TBLNAME_SP,new String[]{COLNAME_SP_VALUE},COLNAME_SP_KEY + "=?",new String[]{key},null,null,null);
}
public String getPrefsStringValue(String key, String default_value) {
String rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getString(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public Boolean getPrefsBooleanValue(String key, boolean default_value ) {
Boolean rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COLNAME_SP_VALUE)) != 0;
csr.close();
}
return rv;
}
public int getPrefsIntValue(String key, int default_value) {
int rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public long getPrefsLongValue(String key, long default_value) {
long rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getLong(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public Float getPrefsFLoatValue(String key, Float default_value) {
Float rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getFloat(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
}
The following is an activity that demonstrates usage:-
public class MainActivity extends AppCompatActivity {
DBHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = DBHelper.getInstance(this);
db.insertPrefsValue("UUID","3FDE9813F93A47CBA6CD4F5DAAECEE01");
db.insertPrefsValue("taxInclusive",false);
db.insertPrefsValue("myprefs_int",100);
db.insertPrefsValue("myprefs_long",100L);
db.insertPrefsValue("myprefs_float",10.567F);
Log.d("PREFSINFO",
"Stored UUID is " + db.getPrefsStringValue("UUID","000000000000000000000000") +
" Stored taxinclusive is " + db.getPrefsBooleanValue("taxInclusive",true) +
" Stored mpint is " + db.getPrefsIntValue("myprefs_int",-99) +
" Stored mplong is " + db.getPrefsLongValue("myprefs_long",-99999999) +
" Stored mpfloat is " + db.getPrefsFLoatValue("myprefs_float",-999999.999999F) +
" NOT STORED is " + db.getPrefsFLoatValue("NOT A SET KEY",-3333.3333F)
);
db.updatePrefsStringValue("UUID","FFFF9813F93A47CBA6CD4F5DAAECEE01");
Log.d("PREFSINFO",
"Stored UUID is " + db.getPrefsStringValue("UUID","000000000000000000000000") +
" Stored taxinclusive is " + db.getPrefsBooleanValue("taxInclusive",true) +
" Stored mpint is " + db.getPrefsIntValue("myprefs_int",-99) +
" Stored mplong is " + db.getPrefsLongValue("myprefs_long",-99999999) +
" Stored mpfloat is " + db.getPrefsFLoatValue("myprefs_float",-999999.999999F) +
" NOT STORED is " + db.getPrefsFLoatValue("NOT A SET KEY",-3333.3333F)
);
}
}
When run (or rerun BUT when rerun the updated UUID rather than the original is retrieved) the log contains :-
D/PREFSINFO: Stored UUID is 3FDE9813F93A47CBA6CD4F5DAAECEE01 Stored taxinclusive is false Stored mpint is 100 Stored mplong is 100 Stored mpfloat is 10.567 NOT STORED is -3333.3333
D/PREFSINFO: Stored UUID is FFFF9813F93A47CBA6CD4F5DAAECEE01 Stored taxinclusive is false Stored mpint is 100 Stored mplong is 100 Stored mpfloat is 10.567 NOT STORED is -3333.3333
NOT STORED demonstrates the default value being returned when the Key/Name isn't stored.
As you can see UUID has been updated in the second line (if rerun both lines would show the updated value)

Android Studio + Database - Multiple check data to insert data if not exists

I'm having a problem with my code. I don't know how to check multiple columns in the database to insert different data on every not existing data.
For example:
1st input
Name: Raymond Jay Berin
Event: INTRAMURALS
FACILITATOR: CSG
2nd input
Name: Raymond Jay Berin
Event: LOVE SYMPOSIUM
FACILITATOR: DSSC
the thing here is that. Raymond Jay Berin already existed in the database, but I want Raymond Jay Berin will be inserted into a different event...
also, I already tried to create multiple tables but my project crashes when I click the attendance button to add data.
Code for DatabaseHelper.class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "attendance.sqlite";
public static final String TABLE_NAME = "attendance";
public static final String COL_1 = "ID";
public static final String COL_2 = "FULLNAME";
public static final String COL_EVENT_2 = "EVENT_NAME";
public static final String COL_EVENT_3 = "FACILITATOR_NAME";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
//ATTENDANCE
db.execSQL(" create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"FULLNAME TEXT NOT NULL, EVENT_NAME TEXT NOT NULL, FACILITATOR_NAME TEXT NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//ATTENDANCE
db.execSQL(" DROP TABLE IF EXISTS "+TABLE_NAME );
//recreate
onCreate(db);
}
//ATTENDANCE
public boolean insertData (String fullname, String event, String facilitator){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,fullname);
contentValues.put(COL_EVENT_2,event);
contentValues.put(COL_EVENT_3,facilitator);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public boolean checkIfRecordExist(String nameOfTable,String columnName,String columnValue) {
SQLiteDatabase db = null;
try {
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT "+columnName+" FROM "+nameOfTable+" WHERE "+columnName+"='"+columnValue+"'",null);
if (cursor.moveToFirst()) {
db.close();
Log.d("Record Already Exists", "Table is:" + nameOfTable + " ColumnName:" + columnName);
return true;//record Exists
}
Log.d("New Record ", "Table is:" + nameOfTable + " ColumnName:" + columnName + " Column Value:" + columnValue);
db.close();
} catch (Exception errorException) {
Log.d("Exception occured", "Exception occured " + errorException);
db.close();
}
return false;
} }
Code for the Attendance.java class
public class Attendance extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
DatabaseHelper myDb;
EditText fname , eventname, faciname;
Button attendance;
Button view;
Switch lock;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
myDb = new DatabaseHelper(this);
fname = findViewById(R.id.txtFullname);
eventname = findViewById(R.id.eventname);
faciname = findViewById(R.id.faciname);
attendance = findViewById(R.id.btnatt);
view = findViewById(R.id.btnview);
lock = findViewById(R.id.switchLock);
viewAll();
AddData();
lock.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (lock.isChecked()){
eventname.setEnabled(false);
faciname.setEnabled(false);
}else{
eventname.setEnabled(true);
faciname.setEnabled(true);
}
}
public void viewAll() {
view.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if (res.getCount() == 0) {
// show message
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("ID :" + res.getString(0) + "\n");
buffer.append("NAME :" + res.getString(1) + "\n");
buffer.append("EVENT :" + res.getString(2) + "\n");
buffer.append("FACILITATOR :" + res.getString(3) + "\n"+"\n");
}
// Show all data
showMessage("ATTENDANCE LIST", buffer.toString());
}
}
);
}
public void showMessage(String title, String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
public void AddData() {
attendance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String valInput = fname.getText().toString();
final String valInput1 = eventname.getText().toString();
final String valInput2 = faciname.getText().toString();
boolean valid = true;
if (TextUtils.isEmpty(valInput)) {
fname.setError("This Item must not be empty!");
valid = false;
}
if (TextUtils.isEmpty(valInput1)) {
eventname.setError("This Item must not be empty!");
valid = false;
}
if (TextUtils.isEmpty(valInput2)) {
faciname.setError("This Item must not be empty!");
valid = false;
}
if (valid) {
boolean isExist = myDb.checkIfRecordExist(DatabaseHelper.TABLE_NAME, DatabaseHelper.COL_1, fname.getText().toString());
if (!isExist) {
boolean isInserted = myDb.insertData(fname.getText().toString(), eventname.getText().toString(), faciname.getText().toString());
if (isInserted) {
Toast.makeText(Attendance.this, "Attendance Success", Toast.LENGTH_LONG).show();
fname.setText(null);
} else if (isInserted == false) {
Toast.makeText(Attendance.this, "Failed to Attendance", Toast.LENGTH_LONG).show();
}
}else if (isExist == true){
Toast.makeText(Attendance.this, "Failed to Attendance "+fname+" Already Existed", Toast.LENGTH_LONG).show();
}
}
}
}); }
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.Logout)
.setMessage(R.string.really_logout)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
Intent intent = new Intent(Attendance.this, MainActivity.class);
startActivity(intent);
Attendance.this.finish();
}
})
.setNegativeButton(R.string.no, null)
.show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}}
change checkIfRecordExist method like this
public boolean checkIfRecordExist(String nameOfTable,String columnName1,String columnValue1,String columnName2,String columnValue2) {
SQLiteDatabase db = null;
try {
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "+nameOfTable+" WHERE "+columnName1+"='"+columnValue1+"' and "+ columnName2 +"='"+columnValue2+"'",null);
.......................
change below line like this
boolean isExist = myDb.checkIfRecordExist(DatabaseHelper.TABLE_NAME, DatabaseHelper.COL_1, fname.getText().toString(),DatabaseHelper.COL_2, eventname.getText().toString())

Tracker service not working on some devices

I have written an application for Tracker; with a service that runs every 5 minutes. It works fine on Samsung Galaxy J7 Prime (Android 7.0) and Samsung Galaxy Tab A (Android 7.1), But when I run on Lenovo A2010 (Android 5.1), the service does not work. I don't know whether it is my code or my device which is causing the problem.
This is the log from when the service stopped:
10-08 09:01:31.122 721-737/? E/JavaBinder: *** Uncaught remote exception! (Exceptions are not yet supported across processes.)
java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
at com.android.internal.os.BatteryStatsImpl.updateAllPhoneStateLocked(BatteryStatsImpl.java:3321)
at com.android.internal.os.BatteryStatsImpl.notePhoneSignalStrengthLocked(BatteryStatsImpl.java:3351)
at com.android.server.am.BatteryStatsService.notePhoneSignalStrength(BatteryStatsService.java:395)
at com.android.server.TelephonyRegistry.broadcastSignalStrengthChanged(TelephonyRegistry.java:1448)
at com.android.server.TelephonyRegistry.notifySignalStrengthForSubscriber(TelephonyRegistry.java:869)
at com.android.internal.telephony.ITelephonyRegistry$Stub.onTransact(ITelephonyRegistry.java:184)
at android.os.Binder.execTransact(Binder.java:451)
And here is my service, AppService.java:
public class AppService extends Service {
private MyThread thread;
PowerManager.WakeLock wl;
DatabaseHelper myDb;
private static final String tracker = "Tracker";
String result=null,status=null,statusresult=null;
String stusername;
String imeiids;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!thread.isAlive()) {
thread.start();
}
return START_STICKY;
}
#Override
public void onDestroy() {
if (thread.isAlive()) {
stopService(new Intent(this, AppService.class));
}
super.onDestroy();
}
#Override
public void onCreate() {
Toast.makeText(AppService.this,"Start...",Toast.LENGTH_SHORT).show();
thread = new MyThread();
myDb = new DatabaseHelper(this);
SharedPreferences shared = getSharedPreferences(tracker, Context.MODE_PRIVATE);
stusername = shared.getString("username", "not found!").toString();
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE)== PackageManager.PERMISSION_GRANTED){
TelephonyManager c=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
SharedPreferences.Editor editor = shared.edit();
if(c.getDeviceId()==null){
editor.commit();
}
else{
editor.putString("imeiid", c.getDeviceId());
editor.commit();
}
}
}
private class MyThread extends Thread {
private static final String tag = "Sevice Demo";
private static final int delay = 60000;//60000=30sec/1minute
private int roundNumber = 0;
private boolean finishService = false;
#Override
public void run() {
while (true) {
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(
getApplicationContext().POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
if(ContextCompat.checkSelfPermission(AppService.this, android.Manifest.permission.READ_PHONE_STATE)== PackageManager.PERMISSION_GRANTED){
TelephonyManager c=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
imeiids = c.getDeviceId();
}
if(imeiids== null){
SharedPreferences shared = getSharedPreferences(tracker, Context.MODE_PRIVATE);
imeiids=shared.getString("imeiid", "").toString();
}
Date current = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
final String currentDateandTime = sdf.format(current);
if(!stusername.equals("not found!")){
//////////////////////////////////// Open GPS //////////////////////////////////////
int off=0;
try {
off = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
if(off==0){
Intent onGPS = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(onGPS);
}
////////////////////////////////////////////////////////////////////////////////////
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDateString = formatter.format(currentTime);
SimpleDateFormat formatstr = new SimpleDateFormat("EEE", Locale.US);
final String formattedDayString = formatstr.format(currentTime);
if (!haveNetworkConnection()) {
/*no network connect*/
}
else{
Cursor res = myDb.getDatasync(stusername);
if(res.getCount()==0){
Log.d("dddd", "no data");
}
else{
String datetimes=null,lats=null,longs=null;
res.moveToFirst();
do{
final String ids=res.getString(0);
datetimes=res.getString(1);
lats=res.getString(3);
longs=res.getString(4);
final String finalDatetimes = datetimes;
final String finalLats = lats;
final String finalLongs = longs;
new AsyncTask<Void,Void,Void>(){
#Override
protected Void doInBackground(Void... params) {
String location_url = "http://_____._________/__________/______________________.php";
try {
URL url = new URL(location_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("staffcode", "UTF-8") + "=" + URLEncoder.encode(stusername, "UTF-8")+ "&"
+ URLEncoder.encode("dateTime", "UTF-8") + "=" + URLEncoder.encode(finalDatetimes, "UTF-8") + "&"
+ URLEncoder.encode("lat", "UTF-8") + "=" + URLEncoder.encode(finalLats, "UTF-8") + "&"
+ URLEncoder.encode("lon", "UTF-8") + "=" + URLEncoder.encode(finalLongs, "UTF-8") + "&"
+ URLEncoder.encode("imei", "UTF-8") + "=" + URLEncoder.encode(imeiids, "UTF-8") + "&"
+ URLEncoder.encode("app", "UTF-8") + "=" + URLEncoder.encode("T:1.0", "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result = line;
}
JSONObject jsonObject = new JSONObject(result.toString());
for (int i = 0; i < jsonObject.length(); i++)
{
status=(jsonObject.getString("status")); //Get Status
statusresult=(jsonObject.getString("statusresult"));
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(status.equals("success")&& statusresult.equals("success")){
boolean isUpdate = myDb.updateDatasync(ids);
if(isUpdate) {
Log.d("Get Data ", "Updated");
}
else {
Log.d("Get Data ", "not updated");
}
}
else{
}
}
}.execute();
}while(res.moveToNext());
}
}
Cursor res = myDb.getData(stusername);
if (res.getCount() ==0) {
Log.d("dddd", "no data");
}
else {
res.moveToFirst();
do{
String asubstring = String.valueOf(res.getString(1)).substring(11, 16);
String datesub = res.getString(1).substring(0, 10);
if(currentDateandTime.equals(datesub)){ /* Today */ }
else{
//Not Today
if(!res.getString(5).equals("1")) { }
else{ // If Sync = 1 = Sync Success
boolean isDeleteSync = myDb.deleteDataSync(res.getString(0));
if(isDeleteSync) {
Log.d("Log Delete ", "Deleted");
}
else {
Log.d("Log Delete ", "Can't Deleted");
}
}
}
}while(res.moveToNext());
}
if (formattedDayString.equals("Sun")) {
}
else {
String hour = formattedDateString.substring(11, 13);
String minute = formattedDateString.substring(14, 16);
Integer ins = Integer.parseInt(minute);
if (hour.equals("08") || hour.equals("09") || hour.equals("10") || hour.equals("11") || hour.equals("12")
|| hour.equals("13") || hour.equals("14") || hour.equals("15") || hour.equals("16") || hour.equals("17")
|| hour.equals("18")) {
if((hour.equals("18"))&&(ins<=0)){
SimpleDateFormat formatterss = new SimpleDateFormat("HH:mm:ss");
String DateString = formatterss.format(currentTime);
String subtime= DateString.substring(3,5);
Integer minuteif=Integer.parseInt(subtime);
if(minuteif%5==0){
startService(new Intent(AppService.this, GetLocation.class));
}
}
if((!hour.equals("18"))){
SimpleDateFormat formatterss = new SimpleDateFormat("HH:mm:ss");
String DateString = formatterss.format(currentTime);
String subtime= DateString.substring(3,5);
Integer minuteif=Integer.parseInt(subtime);
if(minuteif%5==0){
startService(new Intent(AppService.this, GetLocation.class));
}
}
}
else{
}
}
try {
stopService(new Intent(AppService.this,GetLocation.class));
sleep(delay);
run();
}
catch (InterruptedException e) {
e.printStackTrace();
}
wl.release();
if (finishService) {
return;
}
}
}
}
}
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
}
It's my DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Tracker.db";
public static final String TABLE_NAME = "LocationMessenger";
public static final String COL_1 = "ID";
public static final String COL_2 = "DATE";
public static final String COL_3 = "USERNAME";
public static final String COL_4 = "LATITUDE";
public static final String COL_5 = "LONGITUDE";
public static final String COL_6 = "SYNC";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT," +
"DATE TEXT,USERNAME TEXT,LATITUDE TEXT,LONGITUDE TEXT,SYNC TEXT )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String dates,String username,String latitude,String longitude) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,dates);
contentValues.put(COL_3,username);
contentValues.put(COL_4,latitude);
contentValues.put(COL_5,longitude);
contentValues.put(COL_6,"0");
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1) {
return false;
}
else{
return true;
}
}
public boolean insertDataSuccess(String dates,String username,String latitude,String longitude) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,dates);
contentValues.put(COL_3,username);
contentValues.put(COL_4,latitude);
contentValues.put(COL_5,longitude);
contentValues.put(COL_6,"1");
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1) {
return false;
}
else{
return true;
}
}
public Cursor getData(String username) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_3,username);
Cursor res = db.rawQuery("select * from "+TABLE_NAME+" where USERNAME= ? ",new String[] { username });
return res;
}
public Cursor getDataforsync(String id) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_3,id);
contentValues.put(COL_6,"0");
Cursor res = db.rawQuery("select * from "+TABLE_NAME+" where ID= ? and SYNC = ?",new String[] { id,"0" });
return res;
}
public Cursor getDatasync(String username) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_3,username);
contentValues.put(COL_6,"0");
Cursor res = db.rawQuery("select * from "+TABLE_NAME+" where USERNAME= ? and SYNC = ?",new String[] { username,"0" });
return res;
}
public boolean deleteData(String id){
SQLiteDatabase db =this.getWritableDatabase();
long rows = db.delete(TABLE_NAME, "ID = ?", new String[] { String.valueOf(id) });
db.close();
if(rows == -1) {
return false;
}
else{
return true;
}
}
public boolean deleteDataSync(String id){
SQLiteDatabase db =this.getWritableDatabase();
long rows = db.delete(TABLE_NAME, "ID = ?", new String[] { id });
db.close();
if(rows == -1) {
return false;
}
else{
return true;
}
}
public boolean updateDatasync(String id){
SQLiteDatabase db =this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_6,"1");
long result = db.update(TABLE_NAME,contentValues,"ID=" + id,null);
if(result == -1) {
return false;
}
else{
return true;
}
}
}

Increment a counter in database SQLite

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

Categories

Resources