This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I am new to app development and I have a problem with coding in android studio. I want to compare an input text with a string in the string array. For some reason it won't work. When i try the java code in eclipse it works.
I already run the debugger and the inputmessage is "Banana". The debugger also shows that message = "Banana" when it is in CheckAnswer(message). But for some reason the function isn't returning "Right". It returns "wrong"
I hope somebody can help me.
Here is my code:
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
String message2 = CheckAnswer(message);
intent.putExtra(CORRECT_MESSAGE, message2);
startActivity(intent);
}
public static String CheckAnswer(String string) {
String rightanswer[] = {"Apple", "Banana", "Coconut"};
String answer = null;
for (int i = 0; i <= rightanswer.length-1; i++) {
if (string == rightanswer[i]) {
answer = "Right!!";
break;
}
else answer = "Wrong.";
}
return answer;
}
The correct way of comparing two strings is with equals() function not ==
So Change :
if (string == rightanswer[i]) {
answer = "Right!!";
break;
}
to:
if (string.equals(rightanswer[i])) {
answer = "Right!!";
break;
}
When you are comparing Strings in Java, it is best to use the String's equals()method which looks like this:
if(someValue.equals(somethingElse){}
I hope this helps!
Related
So I have 2 screen one to store the other to retrieve. What I want ultimately is storing the checked checkbox into sharedPref, retrieve it as a STRING and put it inside an ArrayList to shuffle for a random STRING that was SELECTED.
So far I tried many solutions but none worked. I always get the unchecked checkbox as well. I only want checked even if I just select ONE of the checkbox. Any advise would be appreciated.
EDIT: I have solve the problem...at least for now. Look at the UpdateReceive.java to see the solution. But however for other screens I will have 9 Checkboxes and the possibilities are too tedious to do it this way. So are there any better methods out there?
Storing.java
SharedPreferences sharedMode = getSharedPreferences("MySharedMode", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedMode.edit();
editor.clear();
editor.commit();
if ( cbCool.isChecked() || cbHeat.isChecked()) {
editor.putBoolean("Cool", cbCool.isChecked());
editor.putBoolean("Heat", cbHeat.isChecked());
editor.commit();
}
Receieve.java
SharedPreferences sharedMode = getSharedPreferences("MySharedMode", Context.MODE_PRIVATE);
String heat = String.valueOf(sharedMode.getBoolean("Heat", false));
String cool = String.valueOf(sharedMode.getBoolean("Cool", false));
if (heat != null && cool != null) {
String m_heat = "Heat";
String m_cool = "Cool";
List<String> list = new ArrayList<String>();
list.add(m_heat);
list.add(m_cool);
Collections.shuffle(list);
String randMode = list.get(0);
tvMode.setText(randMode);
}
UpdatedReceive.java
if (heat == "true" && cool != "true") {
tvMode.setText("Heat");
}
else if (heat != "true" && cool == "true") {
tvMode.setText("Cool");
}
else if (heat =="true" && cool == "true") {
String m_heat = "Heat";
String m_cool = "Cool";
List<String> list = new ArrayList<String>();
list.add(m_heat);
list.add(m_cool);
Collections.shuffle(list);
String randMode = list.get(0);
tvMode.setText(randMode);
}
This question already has answers here:
How to validate phone numbers using regex
(43 answers)
Closed 7 years ago.
Having trouble using a regex to validate a phone number. I want to allow only numbers and hyphens, but so far I've been trying to just get numbers working. Unfortunately despite different changes after looking around Google and Stack Overflow, the regex continues to evaluate as false. Ideally, strings such as 8889990000 or 888-999-3333 should both evaluate to true. Any help is appreciated!
Main class code for regex:
boolean correct = PhoneFilter.filterPhone(phone_num);
if (correct == true) {
//create an intent to carry data from main activity to OrderConfirmationActivity
Intent intent = new Intent(MainActivity.this, OrderConfirmationActivity.class);
//pack pizza order data into intent
intent.putExtra("nameSelected", nameEditText.getText().toString());
intent.putExtra("aVariable", type);
intent.putExtra("mtSelected", mt);
intent.putExtra("otSelected", ot);
intent.putExtra("ptSelected", pt);
intent.putExtra("dateSelected", Date);
//start the OrderConfirmationActivity
startActivity(intent);
}
//alert user if phone number entered incorrectly
else if (correct == false) {
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Please enter a phone number in either 000-0000-000 format or 0000000000 format");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
The code for filterPhone is:
public class PhoneFilter {
public static boolean filterPhone(String phone_text) {
boolean correct;
if ((phone_text.length() <= 12) && (phone_text.matches("[0-9]+")))
correct = true;
else
correct = false;
System.out.println("correct =" + correct);
return correct;
//InputFilter lengthFilter = new InputFilter.LengthFilter(12);
}
}
Try switching
phone_text.matches("[0-9]+")
to
phone_text.matches("^[0-9-]+$")
I put together a quick test to try it out:
public static void main(String[] args) {
//Sysout for example only
System.out.println(filterPhone("8889990000"));
System.out.println(filterPhone("888-999-3333"));
System.out.println(filterPhone("888B999A3333"));
System.out.println(filterPhone(""));
}
public static boolean filterPhone(String phone_text) {
boolean correct;
if ((phone_text.length() <= 12) && (phone_text.matches("^[0-9-]+$")))
correct = true;
else
correct = false;
System.out.println("correct =" + correct);
return correct;
// InputFilter lengthFilter = new InputFilter.LengthFilter(12);
}
Produces:
correct =true
true
correct =true
true
correct =false
false
correct =false
I am trying to convert a value from Double to String in an Android Activity.I can get this to work with my first example here below (working in the sense of no squigly error from Eclipse). However I am curious as to why the second example is not working.
First example
balance = (TextView) findViewById(R.id.textViewCardBalance);
Intent intent = getIntent();
if (intent.getExtras() != null) {
balance.setText(String.valueOf((long)intent.getDoubleExtra("balance", 0.00)));
}
Second example below not working (Error: "Cannot cast from Double to Long"
balance = (TextView) findViewById(R.id.textViewCardBalance);
Double cardBalance;
Intent intent = getIntent();
if (intent.getExtras() != null) {
cardBalance = intent.getDoubleExtra("balance", 0.00);
balance.setText(String.valueOf((long)cardBalance);
}
Would anyone know how I can get the second example to work as I need to log the value retrieved from the intent before passing it to the TextView.
Thanks
Why can't you do this?
balance.setText(cardBalance + "");
String yourDoubleString = String.valueOf(yourDouble);
in your case:
String yourDoubleString = String.valueOf(intent.getDoubleExtra("balance", 0.00));
using String v = ""+String.valueOf((long)cardBalance) not work?
I want passing parameters taking from a edittext in the google maps.. the method:
public void nav() {
String address = edit.getText().toString();
address = address.replace(" ","+");
String city = address.substring(address.lastIndexOf(" ") + 1);
Intent i = new Intent(Intent.ACTION_VIEW, uri.parse("geo:0,0?q="+city));
startActivity(i);
}
why String city = address.substring(address.lastIndexOf(" ") + 1);? Because the intent have to start only if in the edittext there is the word bring. So maps starts only if anyone write: bring me New york for example.. The "problem" is that actually the maps application takes the whole string and not only the city. I tried with the substring but not works.. Any way?
The problem is that there are no spaces because you just replaced them all with "+" so if you want the user to write "bring me" (place name) than try this:
try {
String address = edit.getText().toString();
address = address.replace(" ","+");
address = address.substring(9);
Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:0,0?q="+address));
startActivity(i);
}
catch (Exception e){
}
This question already has answers here:
How do I trim a file extension from a String in Java?
(23 answers)
Closed 9 years ago.
I got confused with substring in android. in my database i have file pdf like this DOGMATIKA-3.pdf and i want to select the "pdf". ho to do it in android? i just want to select 3 last letters , anyone please help me, thank you. i already try with this code but got force close.
package mobile.download;
public class DownloadText extends Activity{
public Koneksi linkurl;
public Kondownload linkurl2;
String url;
String SERVER_URL;
String SERVER_URL2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linkdownload);
TextView mTextLink = (TextView) findViewById(R.id.LinkDownload);
Bundle bundle = this.getIntent().getExtras();
String param1 = bundle.getString("keyIdc");
String param2 = bundle.getString("keyReference");
if(param2.substring(-3, 0).equals("pdf"))
{
linkurl = new Koneksi(this);
SERVER_URL = linkurl.getUrl();
SERVER_URL += "/moodledata/"+param1+"/"+param2;
mTextLink.setText(SERVER_URL);
Pattern pattern = Pattern.compile(SERVER_URL);
Linkify.addLinks(mTextLink, pattern, "");
}
else
{
linkurl2 = new Kondownload(param2);
SERVER_URL2 = linkurl2.getUrl();
mTextLink.setText(SERVER_URL2);
Pattern pattern = Pattern.compile(SERVER_URL2);
Linkify.addLinks(mTextLink, pattern, "");
}
}
}
last 3 letters are length() - 3 to length() (the second parameter is implicitely length(), so it is not necessary)
param2.substring(params2.length() - 3)
however, you could use endsWith which is clearer :
param2.endsWith("pdf")
which does exactly that.
try param2.substring(param2.indexOf("."), param2.length()).equals("pdf") instead..
If you are intent on using .substring(), use string.substring(string.length()-3).
However, you can also use the .split() method like so:
String [] split = string.split(".");
This will create a new array excluding all instances of "." and using them as the array separators. In other words, if you called this .split() on your above string, you would get
{"DOGMATIKA-3","pdf"}
The latter method will work for file extensions that are not three characters.
i have file pdf like this DOGMATIKA-3.pdf and i want to select the
"pdf"
String test = "myPdf.pdf";
String extension = test.substring(test.lastIndexOf(".")+1, test.length());
Or you can just do :
String extension = test.substring(test.lastIndexOf(".")+1);
just use like that
String substr = param2.substring(param2.length() - 3);
if("pdf".equals(substr))
{
// use what you want
}