Comparing strings in Java - java

Im trying to compare the values of two edittext boxes. What i would like is to just compare passw1 = passw2. As my code is now comparing two strings i have entered as i could not get to compare them.
final EditText passw1= (EditText) findViewById(R.id.passw1);
final EditText passw2= (EditText) findViewById(R.id.passw2);
Button buttoks = (Button) findViewById(R.id.Ok);
buttoks.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (passw1.toString().equalsIgnoreCase("1234") && passw2.toString().equalsIgnoreCase("1234")){
Toast.makeText(getApplication(),"Username and password match", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplication(),"Username and password doesn't match", Toast.LENGTH_SHORT).show();
}
} });

Using the == operator will compare the references to the strings not the string themselves.
Ok, you have to toString() the Editable. I loaded up some of the code I had before that dealt with this situation.
String passwd1Text = passw1.getText().toString();
String passwd2Text = passw2.getText().toString();
if (passwd1Text.equals(passwd2Text))
{
}

[EDIT]
I made a mistake earlier, because, to get the text, you need to use .getText().toString().
Here is a full working example:
package com.psegina.passwordTest01;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class Main extends Activity implements OnClickListener {
LinearLayout l;
EditText user;
EditText pwd;
Button btn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
l = new LinearLayout(this);
user = new EditText(this);
pwd = new EditText(this);
btn = new Button(this);
l.addView(user);
l.addView(pwd);
l.addView(btn);
btn.setOnClickListener(this);
setContentView(l);
}
public void onClick(View v){
String u = user.getText().toString();
String p = pwd.getText().toString();
if( u.equals( p ) )
Toast.makeText(getApplicationContext(), "Matches", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), user.getText()+" != "+pwd.getText(), Toast.LENGTH_SHORT).show();
}
}
Original answer (Will not work because of the lack of toString())
Try using .getText() instead of .toString().
if( passw1.getText() == passw2.getText() )
#do something
.toString() returns a String representation of the whole object, meaning it won't return the text you entered in the field (see for yourself by adding a Toast which will show the output of .toString())

In onclik function replace first line with this line u will definitely get right result.
if (passw1.getText().toString().equalsIgnoreCase("1234") && passw2.getText().toString().equalsIgnoreCase("1234")){

You can compare the values using equals() of Java :
public void onClick(View v) {
// TODO Auto-generated method stub
s1=text1.getText().toString();
s2=text2.getText().toString();
if(s1.equals(s2))
Show.setText("Are Equal");
else
Show.setText("Not Equal");
}

You need both getText() - which returns an Editable and toString() - to convert that to a String for matching.
So instead of: passw1.toString().equalsIgnoreCase("1234")
you need passw1.getText().toString().equalsIgnoreCase("1234").

ou can use String.compareTo(String) that returns an integer that's negative (<), zero(=) or positive(>).
Use it so:
You can use String.compareTo(String) that returns an integer that's negative (<), zero(=) or positive(>).
Use it so:
String a="myWord";
if(a.compareTo(another_string) <0){
//a is strictly < to another_string
}
else if (a.compareTo(another_string) == 0){
//a equals to another_string
}
else{
// a is strictly > than another_string
}

Try to use .trim() first, before .equals(), or create a new String var that has these things.

did the same here needed to show "success" twice
response is data from PHP
String res=response.toString().trim;
Toast.makeText(sign_in.this,res,Toast.LENGTH_SHORT).show();
if ( res.compareTo("success")==0){
Toast.makeText(this,res,Toast.LENGTH_SHORT).show();
}

String password=passw1.trim();
if (password.equalsIgnoreCase("1234")){
Toast.makeText(getApplication(),"Username and password match", Toast.LENGTH_SHORT).show();
}
You need to use the trim method in the String

Related

How can check if a java string contains numbers and letters?

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editTextName);
textView = findViewById(R.id.textViewOne);
button = findViewById(R.id.buttonOne);
view = findViewById(R.id.snackbar_action);
String x = editText.getText().toString();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {//Checking if edit text field is left empty.
if (editText.getText().toString().equals("")) {
Snackbar.make(view, R.string.text_label, Snackbar.LENGTH_SHORT).show();
}//Checking if editText field is numeric.
else if (TextUtils.isDigitsOnly(x)){
Snackbar.make(view, R.string.text_number, Snackbar.LENGTH_SHORT).show();
} else {
textView.setText(NATOConverter("" + editText.getText().toString()));
}
}
});
}
Hello guys im struggling trying to figure out how to check if a my edittext value contains letters and numbers im trying to display a snackbar if the user enters for example "JDF23D" telling them to remove the numbers but my error is no matter what it stays on that else if what would you suggest?
Try next code
if (editText.getText().toString().matches(".*[0-9].*")){
//some code
}
else{
//some code
}
If you want to check whether the string contains a number, you should use this,
public boolean containsDigit(String x){
for(int i = 0; i < x.length(); i++){
if(48 <= (int) (x.charAt(i)) <= 57)
return true;
}
return false;
}
Returns true if even one character is a number, else false.
Try more simplest
boolean match = Pattern.compile("\\d+").matcher(s).find();
You use this method:
TextUtils.isDigitsOnly(x)
but this method checks if your string only contains digits. So your example "JDF23D" will return false.
You can take a look at this post

Unable to get method to access characters in a String

I am trying to make a Caesar Cipher app on Android Studio. I have the XML file and most of the other code ready but was unable to continue past the point in the code where I must access each element of the string. I have tried using the charAt() function.
Also I just want the character at the point in the array to increase by the number specified, I say this because I saw that after 'z' special characters like '|' appear and that is fine by me. This is my first app and could really use some help. The error is at line 47 and 61.
Here is my code:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity
{
EditText input;
EditText output;
EditText num;
String inp;
String out;
int choice;
Character c;
Button enc, dec;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input = (EditText) findViewById(R.id.input);
output= (EditText) findViewById(R.id.output);
num = (EditText) findViewById(R.id.num);
enc = (Button) findViewById(R.id.enc);
dec = (Button) findViewById(R.id.dec);
enc.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
inp=input.getText().toString();
choice= Integer.parseInt(num.getText().toString());
for(int i=0;i<input.length();i++)
{
inp.charAt(i)= (char) (inp.charAt(i)+choice);
}
}
});
dec.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v1)
{
inp=input.getText().toString();
choice= Integer.parseInt(num.getText().toString());
for(int i=0;i<input.length();i++)
{
inp.charAt(i)= (char) (inp.charAt(i)-choice);
}
}
});
}
}
Building on #corsiKa's answer, I suggest the following. First, convert your input string into a char[]:
char[] array = inp.toCharArray();
Now you can iterate over the array and modify its contents:
array[i] = array[i] + choice;
And, at the end, you can build your output string from that array:
output.setText(new String(array));
I believe your first problem is here:
inp.charAt(i)= (char) (inp.charAt(i)+choice);
You are trying to assign a value to a method return. This is not possible in Java.
Strings are immutable in Java - if you'd like to replace a value in a String, you must build a new String and resassign the reference that points to the old String to instead point to the new String.
There may be other issues that I have not had a chance to get to, but I believe this is the real issue. I don't fully understand what you're trying to do, so unfortunately I can't make a suggestion for what you should use instead.

java.lang.NumberFormatException: Invalid int: “” error android

