This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
Can anyone see any errors in this code? I've checked to make sure the data has been written to the database. Every time I click the button it gives me the "Incorrect Password" text. It's probably something stupid that I'm overlooking. Any help is appreciated.
public void buttonWork() {
button_credCheck.setOnClickListener(new View.OnClickListener() {
String rpq = regPwdQuery().toString();
String passInputStr = editText_pwdInput.getText().toString();
#Override
public void onClick(View v) {
if (passInputStr == rpq) {
Intent myIntent = new Intent(LogInActivity.this, FindInfoActivity.class);
startActivity(myIntent);
} else {
Toast.makeText(LogInActivity.this, "Incorrect Password", Toast.LENGTH_LONG).show();
}
}
});
}
EDIT:
This is not a duplicate of the referenced question because changing == to equals() did not fix my problem.
EDIT 2:
Thought maybe I should Include the cursor class for regPwdQuery
public Cursor regPwdQuery() {
String regPwdData = editText_pwdInput.getText().toString();
String regQuery = "SELECT * FROM UsrPass_table WHERE Pwrd ='" + regPwdData + "'";
SQLiteDatabase uDB = usrDB.getReadableDatabase();
Cursor result = uDB.rawQuery(regQuery, null);
return result;
The == operator is used when we have to compare the String object references. If two String variables point to the same object in memory, the comparison returns true.
The equals method is used when we need to compare the content of the text present in the String objects. This method returns true when two String objects hold the same content (i.e. the same values).
To compare two strings for equality, use equals( ).
public void buttonWork() {
button_credCheck.setOnClickListener(new View.OnClickListener() {
String rpq = regPwdQuery().toString();
String passInputStr = editText_pwdInput.getText().toString();
#Override
public void onClick(View v) {
if (passInputStr.equals(rpq))
Intent myIntent = new Intent(LogInActivity.this, FindInfoActivity.class);
startActivity(myIntent);
} else {
Toast.makeText(LogInActivity.this, "Incorrect Password", Toast.LENGTH_LONG).show();
}
}
});
}
your comparisons checks the refferences instead the actual content of the strings. Instead use .equals() to check the value of the String.
if (passInputStr == rpq)
Should be changed to:
if(passInputStr.equals(rpq))
EDIT:
you toString the result you get from the query:
String rpq = regPwdQuery().toString();
if your result only contains the password it might work, but otherwise I don't think it will give the correct result.
Since I don't know how the table UsrPass_table looks like I can only guess but I think something like this has to be implemented:
public String regPwdQuery() {
String regPwdData = editText_pwdInput.getText().toString();
String regQuery = "SELECT * FROM UsrPass_table WHERE Pwrd ='" + regPwdData + "'";
SQLiteDatabase uDB = usrDB.getReadableDatabase();
Cursor result = uDB.rawQuery(regQuery, null);
String password = "";
while(result.moveToNext()){
password = result.getString(0); //Parameter should match the column from where you get your data, normally 0 is an ID.
}
return password;
Hope it helps.
That essentially means passInputStr != rpq , You could try the .equalsIgnoreCase() method or the .equals() method. That is because you are comparing strings! You can read more about this here
You can not compare Strings in java with == operator. Use equals() method instead:
if (passInputStr.equals(rpq))
Try the
if (passInputStr.equals(rpq))
reference:
What is the difference between == vs equals() in Java?
Here is an example (you can run it):
public final class MyEqualityTest
{
public static void main( String args[] )
{
String s1 = new String( "Test" );
String s2 = new String( "Test" );
System.out.println( "\n1 - PRIMITIVES ");
System.out.println( s1 == s2 ); // false
System.out.println( s1.equals( s2 )); // true
A a1 = new A();
A a2 = new A();
System.out.println( "\n2 - OBJECT TYPES / STATIC VARIABLE" );
System.out.println( a1 == a2 ); // false
System.out.println( a1.s == a2.s ); // true
System.out.println( a1.s.equals( a2.s ) ); // true
B b1 = new B();
B b2 = new B();
System.out.println( "\n3 - OBJECT TYPES / NON-STATIC VARIABLE" );
System.out.println( b1 == b2 ); // false
System.out.println( b1.getS() == b2.getS() ); // false
System.out.println( b1.getS().equals( b2.getS() ) ); // true
}
}
final class A
{
// static
public static String s;
A()
{
this.s = new String( "aTest" );
}
}
final class B
{
private String s;
B()
{
this.s = new String( "aTest" );
}
public String getS()
{
return s;
}
}
public void buttonWork() {
button_credCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String rpq = regPwdQuery().toString();
String passInputStr = editText_pwdInput.getText().toString();
if (passInputStr == rpq) {
Intent myIntent = new Intent(LogInActivity.this, FindInfoActivity.class);
startActivity(myIntent);
} else {
Toast.makeText(LogInActivity.this, "Incorrect Password", Toast.LENGTH_LONG).show();
}
}
});
}
Try this.. Put rpq and passInputStr in onClick method. also change if condition if (passInputStr.equals(rpq))
Simply, replace:
if (passInputStr == rpq)
with
if (passInputStr.equals(rpq))
Use string.equals(anotherString) method when you want to compare between two different strings.
Edit:
public String regPwdQuery() {
String regPwdData = editText_pwdInput.getText().toString();
String regQuery = "SELECT * FROM UsrPass_table WHERE Pwrd ='" + regPwdData + "'";
SQLiteDatabase uDB = usrDB.getReadableDatabase();
Cursor cursor = uDB.rawQuery(regQuery, null);
//Modify this
String result = cursor.getString(cursor.getColumnIndex("password"));
return result;
Related
I am trying to add multiple values to an array, but it returns a cannot resolve error. Is there any way or work-around here?
for (Map.Entry<String,String> entry : hash.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if(typePHP.equals("TARGET")) {
message += key + " " + value + "t\n";
}else {
message += key + " " + value + "r\n";
}
array.add(Integer.parseInt(key),value,typePHP,gamePHP);
//Heres the error.
}
Here's the error:Cannot resolve method 'add(int, java.lang.String, java.lang.String, java.lang.String)'
I need the single element to store 4 values at once and have an output like {109,40, TYPE, GAME};
First, ensure that your ArrayList is currently storing an object with a constructor of (String a, String b, String c). When you call array.add(new Item(a, b, c), Java needs to match that to an existing method.
public class Item {
public Item(String a, String b, String c) {
// initialize your object's variables here in the constructor
}
}
Then, you have to use new when you're creating a new object using add().
array.add(new Item(a, b, c));
See this from Java: Adding new objects to an ArrayList using a constructor
And this reference from Oracle about constructors: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
use addAll in this way:
array.addAll(Arrays.asList( key,value,typePHP,gamePHP) );
UPDATE:
You need a 2d array, based on this sentence I need the single element to store 4 values at once and have an output like {109,40, TYPE, GAME};
So, try this:
ArrayList<ArrayList<String>> array2d = new ArrayList<>();
array2d.add(new ArrayList<String>() {{
add("109");
add("40");
add("TYPE");
add("GAME");
}});
In your case, there should be something like this:
ArrayList<ArrayList<String>> array2d = new ArrayList<>();
for (Map.Entry<String,String> entry : hash.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if(typePHP.equals("TARGET")) {
message += key + " " + value + "t\n";
}else {
message += key + " " + value + "r\n";
}
array2d.add(new ArrayList<String>() {{
add(key);
add(value);
add(typePHP);
add(gamePHP);
}});
}
You can create Custom object of your choice member
public class Item {
private int key;
private String value;
private String typePHP;
private String gamePHP;
public Item(int key, String value, String typePHP, String gamePHP) {
this.key = key;
this.value = value;
this.typePHP = typePHP;
this.gamePHP = gamePHP;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getTypePHP() {
return typePHP;
}
public void setTypePHP(String typePHP) {
this.typePHP = typePHP;
}
public String getGamePHP() {
return gamePHP;
}
public void setGamePHP(String gamePHP) {
this.gamePHP = gamePHP;
}
}
Now you can use like
ArrayList<Item> itemArray = new ArrayList <>();
for (Map.Entry<String,String> entry : hash.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if(typePHP.equals("TARGET")) {
message += key + " " + value + "t\n";
}else {
message += key + " " + value + "r\n";
}
itemArray.add(new Item(Integer.parseInt(key),value,typePHP,gamePHP));
}
By using assets folder, we are reading data i.e,address details based on search keyword:
Here is my code
private SQLiteDatabase db;
private Cursor c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_search = (EditText) findViewById(R.id.et_search);
img = (ImageView) findViewById(R.id.img_search);
list = (ListView) findViewById(R.id.list_search);
db = openOrCreateDatabase("sample", Context.MODE_PRIVATE, null);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
search_keyword = et_search.getText().toString();
arr_data = new ArrayList<ListItems>();
if (isValid()) {
SELECT_SQL = "SELECT ROWID AS _id,* FROM Addresses where Type LIKE '%" + search_keyword + "%'";
Log.d("daatt",SELECT_SQL);
try {
c = db.rawQuery(SELECT_SQL, null);
c.moveToFirst();
showRecords();
} catch (SQLiteException e) {
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
}
}
}
});
}
private void showRecords() {
String ugName = c.getString(c.getColumnIndex("Name"));
String ugaddress = c.getString(c.getColumnIndex("Address"));
String ugtype = c.getString(c.getColumnIndex("Type"));
ListItems items = new ListItems();
// Finish reading one raw, now we have to pass them to the POJO
items.setName(ugName);
items.setAddress(ugaddress);
items.setType(ugtype);
// Lets pass that POJO to our ArrayList which contains undergraduates as type
arr_data.add(items);
}
ListDataAdapter adapter = new ListDataAdapter(arr_data);
list.setAdapter(adapter);
if (c != null && !c.isClosed()) {
int count = c.getCount();
c.close();
}
Log.d("ListData", "" + arr_data);
}
private boolean isValid() {
if (search_keyword.length() == 0) {
Toast.makeText(getApplicationContext(), "please enter valid key word", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
For 1st build we got successful data loaded using list adapter
But after clean project, & Rebuild project showing a no such table expection
Please guide us wr we r going wrong
Advance Thanks
As far as I can see from your print, the table you're referring to is called ListOfAddress, ain't it? your SQL is:
SELECT_SQL = "SELECT ROWID AS _id,* FROM Addresses where Type LIKE '%" + search_keyword + "%'";
I might be wrong, but I would double check the query.
I have a database where i have Unique id, Email id and Password. Im storing using SQlite database. I've to get the cursor which stores the result of the query, i have got the cloumn index of each cloumn, appended it using StringBuffer, but i dont know how to get those values in the other class? please help.
here is my code for Adapter class:
public String getData(String email,String pwd)
{
StringBuffer buffer=new StringBuffer();
SQLiteDatabase db =sciHelper.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT _id FROM " + SciHelper.TABLE_NAME + " WHERE email=? AND password=?", new String[]{email, pwd});
while(cursor.moveToNext())
{
int index1=cursor.getColumnIndex(SciHelper.UID);
int index2=cursor.getColumnIndex(SciHelper.EMAIL);
int index3=cursor.getColumnIndex(SciHelper.PASSWORD);
String cid=cursor.getString(index1);
String mail=cursor.getString(index2);
String mailpass=cursor.getString(index3);
buffer.append(cid +" "+mail+" "+mailpass+"\n");
}
return buffer.toString();
}
code at login class:
public void checkTable(View view) {
email2 = emaillog.getText().toString();
pass2 = passlog.getText().toString();
String data = sciDataBaseAdapter.getData(email2, pass2);
String[] values=data.split("\\");
String cid=values(0);
if (TextUtils.isEmpty(email2)) {
emaillog.setError("Enter Email Id");
passlog.setError("Enter Password");
}
// if (email1 != null) {
Intent intent=new Intent(this,ResultActivity.class);
startActivity(intent);
Message.message(this, "Login succesful");
} else {
Message.message(this, "Invalid username/ or register");
}
}
}
When calling the ResultAcitvity
Intent intent=new Intent(this,ResultActivity.class);
intent.putExtra("key","value");
startActivity(intent);
and on ResultActivity, inside onCreate() method write
Intent intent=getIntent();
String value=intent.getStringExtra("key");
String[] values = value.split(" ");
String cid=values[0];
String mail=values[1];
String mailpass=values[2];
public void checkTable(View view) {
email2 = emaillog.getText().toString();
pass2 = passlog.getText().toString();
String data = sciDataBaseAdapter.getData(email2, pass2);
String[] values=data.split("\\");
String cid=values(0);
if (TextUtils.isEmpty(email2)) {
emaillog.setError("Enter Email Id");
passlog.setError("Enter Password");
}
// if (email1 != null) {
Bundle bundle=new Bundle();
b.putStringArray(some_key, values);
Intent intent=new Intent(this,ResultActivity.class);
intent.putExtra(bundle);
startActivity(intent);
Message.message(this, "Login succesful");
} else {
Message.message(this, "Invalid username/ or register");
}
}
and in your next activity get that using.
Bundle extras = getIntent().getExtras();
String[] some_variable= extras.getString("some_key");
![This is my code for find method in DBHelper].class[1]
public StringBuilder findData(String find)
{
StringBuilder output = new StringBuilder("Our data is:\n");
Cursor c = ourHelper.getReadableDatabase().rawQuery("SELECT abbrevaition FROM abbrtab WHERE acronym"+" = ? ;", new String[]{find});
String remarks=" ";
int iRemarks = c.getColumnIndex(KEY_ABBR);
if( c.moveToFirst() && c.getCount()>0 )
{
remarks= c.getString(iRemarks);
if(remarks.isEmpty())
{
Toast.makeText(ourContext, "not", Toast.LENGTH_LONG).show();
}
output.append(remarks);
}
c.close();
return output;
}
![This is code in Main.java for getting data from SQLite3. When i give the query select * from abbrtab then it execute. and apply the where condition then i'm not get any thing. ][1]
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), String.valueOf("Hi"),Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
ASNDBAdapter info = new ASNDBAdapter(AllBranches.this);
info.open();
String data = et.getText().toString();
String result = info.findData(data).toString();
Intent i = new Intent(AllBranches.this, ViewData.class);
i.putExtra("my_data", result);
startActivity(i);
Toast.makeText(getApplicationContext(), String.valueOf(result),
Toast.LENGTH_LONG).show();
info.close();
}
public StringBuilder findData(String find)
{
StringBuilder output = new StringBuilder("Our data is:\n");
Cursor c = ourHelper.getReadableDatabase().query("abbrtab", new String[] {"abbrevaition"},"acronym" +"="+find, null, null, null, null);
String remarks=" ";
int iRemarks = c.getColumnIndex(KEY_ABBR);
if( c.moveToFirst() && c.getCount()>0 )
{
remarks= c.getString(iRemarks);
if(remarks.isEmpty())
{
Toast.makeText(ourContext, "not", Toast.LENGTH_LONG).show();
}
output.append(remarks);
}
c.close();
return output;
}
Here "abbrtab" is table name and "abbrevaition" is name of field .
To get a parameter's value into the query, you have to use a parameter token like ?:
String[] params = new String[]{ find };
Cursor c = db.rawQuery("SELECT abbrevaition FROM abbrtab WHERE acronym = ?",params);
For a simple query like this, you wouldn't need to use rawQuery but could just use query.
String[] params = new String[]{ find };
Cursor c = db.query("abbrtab ", new String{"abbrevaition"},
"acronym = ?", params,
null, null, null);
You also have to ensure that your Column Names are correct.
try this way.
Hi I would like to ask how can I make it an integer here is my code
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String scoreValue = String.valueOf(scoreEdit);
long val = adapter.insertDetails(scoreValue + 3);
finish();
}
what I'm tryng to make is that everytime I click the button it will get the scoreValue and add 3 in it but when I put a number in the scoreValue like "2" it have "23" not "5" as I want it to be. I know it's about the String but when I change the
String scoreValue = String.valueOf(scoreEdit);
to
IntegerscoreValue = String.valueOf(scoreEdit);
I'm having an error can someone please help me please thanks
EDITED:
new code
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int scoreValue = Integer.parseInt(scoreEdit.getText().toString());
long val = adapter.insertDetails(scoreValue + 3);
finish();
}
taken from
public long insertDetails(int score) {
ContentValues contentValues = new ContentValues();
contentValues.put(openHelper_ob.SCORE, score);
opnToWrite();
long val = database_ob.insert(openHelper_ob.TABLE_NAME, null,
contentValues);
Close();
return val;
}
Adding strings together will give you concatenation, but if you want to take the sum of two integers than convert the values to integer do the calculation AND THEN String.valueOf(x) will return the string value of the sum. Where X is the end sum of your result.
Chang to
try
{
int scoreValue = Integer.parseInt(scoreEdit);
}
catch(NumberFormatException ne)
{
ne.printStacktrace();
}
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
use this, have to get string form EditText first
int scoreValue = Integer.parseInt(scoreEdit.getText().toString());
instead of
String scoreValue = String.valueOf(scoreEdit);