empty fields causing error "stopped unexpectedly" - java

Is there any way to predefine a value for strings in order not to have the error when any of the fields are empty?
All porcentagem 1, 2 and 3 are optional, so it's not the case to ask the user to input some data, but predefine values in order not to have the values. Beginner question.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cpc_inicial = (EditText) findViewById(R.id.cpc_inicial);
porcentagem1 = (EditText) findViewById(R.id.porcentagem1);
porcentagem2 = (EditText) findViewById(R.id.porcentagem2);
porcentagem3 = (EditText) findViewById(R.id.porcentagem3);
cpc_final = (TextView) findViewById(R.id.cpc_final);
botao1 = (Button) findViewById(R.id.botao1);
cpc_inicial.setInputType(InputType.TYPE_CLASS_NUMBER);
porcentagem1.setInputType(InputType.TYPE_CLASS_NUMBER);
porcentagem2.setInputType(InputType.TYPE_CLASS_NUMBER);
porcentagem3.setInputType(InputType.TYPE_CLASS_NUMBER);
botao1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(porcentagem3 != null ) {
float cpc = Float.parseFloat(cpc_inicial.getText().toString());
float v1 = Float.parseFloat(porcentagem1.getText().toString());
float v2 = Float.parseFloat(porcentagem2.getText().toString());
float v3 = Float.parseFloat(porcentagem3.getText().toString());
TextView cpcfinal = cpc_final;
if(cpc > 0.0 && v1 != 0.0 && v2 != 0.0 && v3 != 0.0 )
{
soma = (cpc*v1/100)+cpc;
soma = soma*(v2/100)+soma;
soma = soma*(v3/100)+soma;
String sum = Float.toString(soma);
cpcfinal.setText(sum);
}
} else
{
TextView cpcfinal = cpc_final;
soma = 0;
cpcfinal.setText("ops!"); }
}
});
}
Thanks

Every time a form is submitted, you should check whether each field has a proper value. For example, if you want to check weather an optional field has a value or not, you should do something like this:
String optionalText = optionalFieldName.getText().toString();
if (optionalText.equals("some expected value")) {
//Do something with the value here.
}
Of course, you would need to do something similar for every optional field, and really should also do the inverse for fields that are not option to be safe, and perhaps warn the user that the field is required, for example:
String text = fieldName.getText().toString();
if (text.equals("")) {
//field is empty, so warn the user that it is required.
}
If the value you are looking for should be numerical in nature, then you should do something like this:
String text = field.getText().toString();
if (!text.equals("")) {
//Field has at least some text in it.
try {
float val = Float.parseFloat(text);
}catch (NumberFormatException ex) {
//Enterered text was not a float value, so you should do something
// here to let the user know that their input was invalid and what you expect
}
//Do something with the value
}

Either add the values to your xml layout using the android:text="..." attribute or use TextUtils.isEmpty(...) to detect if the string is empty and assign a default value yourself.

Related

Getting Input From Generated EditText Android Kotlin

I'm making a random word generator and I'm having problems getting the input from the generated editText in Kotlin. I have found a few solutions in java and I can see how they work but I'm having trouble putting it into Kotlin.
I've set it up the so the EditTexts are generated by a while loop and the Id is stored in an array call "arraylist". I then wanted to use the Id in the array to obtain the "text" from each editText and put them into the "Strings" variable. I think in java you'd use "string[i]" so the variable becomes string1, string2 etc. I can't get this to work. I've tried printing the array and its blank so I don't think I'm getting the id correctly.
There are a few logic issues with code such as there already being an input that I'm using for formatting and arrays starting at 0 and such that I'll sort out later.
Thanks
Jake
class WordList : AppCompatActivity() {
#RequiresApi(Build.VERSION_CODES.M)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_word_list)
//Get Linear layout as variable
val linearLayout = findViewById(R.id.InfoLayout) as LinearLayout
val Test = findViewById(R.id.WordsInput) as EditText
val RandomiseButton = findViewById<Button>(R.id.RandomiseInputs) as Button
var Value = "Hello" as String
var editText = EditText (this)
var List = arrayListOf<String>()
var arraylist = ArrayList<Int>()
val strings = ArrayList<String>()
//Get Inputs from Previous page
var Choice = intent.getIntExtra("Amount", 0)
/*To Do
Get Inputs From Created Inputs
Randomise
Print output
*/
//Add new input
if (Choice >= 2) {
//Create Var for Edit
var Number = 2
//While loop to create multiple EditText fields
while (Number <= Choice) {
editText = EditText (this)
editText.hint = "Input " + Number
editText.setId(Number)
//Use Appearance To change things you can't set using style.xml
editText.setTextAppearance(R.style.TextHintFont)
editText.setTextColor(Color.parseColor("#E321C2"))
editText.setHintTextColor(Color.parseColor("#E321C2"))
editText.setEms(10)
//Set Edit
linearLayout.addView(editText)
arraylist.add(editText.id.toInt())
Number++
}
}
RandomiseButton.setOnClickListener {
var Random = (0..Choice).random()
var i = 0
while (i <= arraylist.size) {
strings.add(arraylist.get(i).text.toString())
i++
}
var OutputW = strings.get(Random).toString()
//Value = editText.text.toString()
var intent = Intent (this#WordList,WordsOutput::class.java)
intent.putExtra("RandomOut",OutputW)
startActivity(intent)
}
}
}
So I just worked it out
RandomiseButton.setOnClickListener {
var Random = (0..Choice).random()
var OutputW = linearLayout.getChildAt(Random) as EditText
var another = OutputW.text.toString()
var intent = Intent (this#WordList,WordsOutput::class.java)
intent.putExtra("RandomOut",another)
startActivity(intent)
}
I used the getChildAt to just randomly select a field.
more info here
https://www.i-programmer.info/programming/android/11415-android-programming-in-kotlin-layouts-and-autonaming-components.html?start=1
Only took me 3 days hahaha

How do I output an integer to an EditText view?

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;
}
}
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.
Based on some educated guesses on the types of your fields, the following should work, as TotalFood is probably a number:
FoodIncomeCounter.setText(String.valueOf(TotalFood));
getText() is a method on EditTexts but it doesn't work on numbers.

