EDIT <<<<<<<<<
I have discovered that the userName retrieved from below is coming back as null. Anyone tell me why?
public void getUserName() {
getUserNameDialog = new Dialog(MasterMindGameActivity.this);
getUserNameDialog.setContentView(R.layout.retrieveusername);
getUserNameDialog.setTitle("Enter your Name");
getUserNameDialog.setCancelable(false);
TextView viewScore = (TextView) getUserNameDialog
.findViewById(R.id.showScore);
viewScore.setText("Your score was " + numberOfGuesses);
final EditText enterName = (EditText) getUserNameDialog
.findViewById(R.id.userName);
btnConfirm = (Button) getUserNameDialog
.findViewById(R.id.confirmUserName);
btnConfirm.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
userName = enterName.getText().toString();
getUserNameDialog.cancel();
}
});
getUserNameDialog.show();
}
displays something like
Highscore
1: null - [correct score]
Where [correct score] is the output it should have
Why is the userName not being saved and instead repalced with null?
EDIT 1: FIXED THE DOUBLE SAVE PROBLEM - NOW JUST THE NULL VALUE
You have two insert statements, that is why it is storing twice.
db.insert(HIGHSCORE_TABLE, null, value);
long dbcheck = db.insert(HIGHSCORE_TABLE, null, value);
Why username is null, you didn't assign getUserName() to userName (see my code below). Safe side I would put System.out right before inserting the data and make sure userName is really getting there.
public void saveHighscore() {
scoreSaved = true;
userName=getUserName();
DatabaseOpenHelper database = new DatabaseOpenHelper(this);
database.addHighscore(userName, numberOfGuesses);
database.close();
}
Related
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
I am getting a problem in android textview.
I am simply setting text on the android textview like below
pAmount.setText("Rs." + receiptAmount + "/-");
but is showing null in the text
System.out.println("receiptAmount ====>"+ receiptAmount );
I had tried to print the value of receiptAmount to check whether, the value is null or not.
But, It is showing the right value in the log.
What is the issue does any body have any idea.
similarly , other texview are showing the null value in the same activity.
TextView pAmount= (TextView) findViewById(R.id.amount);
1.Call the set text After Declaring the above line in Oncreate.
2.get the Proper data in receiptAmount. Your Problem Solved
pAmount.setText("Rs." + receiptAmount + "/-");
public void FeeGetFeeTypes(String studentId, String fee_slotid) {
// TODO Auto-generated method stub
ArrayList<String> arrayList_FeeType=new ArrayList<String>();
ArrayList<String> arrayList_FeeTypeAmount=new ArrayList<String>();
try{
SQLiteDatabase db = this.getReadableDatabase();
final String MY_QUERY = "select * from feetype where student_id=? and slot_id=?";
Cursor res = db.rawQuery(MY_QUERY, new String[]{ studentId, fee_slotid });
res.moveToFirst();
while (res.isAfterLast() == false){
arrayList_FeeType.add(res.getString(res
.getColumnIndex(FEE_TYPE_COLUMN_FEETYPE)));
arrayList_FeeTypeAmount.add(res.getString(res
.getColumnIndex(FEE_TYPE_COLUMN_FEETYPEAMOUNT)));
}
if(arrayList_FeeType.size()>0){
PrintActivity.sendFeeType(arrayList_FeeType, arrayList_FeeTypeAmount);
}
}
catch(Exception e){
e.printStackTrace();
}
}
This is the code that is resulting the null values. When the data is large, I get out of memory exception
I have a edit tab in my app where the user can edit his details given during the time of registration .Inside the edit activity i have a save button which when clicked it saves the
data or update the datas into the database.
CODE
public void onSave(View btn)
{
EditText edtName = (EditText) findViewById(R.id.edtNameED);
EditText edtPass = (EditText) findViewById(R.id.edtPassED);
EditText edtEmail = (EditText) findViewById(R.id.edtEmailED);
EditText edtPh = (EditText) findViewById(R.id.edtPhED);
int id=0;
String where = DataBase_Server.C_ID+"=?";
String[] whereArgs = {id+""};
DataBase_Server database=new DataBase_Server(Edit.this);
SQLiteDatabase db=database.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DataBase_Server.MOBILE_NO, edtPh.getText().toString());
values.put(DataBase_Server.PASS, edtPass.getText().toString());
values.put(DataBase_Server.EMAIL, edtEmail.getText().toString());
for(int i=0;i<edtName.length();i++)
{
id+=(int)edtName.getText().toString().charAt(i);
}
Toast.makeText(this,id+" hello", Toast.LENGTH_LONG).show();
try
{
db.update(DataBase_Server.TABLE, values,where,whereArgs);
}catch(Exception e){}
Toast.makeText(this,"UPDATE SUCESSFULL !!", Toast.LENGTH_LONG).show();
db.close();
database.close();
}
The code is giving not a single error but it is not even updating anything in the database. The database is not changed at all even after the user edit his details.
You are adding up the values of all the characters in the name:
for(int i=0;i<edtName.length();i++)
id+=(int)edtName.getText().toString().charAt(i);
This is unlikely to be your real ID value. With no record matching the WHERE condition, the update will do nothing, silently.
You must remember the ID value from when you loaded the data, because the name may have changed.
When I click on a ListItem, it opens up a custom dialog with 4 EditText fields. The fields are set with current data depending on the row that is clicked. The purpose of the dialog is to allow the user to update the data (it is a financial app). I am having trouble actually applying the update when the user clicks "submit" in the dialog. There are no errors in the app when I run. Here is the onclick method:
protected void onListItemClick(ListView l, View v, int position, long id) {
List<Debt> values = datasource.getAllDebt();
Debt item = values.get(position);
final long boxId = item.getId();
// final String BoxId = String.valueOf(boxId);
final String BoxName = item.getName();
final String BoxBalance = item.getBalance();
final String BoxApr = item.getApr();
final String BoxPayment = item.getPayment();
// set up dialog
final Dialog dialog = new Dialog(manageDebts.this);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Edit Debt Details");
dialog.setCancelable(true);
// set up text
EditText et1 = (EditText) dialog.findViewById(R.id.editText1);
EditText et2 = (EditText) dialog.findViewById(R.id.editText2);
EditText et3 = (EditText) dialog.findViewById(R.id.editText3);
EditText et4 = (EditText) dialog.findViewById(R.id.editText4);
et1.setText(BoxName);
et2.setText(BoxBalance);
et3.setText(BoxApr);
et4.setText(BoxPayment);
// set up button
Button button = (Button) dialog.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
datasource.updateDebt(boxId, BoxName, BoxBalance, BoxApr,
BoxPayment);
dialog.dismiss();
}
});
dialog.show();
}
The Update Method in my Database helper class is shown here:
public boolean updateDebt(long updateId, String debt_name, String debt_total, String apr, String payment)
{
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_ID, updateId);
values.put(MySQLiteHelper.COLUMN_DEBT_NAME, debt_name);
values.put(MySQLiteHelper.COLUMN_DEBT_TOTAL, debt_total);
values.put(MySQLiteHelper.COLUMN_APR, apr);
values.put(MySQLiteHelper.COLUMN_PAYMENT, payment);
return database.update(MySQLiteHelper.TABLE_DEBT, values, MySQLiteHelper.COLUMN_ID + " = " + updateId, null) > 0;
}
I have verified that the COLUMN_ID and the updateId are pointing to the correct rows in the ListView and the SQL database.
Does someone see something I am not?
Perhaps you are violating a constraint with your update? Just a guess without seeing the DB code.
EDIT
Lose the single quotes around the row id variable, that is making the DB treat it as a string, and a string compared to a number is a fail.
This will work better:
String whereClause = MySQLiteHelper.COLUMN_ID + " = ?";
String[] whereArgs = new String[]{ String.valueOf(updateId) };
return database.update(MySQLiteHelper.TABLE_DEBT,
values, whereClause, whereArgs) > 0;
The String.valueOf() call simply converts the ID to a String value.
I test your code in my computer.
The update method works fine.
So I think you should post more code .
or You should check your logic.
I was missing a step between 2 and 3.
Setting the variable again, inside the onClick method. Once the user pressed the update button, the variable had to be RE-SET to the new value of the EditText field. Like this (simplified version):
String name = null;
EditText et;
name = debt.getName();
et.setText(name);
onclick {
***name = et.getText().toString();***
datasource.updateDebt(name);
}
I have a database with some records in and i have the code i wish to execute on each row but I'm having trouble creating a suitable loop, ive been trying while(movetonext) but it hasnt been working.
cursor = getAppts();
cursor.moveToNext();
String titlefromdb = cursor.getString(3);
if (strTitle.equals(titlefromdb) && cursor.getString(1).equals(dateselforap))
{
// matching code update box
final Dialog matchdiag = new Dialog(CW2Organisor.this);
matchdiag.setContentView(R.layout.apptmatch);
matchdiag.setTitle("View/Edit Appointment");
matchdiag.setCancelable(true);
TextView matchtxt = (TextView) matchdiag.findViewById(R.id.matchtxt);
matchtxt.setText("Appointment \"" + titlefromdb + "\" already exists, please choose a different event title");
Button btnmatchok = (Button) matchdiag.findViewById(R.id.btnmatch);
btnmatchok.setOnClickListener(new OnClickListener() {
// on click for cancel button
#Override
public void onClick(View v) {
matchdiag.dismiss();
}
});
matchdiag.show();
}
else
{
addAppt(strTime, strTitle, strDet);
dialog.dismiss();
}
What I would need is for each row of my database i would need the titlefromdb to hold the title field of the current row and the for the if statement to run and then move to the next row.
You could try
cursor.moveToFirst();
loop with some sort of check
cursor.moveToNext();
end loop
... and I would also try to qualify your "it's not working" statement. What's not working?