PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label android-edittext. Show all posts
Showing posts with label android-edittext. Show all posts

Friday, October 28, 2022

[FIXED] How to check if Number TextEdit is empty?

 October 28, 2022     android, android-edittext, is-empty, kotlin     No comments   

Issue

so I have this problem where I am trying to make Random Number Generator app on android. Basically you set the minimum and the maximum number and then it randomly picks numbers between min and max. However my problem comes if the min or max TextEdit field is empty, the app crashes. I would like to display "X" on the screen. How to check if the field is empty or not? I am using kotlin and here is sample of my code. I am begginer so please do not flame me if the code is wrong :)

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


    val rollButton = findViewById<Button>(R.id.rollButton)
    val resultsTextView = findViewById<TextView>(R.id.resultsTextView)
    //val seekBar = findViewById<SeekBar>(R.id.seekBar)
    val min = findViewById<TextView>(R.id.number_min)
    val max = findViewById<TextView>(R.id.number_max)




    rollButton.setOnClickListener {

    if(min.text.toString().toInt()>= 0 && max.text.toString().toInt() <= 1000){
        val rand = Random.nextInt(min.text.toString().toInt(),max.text.toString().toInt()+1)
        resultsTextView.text = rand.toString()
    }
        else if(min.text.toString().isNullOrBlank()){
        resultsTextView.text = "X"


    }
        else{

        resultsTextView.text = "X"
    }

    }




}

}


Solution

To check if your EditText is empty use isNullOrEmpty(). This will check if your field is empty or is null, like the method name says. Here is an example:

val editTextString :String = editText.text.toString()
if(!editTextString.isNullOrEmpty()) //returns true if string is null or empty

There is another approach with TextUtils but since you are using Kotlin this approach is better.

EDIT:

You are doing this:

if(min.text.toString().toInt()>= 0 && max.text.toString().toInt() <= 1000){
        val rand = Random.nextInt(min.text.toString().toInt(),max.text.toString().toInt()+1)
        resultsTextView.text = rand.toString()
}

and here this line min.text.toString().toInt() is throwing you an exception. The reason for this is because currently min or max are empty String. So compailer can't format number from an String equals to "". You should do it like this:

if(!min.text.toString().isNullOrEmpty() && !max.text.toString().isNullOrEmpty() && min.text.toString().toInt()>= 0 && max.text.toString().toInt() <= 1000){
        val rand = Random.nextInt(min.text.toString().toInt(),max.text.toString().toInt()+1)
        resultsTextView.text = rand.toString()
}

I hope this works. If not, then take this into two IF statements like this:

