Checking username and password in Android - java

I have a username and password field and now i need to check and redirect him to the next page in Android.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText loginText = (EditText) findViewById(R.id.widget44);
final EditText loginPassword = (EditText) findViewById(R.id.widget47);
final Button button = (Button) findViewById(R.id.widget48);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = null;
if(loginText.getText().equals("admin") &&
loginPassword.getText().equals("admin")) {
System.out.println("Entering");
myIntent = new Intent(view.getContext(), Page1.class);
} else {
}
startActivity(myIntent);
}
});
}
Temp now i am checking by hardcoding the values, but this too does not work for me. Why? I usually check in Java like this, why does it not accept me the same way in Android

I think it's because EditText#getText() returns an Editable object. Try
if(loginText.getText().toString().equals("admin") &&
loginPassword.getText().toString().equals("admin")) {
...
}

Don't you need to put toString() to your textelements?
Like this:
if(loginText.getText().toString().equals("admin") &&
loginPassword.getText().toString().equals("admin")) {
...
Edit: neutrino was faster (+1) :)

I am finding only a small problem. In your code, correct it as shown below, and I think it will work:
if(loginText.getText().**toString()**.equals("admin") &&
loginPassword.getText()**.toString()**.equals("admin")) {
System.out.println("Entering");
myIntent = new Intent(view.getContext(), Page1.class);
} else {
...
}
See the correction in asterisks.

Related

Register page else/if

I am very new to java and need some help. I would like to add a function to this register page where users cannot leave their password and username fields blank. I would very much appreciate it if you could type the lines of code as it would be easier for me to visualize.
I have tried implementing else if to this page but it doesn't work and there is no error as well, so i removed those codes. Those codes does not appear in the lines of code i have shown here.Cheers
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
db = new DatabaseHelper(this);
mTextUsername = (EditText)findViewById(R.id.edittext_username);
mTextPassword = (EditText)findViewById(R.id.edittext_password);
mTextCnfPassword = (EditText)findViewById(R.id.edittext_cnf_password);
mButtonRegister = (ImageButton)findViewById(R.id.imagebutton_register);
mTextViewLogin = (TextView)findViewById(R.id.textview_login);
mTextViewLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent LoginIntent = new Intent(RegisterActivity.this,LoginPageActivity.class);
startActivity(LoginIntent);
}
});
mButtonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String user = mTextUsername.getText().toString().trim();
String pwd = mTextPassword.getText().toString().trim();
String cnf_pwd = mTextCnfPassword.getText().toString().trim();
if(pwd.equals(cnf_pwd)) {
Long val = db.adduser(user,pwd);
if(val > 0){
Toast.makeText(RegisterActivity.this,"Successfully Registered.",Toast.LENGTH_SHORT).show();
Intent movetoLogin = new Intent(RegisterActivity.this,LoginPageActivity.class);
startActivity(movetoLogin);
}
else{
Toast.makeText(RegisterActivity.this,"Registration Error.",Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(RegisterActivity.this,"Those passwords didn't match.Try Again.",Toast.LENGTH_SHORT).show();
}
}
});
}
}
You can use the required attribute in html to avid those fields being left blanked.If you use this then you will not need a code to handle blank fields but it will control that situation in the frontend itself.
Refer here how to use it : required attribute
Have you tried make a length comparisson ?
Change this line: if(pwd.equals(cnf_pwd)) { to
if(pwd.length() > 0 && user.length() > 0 && pwd.equals(cnf_pwd)) {
There is no need to make it that complicated. After declaring strings,You can use
if(pwd.isEmpty() || user.isEmpty() )
{
Toast.makeText(RegisterActivity.this,"Enter Username and Password",Toast.LENGTH_SHORT).show();
}
else
{
if{pwd.equals(cnf_pwd))
{
Toast.makeText(RegisterActivity.this,"Successfully Registered.",Toast.LENGTH_SHORT).show();
Intent movetoLogin = new Intent(RegisterActivity.this,LoginPageActivity.class);
startActivity(movetoLogin);
}
else
{
Toast.makeText(RegisterActivity.this,"Make sure Password Entered is same",Toast.LENGTH_SHORT).show();
}
}

Opening another activity based on number of filled editTexts

The app has a MainActivity with 6 editText fields, and a button. There are 5 more activities, named Activity2, Activity3, etc. Now, When a user enters names in editText fields, and press a button, the app should find out how many editText fields are filled, and open the activity with a corresponding number in it's name.
Example:
If only one field is filled, a toast should appear, saying More players.
If two fields are filled, app opens Activity2.
If three fields are filled, app opens Activity3, etc.
Now, to the problem. I am missing something out, and can't find out what. Here is MainActivity.java
public class MainActivity extends AppCompatActivity {
private EditText editText1,editText2,editText3,editText4,editText5,editText6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btn);
editText1 = findViewById(R.id.editText1);
editText2 = findViewById(R.id.editText2);
editText3 = findViewById(R.id.editText3);
editText4 = findViewById(R.id.editText4);
editText5 = findViewById(R.id.editText5);
editText6 = findViewById(R.id.editText6);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int filledFileds = countFilledFields();
Log.d("filled", String.valueOf(filledFileds));
Class newClass = MainActivity.class;
switch (filledFileds){
case 1:
Context context = getApplicationContext();
CharSequence text = "You need more players!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
break;
case 2:
newClass = Activity2.class;
System.out.println("Activity2");
break;
case 3:
newClass = Activity3.class;
System.out.println("Activity3");
break;
case 4:
newClass = Activity4.class;
System.out.println("Activity4");
break;
case 5:
newClass = Activity5.class;
System.out.println("Activity5");
break;
case 6:
newClass = Activity6.class;
System.out.println("Activity6");
break;
default:
}
Intent intent = new Intent(MainActivity.this, newClass);
}
});
}
private int countFilledFields() {
ArrayList<EditText> editTexts = new ArrayList<>();
editTexts.add(editText1);
editTexts.add(editText2);
editTexts.add(editText3);
editTexts.add(editText4);
editTexts.add(editText5);
editTexts.add(editText6);
int filledNumber = 0;
for(int i = 0;i < editTexts.size() ;i++){
if(editTexts.get(i).getText()!=null && !editTexts.get(i).getText().toString().matches("")){
filledNumber += 1;
}
}
return filledNumber;
}
}
The log shows the exact number, something is not working...
Here is your click listener, with the switch omitted for brevity:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int filledFileds = countFilledFields();
Log.d("filled", String.valueOf(filledFileds));
Class newClass = MainActivity.class;
switch (filledFileds){
...
}
Intent intent = new Intent(MainActivity.this, newClass);
}
The problem is at the very end: you've created an Intent object ... but you're not doing anything with it. Probably you have just forgotten a startActivity() call:
Intent intent = new Intent(MainActivity.this, newClass);
startActivity(intent);
Also, looking this over, you have a problem with the case where the user only enters one EditText. As written, you'll still try to start a new activity (you'll just start a new copy of the same MainActivity, which is probably a bad idea). A better idea would be to only start the new activity if the user fills out enough EditTexts:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int filledFileds = countFilledFields();
Log.d("filled", String.valueOf(filledFileds));
Class newClass = null;
switch (filledFileds){
...
}
if (newClass != null) {
Intent intent = new Intent(MainActivity.this, newClass);
startActivity(intent);
}
}
You're missing one thing:
startActivity(intent);

