I’m creating a lock screen app for android, but I’m having trouble getting the activity to finish when the correct password is entered. The code works only works if the password is one character; otherwise, it doesn’t unlock. I think it has to do with how I’m modifying the global variables.
This is the code I’m using to test. It should unlock with by touching the two textviews in order, but doesn’t.
public class LockScreen extends Activity implements OnClickListener {
String password = "cd";
String guess;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lock_layout);
TextView c = (TextView) findViewById(R.id.c);
TextView d = (TextView) findViewById(R.id.d);
c.setOnClickListener(this);
d.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.c:
if (guess == null) {
guess = "c";
} else {
guess += "c";
}
break;
case R.id.d:
if (guess == null) {
guess = "d";
} else {
guess += "d";
}
break;
}
if (guess == password) {
finish();
}
}
– Use
equals()method to compare.– In Java
Objectsare compared usingequals()method, andStringis an object, so its should also follow the same trend as object.–
==are used to see if 2 or moreObject Reference Variablesare pointing on the same object or not on the heap.– And just a piece of advice, that its always better to use
char[](ie char array) for storing password instead ofString.Eg: