My App Stops When I Try To Get An Int - java

I'm trying to make an app that accepts an input and automatically changes it to an int. However, when it tries to obtain an int, the app automatically stops. Below is the full code...
public class MainActivity extends Activity implements OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button calculate = (Button)findViewById(R.id.calculateTip);
calculate.setOnClickListener(this);
}//end onCreate
public void onClick(View v) {
EditText money = (EditText)findViewById(R.id.bill);
int bill = Integer.parseInt(money.getText().toString());
money.setText("Event Processed");
}//end onClick
}//end MainActivity

I suspect that the application is stopping because the value you are trying to parse is not really an integer. You should throw that code into a try catch.
ie:
public void onClick(View v) {
EditText money;
try
{
money = (EditText)findViewById(R.id.bill);
// This check makes sure that the EditText is returning the correct object.
if(money != null)
{
int bill = Integer.parseInt(money.getText().toString());
money.setText("Event Processed");
}
}
catch(NumberFormatException e)
{
// If we get in here that means the inserted value was not an Integer. So do something.
//ie:
money.setText("Please enter a value amount" );
}
}//end onClick
Regardless, you should have this code in a try catch to maintain data integrity.
Hopefully this helps!
Cheers.

Are you sure that the Object is an instance of EditText and that it isn't null?

Related

How can a Double.parseDouble crash my app?

I'm learning java and i have found a great tutorial on youtube, when trying to addapt it for my needs, i came to this problem:
I need to turn a string into a double, do some math, and fill a TextView with the result.
Also, it would be nice, if i could get that data from the firebase database (which my code does in another activity).
Now, i've abandoned the ideea of getting the data from the dtb because the app crashes everytime i open the activity, after i added the try, catch, finally, it doenst crash, but the activity is blank and no error is being displayed.
Tried eliminating row by row, to see where the problem is, but the app still crashes, even if one row is being left in.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText sup = findViewById(R.id.etSup);
EditText emi = findViewById(R.id.etEmi);
EditText ver = findViewById(R.id.etVer);
EditText abs = findViewById(R.id.etAbs);
TextView ResultTextView = findViewById(R.id.tvResult);
TextView Car = findViewById(R.id.tvCar);
Double dsup = Double.parseDouble(sup.getText().toString());
Double demi = Double.parseDouble(emi.getText().toString());
Double dver = Double.parseDouble(ver.getText().toString());
Double dabs = Double.parseDouble(abs.getText().toString());
Double CE = dsup * demi;
ResultTextView.setText("Total emissions are " + CE);
Double PS = dver * dabs;
Double Total = CE - PS;
Car.setText("Emission balance is " + Total);
}
});
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
No error messages have been seen
Try putting the entirety of the onClick() method in a try/catch block. By the time a parseDouble() method throws an exception, you are no longer in the onCreate() method because all you are doing in onCreate() is registering a listener. The onClick() method runs later on
I'm not sure what exception you might be getting from your parseDouble calls (could be many things, nullpointer perhaps?) but this change will allow you to find out.
In case I'm not explaining myself very well:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
// do things
} catch (Throwable e) {
e.printStackTrace();
throw e;
}
}
}
Edit: Changed catching 'Exception' to 'Throwable' just to be sure we don't miss anything (as a side note, you really shouldn't catch a Throwable except for debugging, which is why I've thrown it on again)

How can I use a double between two classes?

I want to build a currency calculator.
There is a plain text and a button.
if somebody scribe a number in the plain text and press the button a dialog will be shown.
BUT the number of the plaintext is everytime 2.1311!
here is my code
//this is the Main Activity
public class MainActivity extends AppCompatActivity {
public void PesoInEuro (View view){
EditText Peso = findViewById(R.id.EuroBetrag);
String amountPeso = Peso.getText().toString();
double amountPesodouble = Double.parseDouble(amountPeso);
double amountEurodouble = amountPesodouble * 46.85;
String amountEuro = String.valueOf(amountEurodouble);
Button buttonOne = (Button) findViewById(R.id.PesoEuro);
buttonOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialog();
}
});
}
public void openDialog(){
DiaPesoEuro exampleDialog = new DiaPesoEuro();
exampleDialog.show(getSupportFragmentManager(), "example Dialog");
}
First of all, it's a good practice to find your views in the OnCreate method.
Secondly, you have read and calculate your values when the user hit the button.
In the code above, you got the data in the PesoInEuro, and when the user presses the button, it shows the retrieved data and your calculation is based on them.

How to allow EditText to be empty and show setError message?