Android: How can I keep empty EditText fields out of a randomized count?

I am working on this Android app that has five EditText fields in the first activity.
Users can fill out any of the EditText fields they want and after pressing a Button, they'll get a randomized answer on a single TextView in the second activity.
For example, if the user fills out 2 EditText fields, the empty ones are still part of the random count.
Also, whenever a user fills out random EditText fields (an example: choiceThree and choiceFour), nothing gets passed to the second activity.
Can anyone help me? Thanks!
Here's the code:
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
EditText choiceOne;
EditText choiceTwo;
EditText choiceThree;
EditText choiceFour;
EditText choiceFive;
Button mainButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
choiceOne = (EditText) findViewById(R.id.inputOne);
choiceTwo = (EditText) findViewById(R.id.inputTwo);
choiceThree = (EditText) findViewById(R.id.inputThree);
choiceFour = (EditText) findViewById(R.id.inputFour);
choiceFive = (EditText) findViewById(R.id.inputFive);
mainButton = (Button) findViewById(R.id.inputButton);
mainButton.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onClick(View view)
{
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
if(choiceOne.getText().toString() != null && !choiceOne.getText().toString().trim().equals(""))
{
intent.putExtra("choiceOne", choiceOne.getText().toString());
}
if(choiceTwo.getText().toString() != null && !choiceTwo.getText().toString().trim().equals(""))
{
intent.putExtra("choiceTwo", choiceTwo.getText().toString());
}
if(choiceThree.getText().toString() != null && !choiceThree.getText().toString().trim().equals(""))
{
intent.putExtra("choiceThree", choiceThree.getText().toString());
}
if(choiceFour.getText().toString() != null && !choiceFour.getText().toString().trim().equals(""))
{
intent.putExtra("choiceFour", choiceFour.getText().toString());
}
if(choiceFive.getText().toString() != null && !choiceFive.getText().toString().trim().equals(""))
{
intent.putExtra("choiceFive", choiceFive.getText().toString());
}
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
}
SecondActivity.java
public class SecondActivity extends Activity {
TextView answerDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
answerDisplay = (TextView) findViewById(R.id.display);
Intent intent = getIntent();
String[] choice = {intent.getStringExtra("choiceOne"), intent.getStringExtra("choiceTwo"),
intent.getStringExtra("choiceThree"), intent.getStringExtra("choiceFour"),
intent.getStringExtra("choiceFive")};
int choiceRandom = (int) (Math.random()*intent.getExtras().size());
answerDisplay.setText(choice[choiceRandom]);
}
When no input is there in an EditText, it doesnt return getText as null, but as "".
And in MainActivity, work with an ArrayList instead of an array.. gives you the option to use the various methods including add and remove.
String choiceX = intent.getStringExtra("choiceX");
if(!choiceX.equals("")) {
choice.add(choiceX);
}
for each of the choices. This is the best and easiest way i can see.. :)
Just check if the String you are getting from the Intent is not equal to ""
if(!intent.getStringExtra("choiceOne).equals(""))
and add only the Strings that are not empty to your String Array. Then you have to get your random number based on how many Strings there are in your Array, by calling choice.length.
put a check in your onClick method for each choice, only then save the value in intent.putExtra()
if(choiceX.getText().toString() != null && !choiceX.getText().toString().trim().equals("")) {
intent.putExtra("choiceX", choiceX.getText().toString());
}
and then instead of doing Math.random*5, use Math.random*intent.getExtras().size()

Android EditText Value Error?

I'm testing out some stuff on android as a beginner and was trying to grab value entered in a EditText when a button was clicked , then compare it to a string value that I defined inside the class, then use if (EditText == stringDefined) else () , but my code always jumps on the else part even if the correct text is entered, any help is appreciated. Here is the code :
Button mButton;
EditText mEdit1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final String user = "admin";
mButton = (Button)findViewById(R.id.BTN_login);
mEdit1 = (EditText)findViewById(R.id.editText1);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
String userEntered = mEdit1.getText().toString().trim();
Intent intent = new Intent(Login.this, Success.class);
if(userEntered == user){
startActivity(intent);
}
else{
AlertDialog.Builder errAlert = new AlertDialog.Builder(Login.this);
errAlert.setTitle("Wrong Credentials");
errAlert.setMessage("Wrong username");
errAlert.setCancelable(true);
errAlert.show();
}
}
});
}
Use equals method :
if(userEntered.equals(user)){
startActivity(intent);
}
== is used to compare primitive types and equals() method of java.lang.String class compares contents.

