I have an Alarm Manager for update database"s values.When user starts to alarm,My broadcastReceiver is activeted.There is another alarm in my BroadcastReceiver that İt always active when first alarm launch that It works only once.My BroadcastReceiver works but It doesn"t do what I say.My purpose is:Updating UI with colors.I have 3 if loops to updating my database.My problem is I update my database but When Updated my database,Third one loop doesn"t work.I am working with Toast for understanding . How can I fix it?
First one works good:
if( !listDataBoya.contains("#1eac02")){
Toast.makeText(context, "Alarm !!!!!!!!!!1111111111", Toast.LENGTH_LONG).show();
String table = "people_table";
ContentValues productDetailsContentValues = new ContentValues();
productDetailsContentValues.put("boya", "#1eac02");
String where = " id = " + listDataId.get(secilmissayı);
mDatabaseHelper.update(table, productDetailsContentValues, where , null);
setalarm(context);
}
Second one works good:
if (listDataBoya.get(secilmissayı) != "#1eac02" ){
String table = "people_table";
ContentValues productDetailsContentValues = new ContentValues();
productDetailsContentValues.put("boya", "#1eac02");
String where = " id = " + listDataId.get(secilmissayı);
mDatabaseHelper.update(table, productDetailsContentValues, where , null);
Toast.makeText(context, "Alarm !!!!!!!!!!22222222"+ listDataBoya.get(secilmissayı), Toast.LENGTH_LONG).show();
setalarm(context);
}
Third one It doesn"t work: (I can"t see my Toast.)
if (listDataBoya.get(secilmissayı) == "#1eac02" ){
Toast.makeText(context, "Alarm !!!!!!!!!!333333333", Toast.LENGTH_LONG).show();
String table = "people_table";
ContentValues productDetailsContentValues = new ContentValues();
productDetailsContentValues.put("boya", "#1eac02");
String where = " id = " + listDataId.get(secilmissayı);
mDatabaseHelper.update(table, productDetailsContentValues, where , null);
setalarm(context);}
Your third example isn't firing because you're comparing string objects with == instead you should use an equals method that will return true if the argument is a string object that represents the same sequence of characters as the string object you're comparing. Similarly you should change your other examples accordingly.
if(listDataBoya.get(secilmissayı).equals("#1eac02")){
...
}
Related
I created a database with a table named flagTable, this table only has two fields, which are id(auto increment) and an integer field. Next, in my program, I have a button that will trigger a thread to start. When the thread is starting, it constantly retrieve data from database, and check for the for the value, if the value is equal to one then it will trigger another new Thread, something like this:
private class statusOfStrummingInAnotherDevice extends Thread {
int value;
public void run() {
try{
while(true){
try{
if(flagCursor == null){
flagCursor = cdb1.getFlagAll();
}
}catch(Exception e){break;}
try{
Log.i("MAIN3ACTIVITY","getting status");
int size = cdb1.getSize(flagCursor);
Log.i("MAIN3ACTIVITY","SIZE is" + String.valueOf(xyz));
for(int i = 0 ; i < size ; i++){
flagCursor.moveToPosition(i);
Log.i("MAIN3ACTIVITY","getting status jkasdfasdf");
value = cdb1.getFlag();
if(value == 1){
Log.i("FLAGCURSOR=====>>>>","Succesful");
releasingNotes = new ReleasingNotes(IntendedChord);
releasingNotes.start();
//break;
}
cdb1.updateFlag(0);
Log.i("FLAGCURSOR=====>>>>",String.valueOf(value));
}
flagCursor = null;
}catch(Exception e){break;}
Log.i("MAIN3ACTIVITY","thread is sleeping");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
}catch(Exception e){
}
}
}
In the meantime, the data that were retrieved from the database is using this function:
public Cursor getFlagAll(){
return getReadableDatabase().rawQuery(
"SELECT _ID, flag from flagTable", null);
}
And, the data that were updated to the database through this method:
public int updateFlag(int i) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("flag",i);
return db.update("flagTable" , contentValues , "_ID" + "= ?",new String[]{String.valueOf(1)});
}
Now, above codes will give no error, however, the data that were retrieved from the database is always 1, it keeps trigger a new function. In my above codes, I stated if the value is equal to 1, then the current thread will trigger a new thread to start, When its finished, the program will update the current data to 0. So that, the next round of the infinite loop can stop triggering new thread until a the conditon is met. What is problem overhere? did my codes really updated the new value? or I need to referesh the database every time I updated a new value.
Use Listeners to your database.
use SQLiteTransactionListener and do your things in onCommit()
Some guide in details here :
https://developer.android.com/reference/android/database/sqlite/SQLiteTransactionListener.html and
http://www.programcreek.com/java-api-examples/index.php?api=android.database.sqlite.SQLiteTransactionListener
I am trying to prove that my current code stops prevents sql injection. At the same time I am trying to learn to write a rawQuery that uses ? for a place holder.
My Table is as follows below
public static final String TABLE_NAME = "masterPW";
public static final String Col_ID = "ID";
public static final String Col_MPW = "mpw";
When the MainActivity starts it checks to see if the Col_MPW has data or not by calling the onLoad method that goes to DBHelper Class code below
private void onLoad(){
dbHelper = new DBHelper( this );
str = dbHelper.getCol_MPW();
// Line of code above calls getCol_MPW method in DBHelper
// And DBHwlper RETURNS str Variable with the Master Password
//============================================================
if (str == null || str.isEmpty()) {
etPW.requestFocus();
btnSave.setVisibility( View.VISIBLE );
System.out.println( "I am NULL" );
} else {
setTitle( "Enter Password "+str );
tvCPW.setVisibility( View.INVISIBLE );
etCPW.setVisibility( View.INVISIBLE );
btnSave.setVisibility( View.INVISIBLE );
btnEnter.setVisibility( View.VISIBLE );
System.out.println( "Im NOT NULL "+str );
}
}
Ok so now we will say the password has been created and when the user enters the password to go to the next activity we call the onLoad grab the value in the TABLE and return it to the MainActivity and preform validation
the code below is in the DBHelper and returns a string for validation
public String getCol_MPW(){
String str = null;
db = getReadableDatabase();
String q = "SELECT mpw FROM masterPW";
//String q = "SELECT * FROM masterPW";
//String ov = etPW.getText().toString();
//Cursor cursor = db.rawQuery("SELECT mpw "+"FROM masterPW"+"WHERE mpw = ? ",new String[]{ov};
// The line of CODE above fails even when I replase ov with the PASSWORD
//=================================================================
Cursor cursor = db.rawQuery(q,null);
if(cursor.moveToFirst()){
str = cursor.getString(cursor.getColumnIndex(Col_MPW));
}
cursor.close();
db.close();
return str;
}
The str that is returnd to the MainActivity is then validated with this code
public void onEnter(View view) {
// Will use REGEX here so matches is ok
// But with NO REGEX -> MUST <- use equals
//if (str.matches( etPW.getText().toString().trim() )) {
if(str.equals(etPW.getText().toString().trim())){
etPW.setText( "" );
str = "";
Intent intent = new Intent( MainActivity.this, PageTwo.class );
startActivity( intent );
} else {
Toast.makeText( MainActivity.this, "Incorrect Password", Toast.LENGTH_LONG ).show();
etPW.requestFocus();
}
}
My Code in DBHelper public String getCol_MPW() has some of my non productive attempts at NON sql injection code commented out. That said I have also tried various sql injection techniques to get past my validation none would work.
So I would still like to have some guidance on how to implement better rawQuery methods to prevent sql injection? After the password I need to add other data to the database. I have looked at prepared statements and binding but if I can not implement this with a table that has only one row ever I see no point in going further
New to android, I'm currently trying to send a String value from one Activity to another. I have looked through several threads like How to use putExtra() and getExtra() for string data for an answer, but I cannot get it to work.
The string I want to send is:
public void golf(View view) {
Intent intent = new Intent(SearchSport.this, EventList.class);
intent.putExtra("type", "golf");
startActivity(intent);
and my receiver looks like
String type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_list);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if ( extras != null)
type = extras.getString("type");
if (type == "golf"){
TextView eventName = (TextView) findViewById(R.id.EOName);
TextView eventTime = (TextView) findViewById(R.id.EOTime);
TextView eventLocation = (TextView) findViewById(R.id.EOLocation);
DatabaseOperations dop = new DatabaseOperations(ctx);
Cursor CR = dop.getInformation(1);
CR.moveToFirst();
eventName.setText(CR.getString(1));
eventTime.setText(CR.getString(7) + " " + CR.getString(8) + ". " + CR.getString(9) + " kl. " + CR.getString(10) + ":" + CR.getString(11));
eventLocation.setText(CR.getString(4));}
else {Toast toast = Toast.makeText(this, "Error in Type.", Toast.LENGTH_LONG);
toast.show();}
I have no Idea what's wrong here. The app displays the toast everytime I test it, instead of filling out the TextViews with the data from my database entry.
EDIT: Code has been changed based on answers, but the problem has not yet been solved. Writing if (type.equals("golf")){} instead of if (type == "golf"){} crashed the app.
EDIT 2: Problem solved! Fixed case sensitivity, used .equals instead of ==, and wrote the receiver as
if(getIntent().hasExtra("Type"))
type = getIntent().getStringExtra("Type");
In the end, it turns out is was the virtual device I used which crashed the app, for as of yet unknown reasons. When tested on an actual android phone, the app works as intented.
Thanks to everyone for their help!
try this
if(getIntent().hasExtra("Type"))
type = getIntent().getStringExtra("Type");
Change the key it is case sensitive :
type = extras.getString("Type");
Key is wrong when try to get String from Intent Extra :
type = extras.getString("type");
Replace with :
type = extras.getString("Type");
Note : Also use equals() instead == for comparing String
if (type.equals("golf")){
1) First keys are case sensitive
2) pass as
Bundle bundle = new Bundle()
bundle.putString("type","golf");
intent.putExtras(bundle);
after that get it using
Bundle received = i.getExtras();
received.getString("type");
As you are passing the value using Extra. You must have to catch that using getStringExtra(); and the Key must be case sensitive.
Intent i = getIntent();
type = i.getStringExtra("Type");
I've an app that is used by carers to sign in to the system using their android phones. They scan a QRcode or swipe an NFC tag to get the client's information, scan time and location. The latter info constitutes a transaction. The transaction is placed in the phone's DB as well as submitted to a server via HTTP.
All works well as all transactions are put in DB and posted to web service until i have to make two transactions at the same time. A transaction is made by calling AsyncTask as it's a network call and so not to block UI thread. Both transactions are made to the web service but not all the data is sent to DB. I've commented out some code and made one Async post at a time and the data is then sent fine.
The problem
When one AsyncTask is running the other starts. When this happens the first AsyncTask doesn't work correctly. I have found the following thread where there is a similar problem and using a SerialExecutor seems to be the answer.
serialexecutor
https://stackoverflow.com/questions/6645203/android-asynctask-avoid-multiple-instances-running
Could anyone help me implement the 2 following AsyncTasks in a SerialExecutor, I'm fairly new to Android and i'm struggling to start this off. I'd like apd to execute and finish then apd3 to execute after. All in a serial fashion.
Thanks in advance Matt
String temp_tagType = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_TYPE));
String temp_tagCompId = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_COMPANY_ID));
String temp_PersonId = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_PERSON_ID));
String temp_tagName = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_NAME));
String temp_tagId = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_TAG_ID));
String temp_tagScanTime = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_TAG_SCAN_TIME));
String temp_tagLatitude = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_TRANSACTIONS_LATITUDE));
String temp_tagLongitude = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_TRANSACTIONS_LONGITUDE));
if(temp_tagId == null){
temp_tagId = "notag";
}
String manualM = "M";
Log.e(TAG, " temp name and status = " + temp_tagName + " " + manualM);
////////insert the temp variables with the status set to M
ContentValues values = new ContentValues();
values.putNull(LoginValidate.C_ID);
values.put(LoginValidate.C_TYPE, temp_tagType);
values.put(LoginValidate.C_COMPANY_ID, nfcscannerapplication.getCompId());
values.put(LoginValidate.C_PERSON_ID, temp_PersonId);
values.put(LoginValidate.C_NAME, temp_tagName);
values.put(LoginValidate.C_TAG_ID, temp_tagId);
values.put(LoginValidate.C_STATUS, manualM);
values.put(LoginValidate.C_TAG_SCAN_TIME, manualLogoutTime);
values.put(LoginValidate.C_TRANSACTIONS_LATITUDE, temp_tagLatitude);
values.put(LoginValidate.C_TRANSACTIONS_LONGITUDE, temp_tagLongitude);
DateTime now = new DateTime();
DateTimeFormatter df = DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss.SSS");
String formattedNowTime = df.print(now);
Log.e(TAG, "formattedNowTime = " + formattedNowTime);
DateTimeFormatter df2 = DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss.SSS");
String manualTime = df2.print(timeSetOnSpinner);
Log.e(TAG, "about to put " + temp_tagName + " into DB");
nfcscannerapplication.loginValidate.insertIntoTransactions(values);
String[] params = new String[]{nfcscannerapplication.getCompId(), temp_tagId, temp_PersonId, nfcscannerapplication.getCarerID(),
manualTime, formattedNowTime, manualM, getDeviceName(), temp_tagLatitude, temp_tagLongitude};
AsyncPostData apd = new AsyncPostData();
apd.execute(params);
///////////////now carry on as usual with the last actual tag that has been scanned
Log.e(TAG, "about to insert the current record after inserting the manual logout");
if(tagId == null){
tagId = _tagId;
}
ContentValues values3 = new ContentValues();
values3.putNull(LoginValidate.C_ID);
values3.put(LoginValidate.C_TYPE, tagType);
values3.put(LoginValidate.C_COMPANY_ID, nfcscannerapplication.getCompId());
values3.put(LoginValidate.C_PERSON_ID, tagPerson);
values3.put(LoginValidate.C_NAME, tagUserName);
values3.put(LoginValidate.C_TAG_ID, tagId);
values3.put(LoginValidate.C_STATUS, IN);
values3.put(LoginValidate.C_TAG_SCAN_TIME, tagScanTime.getMillis());
values3.put(LoginValidate.C_TRANSACTIONS_LATITUDE, tagLatitude);
values3.put(LoginValidate.C_TRANSACTIONS_LONGITUDE, tagLongitude);
// make the current transaction out
DateTime now3 = new DateTime();
DateTimeFormatter df3 = DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss.SSS");
String formattedNowTime3 = df3.print(now3);
Log.e(TAG, "formattedNowTime = " + formattedNowTime3);
String formattedTagScanTime3 = df3.print(tagScanTime);
Log.e(TAG, "about to put " + tagUserName + " into DB");
nfcscannerapplication.loginValidate.insertIntoTransactions(values3);
String[] params3 = new String[]{nfcscannerapplication.getCompId(), tagId, tagPerson, nfcscannerapplication.getCarerID(),
formattedTagScanTime3, formattedNowTime, IN, getDeviceName(), tagLatitude, tagLongitude};
AsyncPostData apd3 = new AsyncPostData();
apd3.execute(params3);
.
I want to save weekdays in database, so i thought to store it by assigning int value to each day. i.e
1 -> Selected, 0 -> Not Selected.
Monday = 0/1
Tuesday = 0/1
.
.
.
.
.
Sunday = 0/1.
But this will make 7 columns in DB. So I was thinking if anyone can help me with this if I should store it in a single array and retrieve the values for further use. I was reading some examples over internet but didn't get it in a easy way.
To insert 7 values in one column you can use comma separator like this
where Total_Score_P1 is an string array
//string array
String[] Total_Score = new String[] { p1e1,p1e2,p1e3,p1e4,p1e5,p1e6 };
// Convderting it into a single string
String result_ScoreP1 = ("" + Arrays.asList(Total_Score_P1)).
replaceAll("(^.|.$)", " ").replace(", ", " , " );
result_ScoreP1 will be
// output of this
result_ScoreP1 = "p1e1,p1e2,p1e3,p1e4,p1e5,p1e6";
insert it as a single string in database and
when retrieve it in again break in parts like
// a string array list
// query fired
public ArrayList<String> rulTable(String id) {
// TODO Auto-generated method stub
ArrayList<String> Ruleob = new ArrayList<String>();
Cursor c_rule;
try
{
c_rule = db.query(NameTable, new String[]{
columns1
},
Rule_COurseID + "=" + id ,
null, null,
null, null, null);
c_rule.moveToFirst();
// if there is data available after the cursor's pointer, add
// it to the ArrayList that will be returned by the method.
if (!c_rule.isAfterLast())
{
do
{
Ruleob.add(c_rule.getString(0));
}
while (c_rule.moveToNext());
}
// let java know that you are through with the cursor.
c_rule.close();
}
catch(Exception e)
{
}
return Ruleob;
}
//list to get elements
ArrayList<String> ListOne = new ArrayList<String>();
ArrayList<String> row ;
try{
// received values
row = db.TheTable(id);
String r1 = row .get(0);
}
catch(Exception e)
{
}
StringTokenizer st2 = new StringTokenizer(r1, "||");
while(st2.hasMoreTokens()) {
String Desc = st2.nextToken();
System.out.println(Desc+ "\t" );
ListOne.add(Desc);
//
}
You can use a binary integer 1= selected 0 =Not Selected (1111111) (0000000)
total seven days so index 0=mon, 1=tues, 2=wed, 3=thurs, 4=friday, 5=sat, 6=sunday..and so on..
here 1111111 means all day selected, 0000000 all day not selected, 0001000 only thursday is selected.
I have also discovered a way i.e. convert your so called values to a JSON Array and then store the complete JSON String to an entity/field in Database.
It helps in serving the values easily and effectivly.
Create another table with a column for each day, boolean value. Make an association to this table by integer id (use a foreign key) This is the relational way of solving the problem.