I want to use if statement in android studio but without using setText
dayText.setText(forecast.getDay());
if (forecast.getDay().equals("Mon")){
dayText.setText("السبت");
}else if (forecast.getDay().equals("Tue")){
dayText.setText("الاحد");
}else if (forecast.getDay().equals("Wed")){
dayText.setText("الاثنين");
}else if (forecast.getDay().equals("Thu")){
dayText.setText("الثلاثاء");
}else if (forecast.getDay().equals("Fri")){
dayText.setText("الاربعاء");
}else if (forecast.getDay().equals("Sat")){
dayText.setText("الخميس");
}else if (forecast.getDay().equals("Sun")){
dayText.setText("الجمعة");
}
if there is any example
I can't get what you are looking to do but first initialize the String as public String getDay; after you can check the if statement like, if you add more code maybe i can help you more.
if(getDay.equals("Mon")) {
/** do something **/
}
getDay = day;
Is this what you want
public String getDay() {
if (getDay().equals("Mon")){
Log.e("Success","Mon");
}
return;
}
If I understood, what you want is not to have so many setTexts? This will work for that purpose.
String finalText = "";
if (forecast.getDay().equals("Mon")){
finalText = "السبت";
}else if (forecast.getDay().equals("Tue")){
finalText = "الاحد";
}else if (forecast.getDay().equals("Wed")){
finalText = "الاثنين";
}else if (forecast.getDay().equals("Thu")){
finalText = "الثلاثاء";
}else if (forecast.getDay().equals("Fri")){
finalText = "الاربعاء";
}else if (forecast.getDay().equals("Sat")){
finalText = "الخميس";
}else if (forecast.getDay().equals("Sun")){
finalText = "الجمعة";
}
dayText.setText(finalText);
Related
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 1 year ago.
Hello I am making an app where user can order some books. When he, or she, fill out the order with his firs second name etc and hits order button applications,using Intent, will switch to SMS and thus will purchase books via text message.But i wish to be able, if user accidently forget to fill up all fields, toast pop up with message "Please fill up XYZ field". I used if else, but when some field remain empty something else happened.I got android message that my app needs to be closed and and return me to the previous activity.In my LogCat nothing happened . No error message.
this is my code :
public void kreiranjeNarudzbine(View v) {
EditText editTextIme = (EditText) findViewById(R.id.ime);
String imeNarucioca = editTextIme.getText().toString();
EditText editTextPrezime = (EditText)findViewById(R.id.prezime);
String prezimeNarucioca = editTextPrezime.getText().toString();
EditText editTelefonNarucioca = (EditText)findViewById(R.id.telefon);
String telefonNarucioca = editTelefonNarucioca.getText().toString();
EditText editAdresaNarucioca = (EditText)findViewById(R.id.adresa);
String adresaNarucioca = editAdresaNarucioca.getText().toString();
EditText editGradNarucioca = (EditText)findViewById(R.id.grad);
String gradNarucioca = editGradNarucioca.getText().toString();
EditText editKolicina = (EditText)findViewById(R.id.kolicina);
String narucenaKolicina = editKolicina.getText().toString();
int kolicina = Integer.parseInt(narucenaKolicina);
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", "+381629647169");
smsIntent.putExtra("sms_body",poruka);
if(imeNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Unesite ime", Toast.LENGTH_LONG).show();
}
else if(prezimeNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite Prezime", Toast.LENGTH_LONG).show();
}
else if(telefonNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite kontakt telefon", Toast.LENGTH_LONG).show();
}
else if(adresaNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite adresu",Toast.LENGTH_LONG).show();
}
else if(gradNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Navedite grad", Toast.LENGTH_LONG).show();
}
else if(narucenaKolicina.equals("")){
Toast.makeText(Narudzbina.this, "Navedite zeljenu kolicinu", Toast.LENGTH_LONG).show();
}
else{
startActivity(smsIntent);}
}
As already mentioned, you check to make sure it isn't null or empty.
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);
}
This can be converted into a method to prevent as much text:
public boolean isETEmpty(EditText et){
return (et != null && (et.equals("") || et.equals(" ")));//the final piece checks if the edittext is empty or just contains a space. It is or between
//in order to ensure that one of those are true. Thus the parenthesis
}
(how the above works)
Now, for the required fields you can use HTML to format the text:
/*your view*/.setText(Html.fromHtml("Your title. <font color='red'>*</font>"));
The above code formats the code by adding a red star after the required fields. Later down you can do this:
/*your view*/.setText(Html.fromHtml("<font color='red'>*</font> Required field"));
The comment /*your view*/ you replace with a textview reference, edittext or whatever you use to set text
Further reading:
https://stackoverflow.com/a/9161958/6296561
The string of empty edittext might be null, which causes the issue. Try the following code.
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);}
}
You should use isEmpty method provided in android.text.TextUtils. The whole description and implement of this method:
/**
* Returns true if the string is null or 0-length.
* #param str the string to be examined
* #return true if str is null or zero length
*/
public static boolean isEmpty(#Nullable CharSequence str) {
if (str == null || str.length() == 0)
return true;
else
return false;
}
So, to validate null or empty user input, you can do something like this:
if(android.text.TextUtils.isEmpty(imeNarucioca)){
// ...
}
So i'm using this, you can do with it what you like:
This is the method:
public static boolean checkEditTextIsEmpty(EditText... editTexts)
{
try
{
for (EditText editText : editTexts)
{
if (editText.getText().toString().trim().length() == 0)
{
Drawable d = _application.currentActivity.getResources().getDrawable(android.R.drawable.ic_dialog_alert);
d.setBounds(0, 0, d.getIntrinsicWidth()/2, d.getIntrinsicHeight()/2);
editText.requestFocus();
editText.setError(editText.getHint() + " is empty", d);
return false;
}
}
}
catch (Exception ignored)
{
return false;
}
return true;
}
This is a preview: (ignore my style and background)
This is how i implemented it:
if(checkEditTextIsEmpty(txtEmail, txtPassword))
{
//Do whatever if EditTexts is not empty
}
Just add this line in your Java file pro-grammatically,
adding mandatory field near Your Text view.
tv.setText (Html.fromHtml(YourText
+ " <font color='"
+ getResources().getColor(R.color.colorAccent) + "'>" + " * "
+ "</font>"));
add Required field instead of yourText field,
then use the required color from colors.xml
I am trying to make somekind of version checker for my application.
The idea is to compare the numbers from 2 strings and if 1 set of numbers is bigger then the other a new version has been found.
oldString = 360 some - File v1.52.876 [build 2546]
newString = 360 some - File v1.53.421 [build 2687]
What I need is to compare the set numbers after the 'v' in both strings as there can also be numbers (360) in front of the file, as shown in above example.
Below method checks an arraylist (loadTrackedItems) which contains the files to be checked agains the newly received item (checkItemTrack).
But I am having trouble getting the correct numbers.
Is there a better way to do this?, could somebody be so kind and help a bit.
Thank you in advance.
public static boolean newTrackedVersion(String checkItemTrack) {
final List<String> tracking = new ArrayList<String>(loadTrackedItems);
boolean supported = false;
for (final String u : tracking) {
if (checkItemTrack.contains(u)) {
supported = true;
// get the index of the last 'v' character
int trackindex = checkItemTrack.lastIndexOf("v");
String newItem = checkItemTrack.replaceAll("[a-zA-Z]", "").replace("\\s+", "")
.replaceAll("[-\\[\\]^/,'*:.!><~##$%+=?|\"\\\\()]+", "");
String inList = u.replaceAll("[a-zA-Z]", "").replace("\\s+", "")
.replaceAll("[-\\[\\]^/,'*:.!><~##$%+=?|\"\\\\()]+", "");
long newTrack = Long.parseLong(newItem.trim());
long inTrackList = Long.parseLong(inList.trim());
if (newTrack > inTrackList) {
//Toast.makeText(context,"New version found: " + checkItemTrack, Toast.LENGTH_LONG).show();
Log.w("NEW VERSION ", checkItemTrack);
Log.w("OLD VERSION ", u);
}
break;
}
}
return supported;
}
if you receive only two strings to compare this solution will work try it.
String oldString = "360 some - File v1.52.876 [build 2546]";
String newString = "360 some - File v1.53.421 [build 2687]";
String oldTemp = oldString.substring(oldString.indexOf('v'), oldString.indexOf('[')).trim();
String newTemp = newString.substring(newString.indexOf('v'), newString.indexOf('[')).trim();
int res = newTemp.compareTo(oldTemp);
if(res == 1){
//newString is higher
}else if(res == 0){
//both are same
}else if(res == -1){
//oldString is higher
}
i need to change the text="font roboto regular" to Font Roboto Regular in xml itself, how to do?
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="18sp"
android:textColor="#android:color/black"
android:fontFamily="roboto-regular"
android:text="font roboto regular"
android:inputType="textCapWords"
android:capitalize="words"/>
If someone looking for kotlin way of doing this, then code becomes very simple and beautiful.
yourTextView.text = yourText.split(' ').joinToString(" ") { it.capitalize() }
You can use this code.
String str = "font roboto regular";
String[] strArray = str.split(" ");
StringBuilder builder = new StringBuilder();
for (String s : strArray) {
String cap = s.substring(0, 1).toUpperCase() + s.substring(1);
builder.append(cap + " ");
}
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(builder.toString());
Try this...
Method that convert first letter of each word in a string into an uppercase letter.
private String capitalize(String capString){
StringBuffer capBuffer = new StringBuffer();
Matcher capMatcher = Pattern.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(capString);
while (capMatcher.find()){
capMatcher.appendReplacement(capBuffer, capMatcher.group(1).toUpperCase() + capMatcher.group(2).toLowerCase());
}
return capMatcher.appendTail(capBuffer).toString();
}
Usage:
String chars = capitalize("hello dream world");
//textView.setText(chars);
System.out.println("Output: "+chars);
Result:
Output: Hello Dream World
KOTLIN
val strArrayOBJ = "Your String".split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val builder = StringBuilder()
for (s in strArrayOBJ) {
val cap = s.substring(0, 1).toUpperCase() + s.substring(1)
builder.append("$cap ")
}
txt_OBJ.text=builder.toString()
Modification on the accepted answer to clean out any existing capital letters and prevent the trailing space that the accepted answer leaves behind.
public static String capitalize(#NonNull String input) {
String[] words = input.toLowerCase().split(" ");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (i > 0 && word.length() > 0) {
builder.append(" ");
}
String cap = word.substring(0, 1).toUpperCase() + word.substring(1);
builder.append(cap);
}
return builder.toString();
}
you can use this method to do it programmatically
public String wordFirstCap(String str)
{
String[] words = str.trim().split(" ");
StringBuilder ret = new StringBuilder();
for(int i = 0; i < words.length; i++)
{
if(words[i].trim().length() > 0)
{
Log.e("words[i].trim",""+words[i].trim().charAt(0));
ret.append(Character.toUpperCase(words[i].trim().charAt(0)));
ret.append(words[i].trim().substring(1));
if(i < words.length - 1) {
ret.append(' ');
}
}
}
return ret.toString();
}
refer this if you want to do it in xml.
You can use
private String capitalize(final String line) {
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
refer this How to capitalize the first character of each word in a string
android:capitalize is deprecated.
Follow these steps: https://stackoverflow.com/a/31699306/4409113
Tap icon of ‘Settings’ on the Home screen of your Android Lollipop
Device
At the ‘Settings’ screen, scroll down to the PERSONAL section and
tap the ‘Language & input’ section.
At the ‘Language & input’ section, select your keyboard(which is
marked as current keyboard).
Now tap the ‘Preferences’.
Tap to check the ‘Auto – Capitalization’ to enable it.
And then it should work.
If it didn't, i'd rather to do that in Java.
https://stackoverflow.com/a/1149869/2725203
Have a look at ACL WordUtils.
WordUtils.capitalize("your string") == "Your String"
Another approach is to use StringTokenizer class. The below method works for any number of words in a sentence or in the EditText view. I used this to capitalize the full names field in an app.
public String capWordFirstLetter(String fullname)
{
String fname = "";
String s2;
StringTokenizer tokenizer = new StringTokenizer(fullname);
while (tokenizer.hasMoreTokens())
{
s2 = tokenizer.nextToken().toLowerCase();
if (fname.length() == 0)
fname += s2.substring(0, 1).toUpperCase() + s2.substring(1);
else
fname += " "+s2.substring(0, 1).toUpperCase() + s2.substring(1);
}
return fname;
}
in kotlin, string extension
fun String?.capitalizeText() = (this?.toLowerCase(Locale.getDefault())?.split(" ")?.joinToString(" ") { if (it.length <= 1) it else it.capitalize(Locale.getDefault()) }?.trimEnd())?.trim()
Kotlin extension function for capitalising each word
val String?.capitalizeEachWord
get() = (this?.lowercase(Locale.getDefault())?.split(" ")?.joinToString(" ") {
if (it.length <= 1) it else it.replaceFirstChar { firstChar ->
if (firstChar.isLowerCase()) firstChar.titlecase(
Locale.getDefault()
) else firstChar.toString()
}
}?.trimEnd())?.trim()
As the best way for achieving this used to be the capitalize() fun, but now it got depricated in kotlin. So we have an alternate for this. I've the use case where I'm getting a key from api that'll be customized at front end & will be shown apparently. The value is coming as "RECOMMENDED_OFFERS" which should be updated to be shown as "Recommended Offers".
I've created an extension function :
fun String.updateCapitalizedTextByRemovingUnderscore(specialChar: String): String
that takes a string which need to be replaced with white space (" ") & then customise the words as their 1st character would be in caps. So, the function body looks like :
fun String.updateCapitalizedTextByRemovingUnderscore(
specialChar: String = "") : String {
var tabName = this
// removing the special character coming in parameter & if
exist
if (spclChar.isNotEmpty() && this.contains(specialChar)) {
tabName = this.replace(spclChar, " ")
}
return tabName.lowercase().split(' ').joinToString(" ") {
it.replaceFirstChar { if (it.isLowerCase())
it.titlecase(Locale.getDefault()) else it.toString() } }
}
How to call the extension function :
textView.text =
"RECOMMENDED_OFFERS".updateCapitalizedTextByRemovingUnderscore("_")
OR
textView.text = <api_key>.updateCapitalizedTextByRemovingUnderscore("_")
The desired output will be :
Recommended Offers
Hope this will help.Happy coding :) Cheers!!
capitalize each word
public static String toTitleCase(String string) {
// Check if String is null
if (string == null) {
return null;
}
boolean whiteSpace = true;
StringBuilder builder = new StringBuilder(string); // String builder to store string
final int builderLength = builder.length();
// Loop through builder
for (int i = 0; i < builderLength; ++i) {
char c = builder.charAt(i); // Get character at builders position
if (whiteSpace) {
// Check if character is not white space
if (!Character.isWhitespace(c)) {
// Convert to title case and leave whitespace mode.
builder.setCharAt(i, Character.toTitleCase(c));
whiteSpace = false;
}
} else if (Character.isWhitespace(c)) {
whiteSpace = true; // Set character is white space
} else {
builder.setCharAt(i, Character.toLowerCase(c)); // Set character to lowercase
}
}
return builder.toString(); // Return builders text
}
use String to txt.setText(toTitleCase(stringVal))
don't use android:fontFamily to roboto-regular. hyphen not accept. please rename to roboto_regular.
To capitalize each word in a sentence use the below attribute in xml of that paticular textView.
android:inputType="textCapWords"
I am trying to validate my mobile number which I am picking up from Contac List but the problem is that it is picking contact like +91 95 xx xxxxxx and there is space between numbers so the validation is not happening.
For now I am using this validation
String Mobile = "^[+]?[01]?[- .]?(\\([2-]\\d{2}\\)|[2-9]\\d{2})[- .]?\\d{3}[- .]?\\d{4}$";
But it's a failure.
Any help is appreciable.
Thank you.
In android sdk One class is there PhoneNumberUtils by using that class you can validate your phone number:
check the documentation link here
Replace the spaces then validate..
String phone=phone.replace(" ","");
Now the String phone has the text without spaces and you can compare.
Just try this.
String number = " " //Your mobile number
number.replaceAll("[^+\\d]|(?<=.)\\+", ""));
This will remove all the spaces, (, ) symbols
you can use below code :
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
try
{
if (phoneNumber != null)
phoneNumber = extractDigits(phoneNumber);
}
catch (Exception e)
{
e.printStackTrace();
}
where extractDigits() method is as :
public static String extractDigits(String src)
{
StringBuilder builder = new StringBuilder();
String firstchar = src.substring(0, 1);
for (int i = 0; i < src.length(); i++)
{
char c = src.charAt(i);
if (Character.isDigit(c) || firstchar.equals("+"))
{
firstchar = "";
builder.append(c);
}
}
return Checkvalidnumber(builder.toString());
}
where Checkvalidnumber() method is as :
public static String Checkvalidnumber(String number)
{
String validnumber = "";
String Countrycode = chatPrefs.getString("countryCode", "");
if (number.startsWith("+"))
{
validnumber = number.trim();
}
else if (number.startsWith("0"))
{
validnumber = (Countrycode + number.substring(1, number.length())).trim();
}
else
{
validnumber = (Countrycode + number).trim();
}
return validnumber;
}
You should try the following to remove the white spaces and then you can do the validation.
var str = "PB 10 CV 2662";
str = str.replace(/ +/g, "");
I'm new android/java programmer and I can't find anywhere how to set default varriable value only on first call. My console log delete after second call. My code looks like:
public class Ftp {
[...]
//Console
String console_strings[] = new String [15];
int console_line = 0;
//
[...]
public void drawConsole(String msg){
CharSequence time = DateFormat.format("hh:mm:ss", d.getTime());
String message = "["+time+"] "+msg;
TextView console = (TextView)((Activity)context).findViewById(R.id.console);
String newString = "";
for(int i = 0; i < console_strings.length; i++){
if(console_strings[i] != null)
newString += console_strings[i] + "\n";
else
{
console_strings[i] = message;
newString += console_strings[i] + "\n";
break;
}
}
console.setText(newString);
}
}
Whenever I want to add something to the console, it delete old text value.
There are multiple ways to do this. The problem you are having is that you are setting the entire textview's text at once. You could do one of a few things. You could do
console.setText(console.getText() + newString);
or
console.append(newString);
Both of these would work. There are multiple other ways, but those should do it for you.
TextView has also an append method