if(min.text.toString().isNullOrEmpty() || max.text.toString().isNullOrEmpty() {
         resultsTextView.text = "X"
} else if(min.text.toString().toInt() >= 0 && max.text.toString().toInt() <= 1000) {
         val rand = Random.nextInt(min.text.toString().toInt(), max.text.toString.toInt()+1)
         resultsTextView.text = rand.toString()
}

The second approach is maybe an even better and cleaner version since you don't have to check for anything else later.



Answered By - SlothCoding
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 17, 2022

[FIXED] How do I output an integer to an EditText view?

 August 17, 2022     android-edittext, android-studio, java, output     No comments   

Issue

I have an EditText as input. I am trying to use it for output as well. I've tried the following:

FoodIncomeCounter.setText(TotalFood.getText().toString());

FoodIncomeCounter = Integer.parseInt(TotalFood.getText());

String FoodIncomeCounter = String.valueOf(TotalFood);

and nothing works. For the 1st and 2nd option the "getText()" cannot be resolved. Am I able to output to an EditText view, or do I need to make a separate TextView and output to that? Hopefully that all makes sense to you. My goal is to be able to use the FoodCampX and FoodUpgradeX variables to calculate the income and output that into FoodIncomeCounter variable/EditText view (which currently you can manually input). FoodIncomeCounter is an EditText view, FoodCampX and FoodUpgradeX and FoodIncome are integers, TotalFood is an integer. Thank you for teaching me.

Here is the code:

//to get from user input and into variable form
  
    FoodIncomeCounter = (EditText) findViewById(R.id.FoodIncomeCounter);
    IncomeSubmitButton = (Button) findViewById(R.id.IncomeSubmitButton);

    FoodCamp1Counter = (EditText) findViewById(R.id.FoodCamp1Counter);
    FoodCamp2Counter = (EditText) findViewById(R.id.FoodCamp2Counter);
    FoodCamp3Counter = (EditText) findViewById(R.id.FoodCamp3Counter);
    FoodUpgrade1Counter = (EditText) findViewById(R.id.FoodUpgrade1Counter);
    FoodUpgrade2Counter = (EditText) findViewById(R.id.FoodUpgrade2Counter);
    FoodUpgrade3Counter = (EditText) findViewById(R.id.FoodUpgrade3Counter);
    FoodCampSubmitButton = (Button) findViewById(R.id.FoodCampSubmitButton);

}

    //Buttons
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.IncomeSubmitButton:
                //reset to value
                FoodIncomeCounter.setText("");

                //receive the inputted values
                FoodIncome = Integer.parseInt(FoodIncomeCounter.getText().toString());
                break;
            case R.id.FoodCampSubmitButton:
                //reset to value
                FoodCamp1Counter.setText("");
                FoodCamp2Counter.setText("");
                FoodCamp3Counter.setText("");
                FoodUpgrade1Counter.setText("");
                FoodUpgrade2Counter.setText("");
                FoodUpgrade3Counter.setText("");

                //receive the inputted values
                FoodCamp1 = Integer.parseInt(FoodCamp1Counter.getText().toString());
                FoodCamp2 = Integer.parseInt(FoodCamp2Counter.getText().toString());
                FoodCamp3 = Integer.parseInt(FoodCamp3Counter.getText().toString());
                FoodUpgrade1 = Integer.parseInt(FoodUpgrade1Counter.getText().toString());
                FoodUpgrade2 = Integer.parseInt(FoodUpgrade2Counter.getText().toString());
                FoodUpgrade3 = Integer.parseInt(FoodUpgrade3Counter.getText().toString());

                //get food income and show
                TotalFood = FoodCamp1 + (FoodCamp2 * 2) + (FoodCamp3 * 3) + (FoodUpgrade1 * 2) + (FoodUpgrade2 * 4) + (FoodUpgrade3 * 6);

                //These 3 options are what iv tried and do not work
                FoodIncomeCounter.setText(TotalFood.getText().toString());
                FoodIncomeCounter = Integer.parseInt(TotalFood.getText());
                String FoodIncomeCounter = String.valueOf(TotalFood);
                //------------------------------------------------------
                break;
            default:
                break;
        }
    }

Solution

Change

FoodIncomeCounter.setText(TotalFood.getText().toString());

to

FoodIncomeCounter.setText(String.valueOf(TotalFood));

As getText() is a method on components like EditText, TextView, and not datatypes.



Answered By - unc0ded
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, August 11, 2022

[FIXED] How to limit values after decimal point in editText in android?

 August 11, 2022     android, android-edittext, android-studio, decimal, user-input     No comments   

Issue

I have built a BMI calculator. In the user input field, how do I limit the digits after decimal point? Here is my code:

package com.example.bmicalculator;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.text.DecimalFormat;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public double roundTwoDecimals(double d){

        DecimalFormat roundOff = new DecimalFormat("#.##");
        return Double.valueOf(roundOff.format(d));
    }

    public void buttonClicked(View v){

        EditText editTextHeight = findViewById(R.id.userHeight);
        EditText editTextWeight = findViewById(R.id.userWeight);

        TextView textViewResult = findViewById(R.id.userBMI);

        double height = Double.parseDouble(editTextHeight.getText().toString());
        double weight = Double.parseDouble(editTextWeight.getText().toString());

        double BMI = weight / (height * height);

        double cBMI = roundTwoDecimals(BMI);

        textViewResult.setText(Double.toString(cBMI));

        editTextHeight.setText("");
        editTextWeight.setText("");

    }
}