Solution to equation won't display? (no errors being reported on my end)

So I managed to take 4 different activities involving 4 variables and wrote them in this kind of format:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step1);
Button c = (Button) this.findViewById(R.id.continue1);
final EditText input = (EditText) findViewById(R.id.enterscore);
input.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String score1 = input.getText().toString();
Double.parseDouble(score1);
{ Intent myintent = (new Intent(step1.this,step2.class));
myintent.putExtra("SCORE1",score1);
startActivity(myintent);
}
On my final activity the one that's suppose to display the solution I have coded the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_answer);
}
public void solutionf(View v) {
Bundle extras = getIntent().getExtras();
if(extras!=null){
double score1 = extras.getDouble("SCORE1");
double score2 = extras.getDouble("SCOREF");
double l2 = extras.getDouble("L2");
double l3= extras.getDouble("L3");
double solution= (((score2-score1)/l2)*l3);
String resultString = "Result:" +solution;
TextView resultText= (TextView) findViewById(R.id.solution);
resultText.setText(resultstring);
}
}
}
Why won't the final solution display? I've checked over to make sure everything matches up in terms of the doubles that are set in the activities. Could it be I didn't properly bring the variables over from the previous activities through error on my code?
Any help to getting the solution to show would be appreciated!
Unless a part of your code is missing, solution() is never called.
Add a call to this function in onCreate of your second activity, it should help.

Categories

Resources