I am making an app where user must enter basic info about self.First name,second name, city and quantity that he or she wish to order.If he or she skip one field toast will pop up with message what field is skipped. And that is ok.That works, but if he skips quantity field I got error on my phone and it send user back on previously activity.When I inspect my LogCat I see error message
java.lang.NumberFormatException: Invalid int: “” error
Now I know why that message appears.Because it expected to find Integer,in if statment. but actually finds String. But do not know how to fix it.The last if/else statemen is an Issue:
Now what i tried so far:
1) Tried to set primitive int as object Integer
2)Tried to use kolicina==0;
3)Tried to use kolicina.equals(null) / kolicina.equals(0);
4)Tried to use .isEmty();
my code:
package com.dsk.android.decijisvetknjiga;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Narudzbina extends AppCompatActivity {
String porukaGreska="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.narudzbina);
}
public boolean praznoPolje(EditText et){
return (et != null && (et.equals("") || et.equals(" ")));
}
public void kreiranjeNarudzbine(View v) {
EditText editTextIme = (EditText) findViewById(R.id.ime);
String imeNarucioca = editTextIme.getText().toString();
praznoPolje(editTextIme);
EditText editTextPrezime = (EditText) findViewById(R.id.prezime);
String prezimeNarucioca = editTextPrezime.getText().toString();
praznoPolje(editTextIme);
EditText editTelefonNarucioca = (EditText) findViewById(R.id.telefon);
String telefonNarucioca = editTelefonNarucioca.getText().toString();
praznoPolje(editTelefonNarucioca);
EditText editAdresaNarucioca = (EditText) findViewById(R.id.adresa);
String adresaNarucioca = editAdresaNarucioca.getText().toString();
praznoPolje(editAdresaNarucioca);
EditText editGradNarucioca = (EditText) findViewById(R.id.grad);
String gradNarucioca = editGradNarucioca.getText().toString();
praznoPolje(editGradNarucioca);
EditText editKolicina = (EditText) findViewById(R.id.kolicina);
String narucenaKolicina = editKolicina.getText().toString();
int kolicina = Integer.parseInt(narucenaKolicina);
praznoPolje(editKolicina);
int cenaNarudzbine = cena(kolicina);
String poruka = sumiranjeNarudzbine(imeNarucioca, prezimeNarucioca, telefonNarucioca, adresaNarucioca, gradNarucioca, cenaNarudzbine);
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", "+1111111");
smsIntent.putExtra("sms_body", poruka);
if(imeNarucioca!=null && imeNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Unesite ime", Toast.LENGTH_LONG).show();
}
else if(prezimeNarucioca!=null && prezimeNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite Prezime", Toast.LENGTH_LONG).show();
}
else if(telefonNarucioca!=null && telefonNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite kontakt telefon", Toast.LENGTH_LONG).show();
}
else if(adresaNarucioca!=null && adresaNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite adresu",Toast.LENGTH_LONG).show();
}
else if(gradNarucioca!=null && gradNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Navedite grad", Toast.LENGTH_LONG).show();
}
else if(narucenaKolicina!=null && narucenaKolicina.equals("")){
Toast.makeText(Narudzbina.this, "Navedite zeljenu kolicinu", Toast.LENGTH_LONG).show();
}
else{
startActivity(smsIntent);
}
}
English is not my native language so do apologize for spelling mistakes or some lack of clarity in the matter, I'd be happy to explain it if necessary.
Your problem is on this line
int kolicina = Integer.parseInt(narucenaKolicina);
If the input is empty, it will try to parse an empty string "". You need to wrap this in an if statement to check if narucenaKolicina is empty or a valid int before you try to parse it.
Tip for you to ignore this exeception:
EditText editKolicina = (EditText) findViewById(R.id.kolicina);
String narucenaKolicina = editKolicina.getText().toString();
if(!narucenaKolicina.isEmpty())
int kolicina = Integer.parseInt(narucenaKolicina);
else
Toast.makeText(Narudzbina.this, "Don't leave this field empty", Toast.LENGTH_LONG).show();
You need to check if your string have empty text, not only null value or 0.
You have to do something like this
kolicina.equals("");
The exception is caused by the parseInt() method so change kolicina to integer is not useful
You should try something like this :
if (narucenaKolicina != null && !narucenaKolicina.toString().trim().equals(""))
As condition to avoid "" string.

IF Condition doesnt work

Am trying to make an IF condition but it's not working well. I want when the EditText is null, the user doesn't go to the next Activity.
when it's filled it goes to the next activity after a button press.
Name = is my EditText assignment
one_next_diaspora_bt = is the Button.
Below is my Code:
final String Name = name_diaspora_edt.getText().toString();
one_next_diaspora_bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(Name.matches("")){
Toast.makeText(getApplicationContext(),"Make sure that you have filled your name please !!!",Toast.LENGTH_LONG).show();
}
else {
Intent i = new Intent(Diaspora.this,DiasporaTwo.class);
i.putExtra("Name",Name);
i.putExtra("Age",Age);
i.putExtra("Gender",Gender);
i.putExtra("MaritalStatus",MaritalStatus);
startActivity(i);
}
}
});
Change your condition to this:
if(edt.getText().toString().isEmpty()){
}
Or
if (edt.getText().trim().equals("")){
}
use:
if (Name.getText() != null && Name.getText().toString().trim().equals(""))
And follow the Java naming convention. variable names should start with lower case character
try this:
if (Name != null && Name.equalIgnoreCase("null") && Name.trim().equalIgnoreCase("")){
}else
{
}
Use this :
one_next_diaspora_bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String Name = name_diaspora_edt.getText().toString().trim();
if(Name.matches("")){
Toast.makeText(getApplicationContext(),"Make sure that you have filled your name please !!!",Toast.LENGTH_LONG).show();
}
else{
Intent i = new Intent(Diaspora.this,DiasporaTwo.class);
i.putExtra("Name",Name);
i.putExtra("Age",Age);
i.putExtra("Gender",Gender);
i.putExtra("MaritalStatus",MaritalStatus);
startActivity(i);
}
}
});
}
Try TextUtils.isEmpty, it will check null and empty as well. TextUtils is a built-in class in package android.text
if(android.text.TextUtils.isEmpty(Name)) {
First I would say, you really should follow naming conventions.
But you need to grab the String that lives inside of your EditText and compare it with .equals like so:
if(name.getText().toString().equals("")){
//do something
}
if (TextUtils.isEmpty(Name)){
Toast.makeText(getApplicationContext(),"Make sure that you have filled your name please !!!",Toast.LENGTH_LONG).show();
}
Use android default validation, TextUtils class
Use TextUtils.isEmpty(Name) instead of Name.matches("").
TextUtils.isEmpty(CharSequence str) >> Returns true if the string is null or 0-length.
Try this:
final String Name = name_diaspora_edt.getText().toString();
one_next_diaspora_bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(TextUtils.isEmpty(Name)) {
Toast.makeText(getApplicationContext(),"Make sure that you have filled your name please !!!",Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent(Diaspora.this, DiasporaTwo.class);
i.putExtra("Name", Name);
i.putExtra("Age", Age);
i.putExtra("Gender", Gender);
i.putExtra("MaritalStatus", MaritalStatus);
startActivity(i);
}
}
});
Hope this will help~
You can directly check the EditText with this method , equals() works with Strings.
Try This
String data = Name.getText().toString();
Then
if(data.isEmpty()){
}

