Error while checking user input - android

I'm trying to check the editText condition. In the code below, I declared a setOnClickListener method to check the condition of editText. If condition is true, I want to print toast message, change the activity and to output a sound. If condition fails, it should toast a single message. In both cases if it's true or not, it prints me only "Incorect" no matter if editText is correct.
What I am doing wrong?
public void next(View v){
final MediaPlayer correctSound = MediaPlayer.create(this, R.raw.correctsound);
Button playCorrectSound = (Button) this.findViewById(R.id.angry_btn1);
final EditText editTextt = (EditText) findViewById(R.id.editText);
playCorrectSound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editTextt.setVisibility(View.INVISIBLE);
if(editTextt.getText().toString() == "string")
{
Toast.makeText(getApplicationContext(), "Correct", Toast.LENGTH_SHORT).show();
correctSound.start();
Intent i = new Intent(Hereuu.this, MainActivity.class);
startActivity(i);
} else {
Context context = getApplicationContext();
CharSequence text = "Incorect";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
editTextt.setVisibility(View.VISIBLE);
}
});
}

Like everyone had said, you
Basically, when you use == operator, your are checking if the reference for object are the same/equals. When you use .equals(String), the method checks the content.
tip:
When your are working with Strings, remember to avoid NullPointerException situations. So,you should write "constant".equals(editTextValue) instead of editTextValue.equals("constant")
The link bellow will help you to understand how String objects and String content work:
Java String.equals versus ==
regards

in java you need to compare strings using equals method instead of ==
check this topic for more details

I would suggest you to take some basic JAVA lessons. That will immensely help you.
For now, the problem is in the way you are checking equality of the strings. You do not use == with strings, you use String#equals() method. So,
Change
editTextt.getText().toString() == "string"
to
editTextt.getText().toString().equals("string")

Make sure to compare strings in java with .equals and not ==. Use this if statement:
if(editTextt.getText().toString().equals("string"){

Related

if-else block not working properly in android

Scenario: when the focus is lost from an EditText, I'm checking if it contains null (in the first if block).
If so, then I'll show a Toast.
In the else-if block I'm checking if the EditText doesn't contain letters.
Then I'll show a toast, but when I run the application, the Toast is shown even on a correct input.
I.e.: If I enter any letter the Toast should not be shown, it should be shown only when a null or digit/special symbol is entered.
Here is the code
et1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus)
{
a = et1.getText().toString();
if (a.equals(""))
{
Toast.makeText(getApplicationContext(), "Your entry is incorrect!!", Toast.LENGTH_LONG).show();
}
else if (!a.contains("[a-z]")||!a.contains("[A-Z]")) {
Toast.makeText(getApplicationContext(), "Your entry is incorrect!!", Toast.LENGTH_LONG).show();
}
else
{
}
Please help
The '==' operator only compares references. To compare string values you must use the equals() method.
Instead of
if (a == "")
use
if (a.equals(""))
See: What is the difference between == vs equals() in Java?
It's not working because:
if (a == "")
won't work in Java
Use
if (a.equals(""))
instead
Also, String.contains doesn't use regular expressions, but CharacterSequences.
So, unless your string doesn't contain the exact character sequences "[a-z]" or "[A-Z]" (and only one of these 2 strings), you'll never get a match.
See: http://developer.android.com/reference/java/lang/String.html#contains(java.lang.CharSequence)
The problem is:
if (a == "")
Strings can't be compared like this. Instead, check for size equal to 0, or against a specific string with the equals() method.

How to return a toast to anything typed on EditText but a specific word?

I am currently developing my first android application, which is actually my first contact with java ever. Therefore, I suppose this question has an obvious answer to experienced developers, but I couldn't find anything at SO or anywhere else. The following EditText has two toasts (I'm not sure if that sounded right). One is shown if the user types a specific word (in this case, Please is shown if the user types Magic word and presses the button). I would like the another toast to appear if the user types anything else but that word (anything but "Magic word") when clicking the button.
EditText editText1 = (EditText) findViewById(R.id.editText1);
{
if(editText1.getText().toString().trim().equals("Magic word"))
{
Toast.makeText(MainActivity.this,
"Please", Toast.LENGTH_LONG).show();
}
}
else if (editText1.getText().toString().trim().equals())
{
Toast.makeText(MainActivity.this,
"You didn't say the magic word", Toast.LENGTH_LONG).show();
}
}
}
});
I apologize for my poor english. Hopefully, I made myself understood.
Thank you very much.
Following code give you the solution:
final EditText editText1=(EditText)findViewById(R.id.editText1);
Button btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
final String edittext=editText1.getText().toString();
if(edittext.trim().equals("Magic word"))
{
Toast.makeText(MainActivity.this,
"Please", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(MainActivity.this,
"You didn't say the magic word", Toast.LENGTH_LONG).show();
}
}
});
More simple way!!
String hello = editText1.getText().toString();
and then,
Toast.makeText(MainActivity.this, "The text is" +hello , Toast.LENGTH_SHORT).show();
More accurately "Magic word" isn't a word, its two with a space. The first if statement will require the text in the EditText to be exactly that for the statement to be true. If you actually intended for "magic word" to merely be somewhere in the text typed into the EditText to show a Toast that says please, look into using String.contains() or regex for the first comparison.
For all other conditions there's no need to check the value of the EditText. In other words remove the second if just keep else as Luksprog mentioned.