Create Dynamic alert dialog box with multiple options to select

When user clicks on location element then app populate alert dialog to select location , this locations are coming from php server open .Below is the code i have used.
Declaration
final String locations[] = new String[100];
final String locations_id[] = new String[100];
onPostExecute
jObj = new JSONObject(json);
JSONArray locations_resp = jObj.getJSONArray("Locations");
JSONArray manufacturer_resp = jObj.getJSONArray("Manufacturers");
for(int i=0;i<locations_resp.length();i++)
{
JSONObject c = locations_resp.getJSONObject(i);
int id = c.getInt("id");
String name = c.getString("title");
locations[i]=name;
locations_id[i]=id+"";
//Log.d("Locations","Id ="+id+" name = "+name );
}
onclick Event
location_ele.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Location");
builder.setItems(locations, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// the user clicked on colors[which]
location_ele.setText(locations[which]);
location=locations_id[which].toString();
}
});
builder.show();
}
});
Screen shot
Observe the screen. locations are coming randomly along with some null values there are only 4 locations coming from API.Please suggest me procedure how to create this locations list dynamically with out Null value please notice i have created Locations as fixed size array.
In your post execute you need a condition when looping on locations_resp that checks when a location is null or empty so you won't add it to your location array.
I would suggest to work with List instead of array so your listview matches the size of the datasource (for instance show a list of 2 locations instead a list of 10 locations where 8 are empty).
List<String> locations = new ArrayList<String>();
List<String> locationsId = new ArrayList<String>();
for (JSONObject c : locations_resp)
{
int id = c.getInt("id");
String name = c.getString("title");
if(name != null && name.length > 0)
{
locations.add(name);
locationsId.add(String.valueOf(id));
}
}
I'll also suggest to have a local Location representation instend of having 2 array so you can do something like :
List<Location> locations = new ArrayList<Location>();
for (JSONObject c : locations_resp)
{
int id = c.getInt("id");
String name = c.getString("title");
if(name != null && name.length > 0)
{
locations.add(new Location(name, id));
}
}
and work with the Location object.

printing error for an empty input

I am trying to do a calculator app for android where i take two inputs for 2 numbers and output the result along with the function it does(i.e. addition or subtraction...).
public void Add(View view)
{
float a=0,b=0,res=0;
EditText num1 = (EditText) findViewById(R.id.editText1);
EditText num2 = (EditText) findViewById(R.id.editText2);
TextView function = (TextView) findViewById(R.id.textView4);
TextView ans = (TextView) findViewById(R.id.textView5);
a=Float.parseFloat(num1.getText().toString());
b=Float.parseFloat(num2.getText().toString());
String str1 = Float.toString(a);
String str2 = Float.toString(b);
if(str1=="")
{
function.setText("Enter both Numbers");
ans.setText("");
return;
}
if(str2=="")
{
function.setText("Enter both Numbers");
ans.setText("");
return;
}
res=a+b;
String str = Float.toString(res);
function.setText("addition");
ans.setText(str);
}
so this is what i am doing. i take 2 inputs. convert them to float variables a and b. now my issue is if the user did not input an input and try for the solution, then i must produce some error saying 'enter both the numbers'. on doing it as above it's not working.
nor does it works in this manner
if(str1=='\0')
{
function.setText("Enter both Numbers");
ans.setText("");
return;
}
this produces error when the input is zero.
So please help how to identify if there is no input given and to produce the error at that time.
Put the test before converting to Float.
Your test need to be some thing like this:
if (num1.getText().toString().trim().isEmpty()){
// show error
}
Use:
if(str1==null || str1.trim().equals(""))

Creating multiple identical text verify listeners in eclipse-rcp/swt

I'm trying to validate the input of multiple text boxes (i.e. they should be a number), and found the useful code snippet below here.
However, if I have three text boxes (text, moreText and evenMoreText), how can I apply a verify listener with the same functionality to each, without having to repeat the (.addVerifyListener(new VerifyListener() {...) code three times?
I don't want to implement a switch statement or similar (to decide which text box to apply it to), I want something more generic (that I can perhaps make available for other classes to use in the future).
text.addVerifyListener(new VerifyListener() {
#Override
public void verifyText(VerifyEvent e) {
final String oldS = text.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try {
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
} catch (final NumberFormatException numberFormatException) {
// value is not decimal
e.doit = false;
}
}
});
Define the VerifyListener beforehand and get the actual Text from the VerifyEvent:
VerifyListener listener = new VerifyListener()
{
#Override
public void verifyText(VerifyEvent e)
{
// Get the source widget
Text source = (Text) e.getSource();
// Get the text
final String oldS = source.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try
{
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
}
catch (final NumberFormatException numberFormatException)
{
// value is not decimal
e.doit = false;
}
}
};
// Add listener to both texts
text.addVerifyListener(listener);
anotherText.addVerifyListener(listener);
If you want to use it in other places as well, create a new class:
public class MyVerifyListener implements VerifyListener
{
// The above code in here
}
and then use:
MyVerifyListener listener = new MyVerifyListener();
text.addVerifyListener(listener);
anotherText.addVerifyListener(listener);

Categories

Resources