Logic Error; TextView returns even after setting to null

I have a logic error in a simple android app;
I have 3 Buttons (Permute, Clear and GC), 1 EditText and a TextView. When the Permute button is clicked it sends the text in the EditText box to a method from another class and sets the returned value to the TextView. The returned value is just gibberish text.
When I click the Clear, it clears the current contents of the EditText box and the TextView; (by setting the contents to a null string "").
However when I click Permute with new values in the textBox, the old (cleared) text returns along with the newer text below
Here's the code:
package com.mobinga.string;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.mob.string.Perm;
public class MoPermActivity extends Activity implements View.OnClickListener {
Button btn;
Button btn2;
Button btn3;
EditText et;
TextView tv;
Vibrator vi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.Permute);
btn2 = (Button) findViewById(R.id.Clear);
btn3 = (Button) findViewById(R.id.GC);
btn.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
et = (EditText) findViewById(R.id.Text);
tv = (TextView) findViewById(R.id.textView1);
}
public void onClick(View view){
switch(view.getId()){
case R.id.Permute:
vi = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vi.vibrate(50);
tv.setText(Perm.perm(et.getText().toString()));
break;
case R.id.Clear:
vi = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
et.setText("");
tv.setText("");
vi.vibrate(50);
break;
case R.id.GC:
vi = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
GC();
vi.vibrate(50);
}
}
public static void GC(){
Log.d("Permute","Calling GC");
System.gc();
}
}
How do I properly and completely clear the contents of TextView, and stop it from returning? Simply put : My problem is that the supposedly cleared contents of the TextView return back even after clearing.
Edit if necessary here's the Perm Class
package com.mob.string;
public class Perm {
static String v = "";
static void permute(int level, String permuted, boolean used[], String original) {
int length = original.length();
if (level == length) {
v +=permuted+"\n";
} else {
for (int i = 0; i < length; i++) {
if (!used[i]) {
used[i] = true;
permute(level + 1, permuted + original.charAt(i), used, original);
used[i] = false;
}
}
}
}
public String perm(String s){
boolean used[] = {false, false, false, false, false,false,false};
permute(0, "", used, s);
return v;
}
}
v is never reset.
public String perm(String s){
v = "";
boolean used[] = {false, false, false, false, false,false,false};
permute(0, "", used, s);
return v;
}
However I don't see why v even exists to be honest. I would of passed it through the recursive calls.
I dont know what the calss Perm is you are using but why not just try
tv.setText(et.getText().toString());
EDIT:
You should try setting it t a String variable first.
String editText = et.getText.toString();
then pass it to your TextView
tv.setText(editText);
I think that the problem lies in your Perm class - here you've got a static String, which isn't cleared anywhere (just appended). If you hold state in your class, make this "v" string a normal field and instantiate your class when needed.
Store the state of the string in the Activity, pass it into the Perm class when you want to append values to it, and then clear the stored string at the same time you clear your TextView.
Or make a method in the Perm class called clearString which sets v = "", and call it when you clear the TextView.
You have to clear the text in TextViews by setting text "" and clearing v value in Perm class. That should do the trick.

Categories