where to put checking edittext syntax?

i need a favor.. i'm confused to put these codes to check whether the edittext is empty or not:
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
where must i write these codes? is it between these codes?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuawal);
...
...
...
JmlAhliWarisAnakLK = (EditText) findViewById(R.id.JmlAhliWarisAnakLK);
JmlAhliWarisAnakPR = (EditText)findViewById(R.id.JmlAhliWarisAnakPR);
or in this function after double sisa=0;??
public void cc() {
int JmlWarisAnakPR = Integer.parseInt(JmlAhliWarisAnakPR.getText().toString());
int JmlWarisAnakLK = Integer.parseInt(JmlAhliWarisAnakLK.getText().toString());
int JmlHarta = Integer.parseInt(JmlHartaPeninggalan.getText().toString());
double HasilSuami = 0;
double HasilIstri = 0;
double HasilAnakLK = 0;
double HasilAnakPR = 0;
double sisa = 0;
}
please correct me if i'm wrong.. :D
you are on the right track
After you set the layout using setContentView you need to add your EditText's which you are doing fine as follows.
JmlAhliWarisAnakLK = (EditText)findViewById(R.id.JmlAhliWarisAnakLK);
JmlAhliWarisAnakPR = (EditText)findViewById(R.id.JmlAhliWarisAnakPR);
You then need to store the value you get from the EditText's in some variable,
int JmlWarisAnakPR = Integer.parseInt(JmlAhliWarisAnakPR.getText().toString());
....
....
After you have stored your values you can then call some method that validates your input on click of a button(if you have):
public void validateinput()
{
if(input == null || input.trim().equals(""))
{
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
}
According to me, you should put the check on some event, like if its login screen, then on click of submit button. or other wise on focus change it main instantly provide user with the toast that he left the field empty. or if other case, please provide more information for your query. thanks.
That depends on when you want to validate the editText..You propably have some button which "submits" the EditText so call this code in after onClick event gets fired on the button..
Put the input validation code when you have to navigate away from the current activity, either to go to another activity or to save the input details. That's the least annoying place to shove an error message onto the user.
Another approach is to validate when the focus leaves the EditText. But in this case the error notification should be more subtle (and therefore less annoying) like changing the EditText's background to lightred.
Ur questions does not seem to be clear. Are u asking where do u need to put the validation for empty edittext? If this is ur question then the general case would be to validate during any events such as BUTTON CLICK. Set the onClickListener for ur button and inside ur onclick perform the validation.
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
Your above code is pretty much correct. You Must need to add above code whenever you want to take input from these edittext, Or whenever you want to save these value. make a function which will return true if edit text is empty so u can ask user to enter values
public boolean isETEmpty(){
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
return true;
}
return false; // if not empty
}
call this function Whenever u want to use values from ET, if this function return true, you must let user enter values. Such as on Button Click to save etc

Show Dialog Box when Button is clicked and the String of EditText is empty

I want to make that when the user click the button below and the String on EditText is empty, it shows a dialog.
So I made this method, but unfortunately rather than showing a Dialog Box, the app crashed. There's no problem with the Dialog box method, the problem is the IF function doesn't read what I requested properly.
Anybody has the solution for this?
Here's my method:
public void onClick(View v) {
if(v == launchSimplePayment) {
String amount = paymentAmount.getText().toString();
System.out.println(amount);
if (amount == "")
{
errorDialog();
}
else
{
System.out.println(amount);
// Use our helper function to create the simple payment.
PayPalPayment payment = exampleSimplePayment();
// Use checkout to create our Intent.
Intent checkoutIntent = PayPal.getInstance().checkout(payment, this, new ResultDelegate());
// Use the android's startActivityForResult() and pass in our Intent. This will start the library.
startActivityForResult(checkoutIntent, request);
}
}
Change this
if (amount == "")
with this
if (amount.equals(""))
Remember that the operator == compares references, not the content!
You should rewrite the condition like this:
if (amount.trim().equals(""))
Since a blank space like this " " would pass over your validation check.

Register not able to be done due to error checking in the if..else statement

I got problem with register. I use an if-else statement to check whether the user left any blank. If there is any blank, an error message will appear. The problem is, even with no blanks, all filled up, the error message still appears and thus prevents user from registering. I can't find any error.
Please help me spot my error.
package log1.log2;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Login extends Activity {
DBAdapter db = new DBAdapter(this);
/** Called when the activity is first created. */
private EditText etUsername;
private EditText etPassword;
private Button btnLogin;
private Button btnRegister;
private TextView lblResult;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the EditText and Button References
etUsername = (EditText)findViewById(R.id.usernametxt);
etPassword = (EditText)findViewById(R.id.passwordtxt);
btnLogin = (Button)findViewById(R.id.btnLogin);
btnRegister = (Button)findViewById(R.id.btnRegister);
lblResult = (TextView)findViewById(R.id.msglbl);
//Cursor c = (Cursor) db.getAllTitles();
//Button btnArrival = (Button) findViewById(R.id.btnRegister);
//btnArrival.setOnClickListener(this);
// Set Click Listener
btnRegister.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(Login.this,Register.class);
startActivity(intent);
}
});
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
db.open();
Cursor c = (Cursor) db.getAllUser();
c.moveToFirst();
// Check Login
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
if(username.equals("") || password.equals(""))
{
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "FILL IN ALL FIELDS", duration);
toast.show();
}
else
{
if(username.equals(c.getString(1)))
{
if(password.equals(c.getString(2)))
{
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "LOGIN SUCCESS", duration);
toast.show();
long id;
id = db.insertTransaction(
new String(etUsername.getText().toString()));
Intent intent=new Intent(Login.this,Test.class);
startActivity(intent);
}
else
{
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "LOGIN FAIL", duration);
toast.show();
}
}
else
{
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "LOGIN FAIL", duration);
toast.show();
}
}
db.close();
}
});
}
}
Thank you very much.
Dayne,
I'm gonna try to help you here. Before I do, though, I want you to understand that you have been violating a lot of the conventional rules of stack overflow. I put a lot of time into trying to sort out your issues in this question, so I want to ask you to take a bit of time and try to understand what it is that you are doing wrong that makes others users on stack overflow (including me) very annoyed.
First, please don't use all caps. It is considered rude. Second, please don't post multiple questions on stack overflow that are all about the same issues. This is the 7th question that you have posted regarding this issue. That is also considered rude. Please post one question, and if the suggested answers do not work for you, then comment on them and ask for more help, specifying what part of their answer you used and what problems you are having still. Third, please do not post your entire file. If your entire file is needed the the commentors will ask you to post it, but don't post it up front. Consider that the people who are helping you with your questions are NOT getting paid. They are doing it for free, as a service to people trying to learn how to program. Posting your entire file up front is like you are asking someone to do your work for you, and the users on here are not interested in doing your work, they are interested in helping people learn. We want you to be able to do this stuff yourself. If you just want a solution that works and are not interested in learning why it works, you would be better off choosing a different community of people to ask questions to. Lastly, please try to research more! A lot of your questions betray that you are utterly clueless about how certain things work. Please, rather than simply posting on stackoverflow again and again, go spend a few hours reading up on how to create a login system in Android
That being said, you seem like a nice enough person to me. It looks like you are new to stack overflow and new to programming in general, so I am willing to forgive all those things you did that annoyed me, as long as you do your best to not do them again.
General Issues with your code
Ok, let's get into the general point of your code code. I have tried to fix your code to the point that it compiles and works. However, I want to point out that what you are trying to do is largely useless for any practical program. If I understand you correctly, you are trying to have a user login to some service or be able to register for that service. However, it looks like you are trying to use a database on the phone to log users in or register new users. If you have a database of usernames and passwords stored on a phone, then there is no way to have another user login. Let me give you an example. User A has a phone, and user B has a phone. If the database of usernames and passwords is stored on user A's phone, then how will user B login? Additionally, how would user B register for the service? There is reliable way to communicate between the two phones. On top of that, what if user A drops their phone and it breaks? Does that mean that your entire service is unavailable?
What you need to do, if you are providing login/registration for some service, is to have a server set up somewhere that phones can contact to perform login operations or registration operations. Setting up a server and a login/registration system is a big project, and you will need to read up on how to do that before anyone can really help you - right now I dont think you would understand most of the advice they would give you.
That being said, it is possible that you just want to get this local database login system to work for some reason (perhaps you just want something to work, all programmers have had a point where nothing they do seems to work and you are desperate to make anything work ;) ). So, let's see if we can make it work . . .
Separation of responsibility
You are trying to solve 2 main problems (I am ignoring registration for now. If you understand login then you can figure out registration). First, you want to provide some feedback to the user if they do not give you a username or a password. Second, you want to check if that person has provided a correct username / password combination. Right now you are trying to solve both of these problems within the Login Activity. I recommend separating these responsibilities - let the Login class handle providing feedback, and slightly modify your DBAdapter class so that it can handle checking the username/password.
Modify your DBAdapter class and add the following method:
public boolean isValidUser(String username, String password) {
Cursor c = <your SQLiteDatabase>.rawQuery("SELECT username FROM Users WHERE username='?' AND password='?'", new String[] {username, password});
boolean result = c.moveToFirst();
return result;
}
Please note that this method has a lot of problems, and should not be used in production code. I am assuming you just want this to work, and you don't care if it is perfect. If you can get this all working, perhaps ask a new question focused on verifying that a username / password combination is correct.
Note that you need to change the part that says <your SQLiteDatabase> to contain your database name.
Once you have added this method, your DBAdapter class can, given a username and password, inform you if that username and password combination is valid.
Making the Login Activity
Change the btnLogin onClickListener to this:
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
if (username.trim().equals("") || password.trim().equals("")) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "FILL IN ALL FIELDS",
duration);
toast.show();
// Rather than having a huge else {} block, why not just add a
// return statement here? Then the rest of your code is a bit
// cleaner!
return;
}
db.open();
if (db.isValidUser(username, password))
{
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"LOGIN SUCCESS", duration);
toast.show();
Intent intent = new Intent(Login.this, Test.class);
startActivity(intent);
} else {
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "LOGIN FAIL",
duration);
toast.show();
}
db.close();
}
});
That should be all you need to get this to work! Note, however, that you didn't post your DBAdapter class here. I didn't want to look through the 7 posts to find it. Given the state of this post's code and the one other I looked at, it's likely that there are some errors in your DBAdapter. Read this section on the Android docs and try to debug that part yourself :) If you get stuck, you can ask a question about how to build a database on Android, and NOT a question about how to build a database/login on Android, since your login code should be mostly workable if you use the code I pasted here!
Final Points
Please consider the following comments I made when originally looking at your code
// NO!!!! Do not do this. You will end up with a problem
// very similar to http://stackoverflow.com/questions/3352957/
// why-does-not-this-work-android-oncreate/3352978#3352978
// Instead, say db = new DBAdapter(this) inside of the onCreate() method!
DBAdapter db = null; // new DBAdapter(this);
Also,
// This is an absolutely huge inner-class. It would be a lot better
// to extract this into a private member variable, by saying
// OnClickListener foo = new OnClickListener() { <put all code here> };
// btnLogin.setOnClickListener(foo);
btnLogin.setOnClickListener(new OnClickListener() {
Also,
// No!! If you are calling getAllUser(), you are likely returning a Cursor that points
// to a ton of users. The way your code is now, you are returning a list of all users
// in the application, and then checking to see if this data entered matches the first
// user. This would never work! If you have more than one user, then you need to check
// if the data entered matches ANY of your users. I am removing this code
// db.open();
// Cursor c = (Cursor) db.getAllUser();
// c.moveToFirst();
Cheers,
Hamilton
I think you need to do username.getText().equals(""), not just .equals because in that case you try to compare the empty string to the EditText object...

Categories

Resources