For many days now, I have been struggling to understand why the help that I found online didn't solve my issue, so I thought my best bet would be to ask here.
As a side note, I'm aware that my variable names aren't the best,and I am in general a newbie when it gets to Android development, but I think I can understand and I'm able sort issues fairly easily - except perhaps this thing.
I'm creating a simple app that allows me to get the total of profits of an item sold, so it would take the shipping price into consideration and do the calculation automatically. For this, when the shipping price would be left empty (blank), I would want to return a message saying it can't be empty, and a '0' must be entered to do the calculation. (My EditText field only allows numbers to be entered)
public class MainActivity extends AppCompatActivity {
double shippingNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
shippingPrice = (EditText) findViewById(R.id.shippingPrice);
}
calculateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
shippingNum = Integer.parseInt(shippingPrice.getText().toString());
if(shippingPrice.getText().toString().equals("") ||
shippingPrice.getText().length() == 0){
//shippingPrice.setText("0");
shippingPrice.setError("You can't leave this field empty! Enter something!");
}
I have also tried other variations such as:
if(TextUtils.isEmpty(shippingPrice.getText().toString().trim())){
shippingPrice.setError("You can't leave this field empty! Enter something!");
shippingPrice.setText("0");
}
But none of these seem to have allow me to leave the field empty without crashing. I've tried a dozen of different methods which I have realised that they were a waste of time as they wouldn't work - at least I've learned where I can use them.
Any help is much appreciated and thank you.
You could try just doing, check the length of the edit text, if zero display a toast saying enter more if not do the next part of the program:
if(getText().length() == 0){
Toast.makeText(getActivity(), "Enter values into field!",
Toast.LENGTH_LONG).show();
}
else{
// continue with the desired function of the program
}
Add this below method in your class :
public static boolean checkBlankValidation(EditText editText) {
if (TextUtils.isEmpty(editText.getText().toString().trim())) {
return false;
} else {
return true;
}
}
And call this method like below :
if (!checkBlankValidation(shippingPrice)) {
shippingPrice.requestFocus();
Toast.makeText(this, "Field should not be empty", Toast.LENGTH_SHORT).show();
return false;
} else {
return true;
}
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = findViewById(R.id.edittext);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().trim().length() <= 0) {
editText.setError("This Field is required");
editText.requestFocus();
} else
editText.setError(null);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}

Android: Wait for button click

I have to implement a return method of a class. So the structure is as simple as
public boolean yesNo(String message){
//return something
}
The problem here is that there is an EditText object and a Button and I want return a boolean depending on the answer entered by the User in the EditText. So naturally I have to wait for the user to write and click the Button when he finishes. I already tried setting up an onClicklistener inside the method but then I would not be able to pass anything to the outer method.
I know that in android everything is asynchronous so I you are not supposed to wait for the user to do something but in this case I have no other idea. Also FYI the method that I'm implementing is of the UserInfo class of the Jsch library. From what i understood this UserInfo is designed for user interaction so I figured it would somehow manage "prompt" the user by calling the yesNo method and then "wait" for the user to react. Any ideas? Also I would be happy if anyone would explain to me if there is some error in my logic. Im not quite confident in using AsynTask or runnables but I think its got something to do with this.
The only available documentation of UserInfo class
Thanks a lot!
EDIT: code so far:
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {
public Button goButton = (Button) MainActivity.contentView.findViewById(R.id.startSSH);
public EditText editText = (EditText) MainActivity.contentView.findViewById(R.id.commandSSH);
public boolean yesNo = false;
public boolean promptYesNo(String str) {
goButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String answer = editText.getText().toString();
if(answer.equals("yes")){yesNo = true;}
else {yesNo = false;}
}
});
return yesNo;
}
}
Put an OnClickListener on the Button when the screen is initialized, for example at onCreate lifecycle method. At the listener's onClick method you can call the yesNo method with the EditText content.
Try this way at the screen's onCreate method:
mButton = (Button)findViewById(R.id.my_button);
mEditText = (EditText) findViewById(R.id.my_edittext);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
yesNo(mEditText.getText().toString());
}
});
I already tried setting up an onClicklistener inside the method but
then i would not be able to pass anything to the outer method.
What do you want to pass to the outer method? You can create class variables to make it available inside the whole class.
The promptYesNo method:
public void promptYesNo(String s) {
if(s.equals("Yes") //do something
else if(s.equals("No") //do something
}
Change your code this way:
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {
public Button goButton = (Button) MainActivity.contentView.findViewById(R.id.startSSH);
public EditText editText = (EditText) MainActivity.contentView.findViewById(R.id.commandSSH);
goButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
if (prompt) {
promptYesNo(editText.getText().toString());
}
}
});
}

How to get last outgoing call in Android

I'm working with an app that uses Android Intent class to make calls.
I can successfully create a call to a number so that is working.
What I want now is to show the last outgoing call number to show in a TextView.
Also I made that TextView to be clickable so by a click I can redial the number.
I'm using CallLog.Calls.getLastOutgoingCall(getApplicationContext()); to get the last called number.
This works only once in my application.
I start the application, enter a number and it makes a call. The first outgoing called number I set in the TextView. After that I enter a second number which is successfully set in the TextView but when I click to redial the app calls the first number!
Why is that?
My last outgoing number is the second.
Why is it calling the first number?
Also if I restart the app then it redials the second outgoing number.
Here is my code:
public class MainActivity extends ActionBarActivity {
Button btnCall;
TextView number;
EditText calledNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCall = (Button) findViewById(R.id.button);
number = (TextView) findViewById(R.id.textView2);
calledNumber = (EditText) findViewById(R.id.editText);
//Gets the last outgoing number from the call log
final String lastCalledNumber = CallLog.Calls.getLastOutgoingCall(getApplicationContext());
btnCall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String TheNumber = calledNumber.getText().toString();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + TheNumber));
startActivity(callIntent);
number.setText(TheNumber);
}
});
//redial number in TextView by click
number.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent call = new Intent(Intent.ACTION_CALL);
call.setData(Uri.parse("tel:" + lastCalledNumber));
startActivity(call);
}
});
}
}
Per the activity lifecycle, onCreate() is only called once and does not run each time your app appears - this would mean that your getLastOutgoingCall() would be correct the first time but wouldn't necessarily work the second time.
If you'd like to run something every time the activity appears, you should move it to onResume() - this ensures it will always be up to date:
String lastCalledNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Same except without the `getLastOutgoingCall()`
}
#Override
public void onResume() {
lastCalledNumber = CallLog.Calls.getLastOutgoingCall(this);
}

Categories

Resources