Please don't mark it as a duplicate. I've already tried all methods which are there in the StackOverflow but none of them worked for me.

I have used the below method

    InputFilter filter = new InputFilter() {

        final int maxDigitsBeforeDecimalPoint = 4;
        final int maxDigitsAfterDecimalPoint = 1;

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dStart, int dEnd) {

            StringBuilder builder = new StringBuilder(dest);
            builder.replace(dStart, dEnd, source.subSequence(start, end).toString());

            if(!builder.toString().matches(
                    "(([1-9]{1})([0-9]{0,"+(maxDigitsBeforeDecimalPoint-1)+"})?)?(\\.[0-9]{0,"+maxDigitsAfterDecimalPoint+"})?")){

                if(source.length() == 0){
                    return dest.subSequence(dStart, dEnd);
                }
                return "";
            }
            return null;
        }
    };

and in editText

editTextHeight.setFilters(new InputFilter[]{filter});
editTextWeight.setFilters(new InputFilter[]{filter});

Solution

You can use TextWatcher.afterTextChanged() to alter the entered text.



Answered By - Ridcully
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 30, 2022

[FIXED] How to prevent user from entering zero as an input?

 July 30, 2022     android, android-edittext, validation     No comments   

Issue

I'm trying to add input validation to a set of three EditTexts, that the user enters numeric values into. The problem I'm facing is for the calculation to work the user can't enter zero as one of the input fields or the application will crash.

I tried to implement the following to prevent zero from being entered and show a warning message. I get an error stating "unable to start activity calcResult" which is the activity that shows the calculation.

This is the link to the error log: http://pastebin.com/hDsabjR6

I understand from this that the zero value is still slipping through the validation but I don't know why?

 String getoffsetlength = offsetLength.getText().toString(); 

 if (getoffsetlength.trim().equals('0')) {

     Toast.makeText(this, "Enter number greater than 0!", Toast.LENGTH_SHORT).show();
     return;
   }

The application crashes when I have used this validation in the app. Any ideas as to where I have messed up with this implementation?


Solution

Just add android:digits="123456789" to the EditText in XML. This way the user won't be able to input 0

[EDIT]

However, if you want to avoid the user from entering 0 only at the beginning, then use this:

code_text.addTextChangedListener(new TextWatcher(){
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                if (code_text.getText().toString().matches("^0") )
                {
                    // Not allowed
                    Toast.makeText(context, "not allowed", Toast.LENGTH_LONG).show();
                    code_text.setText("");
                }
            }
            @Override
            public void afterTextChanged(Editable arg0) { }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        }); 


Answered By - Joel Fernandes
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, July 29, 2022

[FIXED] How to add multiple image into EditText using spannable or any other way?

 July 29, 2022     android-edittext, image, spannablestringbuilder     No comments   

Issue

I am creating a note taking app, I have done text section and its working properly. Also database working properly. But I want to add image in the EditText. When user add an image, it will place at the EditText cursor position and this task will happen for multiple image. And save the EditText entities (text and image) in SQL Lite database.

Please help someone to do this job. Thank you.

I have tried this job in onActivityResult , but image are not showing

if(requestCode==1 && resultCode==RESULT_OK && data!=null) {
    Uri imageUri= data.getData();
    try {
        InputStream inputStream= getContentResolver().openInputStream(imageUri);
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        final Drawable drawable = new BitmapDrawable(getResources(), bitmap);
        final ImageSpan imageSpan = new ImageSpan(drawable,ImageSpan.ALIGN_BOTTOM);
        Spannable span = new SpannableStringBuilder(editText.getText().toString()+"\n");
        span.setSpan(imageSpan, 0, 0, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        editText.append(span, 0, ("\n").length());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

Solution

You are replacing zero characters when you do the following:

span.setSpan(imageSpan, 0, 0, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

You will need to replace at least one character. Since you are inserting an ImageSpan, you will need to add at least one character to replace.

ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BOTTOM);
Editable editable = editText.getText();
// Insert a single space to replace.
editable = editable.insert(0, " ");
editable.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
editText.setText(editable);


Answered By - Cheticamp
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing