I'm developing an app for android, and currently the only thing it does is calculate grades. There's two input boxes, one that takes the current grade, and another that takes a possible exam grade, and then it tells you the final grade. However, when there is no value in at least one of those boxes, it crashes. I tried to make an if statement to detect if the final value was null, but that didn't work. Here's my code:
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText grade = (EditText) findViewById(R.id.grade1);
EditText exam = (EditText) findViewById(R.id.grade2);
String stringGrade = (grade.getText().toString());
String stringExam = (exam.getText().toString());
double finalResult = (Double.parseDouble(stringGrade) * .8) + (Double.parseDouble(stringExam) * 0.2);
String finalResultString = String.valueOf(finalResult);
if (finalResultString == null){
finalResultString = "0";
} else {
intent.putExtra(EXTRA_MESSAGE, finalResultString);
startActivity(intent);
}}
and here's the code that renders it:
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView1 = new TextView(this);
textView1.setTextSize(30);
textView1.setText("Your final would be " + message);
setContentView(textView1);
Just for reference, the .8 and .2 is because the current grade is weighted at 80%, and the exam is weighted at 20%. How can I make it so it won't crash when nothing is put into the boxes?
usernameEditText.getText().toString(); would not return null. It will return an empty string. What you can do before calculating finalResult is to check stringGrade and stingExam are non-empty and numerical values and if one is not then stop the operation. i.e.
String stringGrade = (grade.getText().toString());
String stringExam = (exam.getText().toString());
if (stringGrade.isEmpty() || stringExam.isEmpty()) {
Toast.makeText(this, "Invalid values", Toast.LENGTH_SHORT);
return;
}
try this:
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText grade = (EditText) findViewById(R.id.grade1);
EditText exam = (EditText) findViewById(R.id.grade2);
String stringGrade = (grade.getText().toString());
String stringExam = (exam.getText().toString());
if(stringGrade.equals("") ){
stringGrade = "0";
}
if(stringExam.equals("") ){
stringExam= "0";
}
double finalResult = (Double.parseDouble(stringGrade) * .8) + (Double.parseDouble(stringExam) * 0.2);
String finalResultString = String.valueOf(finalResult);
if (finalResultString == null){
finalResultString = "0";
} else {
intent.putExtra(EXTRA_MESSAGE, finalResultString);
startActivity(intent);
}}
Related
I've just started off learning Adroid studio and coding with Java. I'm not sure why my if statement returns a value of 0(The initialized value).
The code above the onclicklistener works fine.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thecart);
Intent caller = getIntent();
String item = caller.getStringExtra("choice");
TextView disptext = (TextView) findViewById(R.id.carttoptext);
disptext.setText("You selected " + item);
EditText quantity = (EditText) findViewById(R.id.inputquantity);
Button calc= (Button) findViewById(R.id.calc);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double price=0;
double vquant = valueOf(quantity.getText().toString());
String item = caller.getStringExtra("choice");
if (item.equals("Eggs")) {
price = vquant * 4;
} else if (item.equals("Milk")) {
price = vquant * 30;
} else if (item.equals("Bread")) {
price = vquant * 23;
} else if (item.equals("Chips")) {
price = vquant * 20;
} else if (item.equals("Maggi")) {
price = vquant * 15;
}
DecimalFormat formatval = new DecimalFormat("##.##");
TextView pricetext = (TextView) findViewById(R.id.pricetext);
pricetext.setText("Total: " + formatval.format(price));
}
});
}
}
I'm expecting the textview beneath the edittext to give me the value vquant*(if condition value). But I'm getting the Textview as Total: 0 , which is the initializing value.
What changes should I make to the code so that I get desired output?
check if the vquant is able to fetch the value from the quantity as a double.
ValueOf() change the data into String and you are taking that data to a double variable. It won't work. Use Double.valueOf()
Have you tried "Double.parseDouble(..)" instead of valueOf?
enter image description here
I want to fetch the data from previous activity (using getIntent) in a .java class and same the data to next activity through intent. can anyone help me how.Thanks in advance.
public class AddToCartHelper {
public static void addToCart(Context context, Intent intent) {
String TAG = "AddToCart";
DecimalFormat decimalFormat;
boolean loginflagforuser = false, loginflagforguest = false;
String advId = "", num = "", uid = "", productName = "", emailCart = "",cartMessage = "";
Double price = 0.0;
Integer quantity = 1;
SharedPreferences preferences = context.getSharedPreferences("SECRETFILE", Context.MODE_PRIVATE);
loginflagforuser = preferences.getBoolean(Parameters.userEmail, false);
loginflagforguest = preferences.getBoolean(Parameters.guestEmail, false);
decimalFormat = new DecimalFormat("##.##");
if (loginflagforuser){
Intent fromCart = getIntent();
// imageId = fromCart.getStringExtra("image_url");
advId = fromCart.getStringExtra("Advid");
price = fromCart.getDoubleExtra("price", 0.0);
num = fromCart.getStringExtra("num");
uid = fromCart.getStringExtra("uid");
Log.d(TAG, "--- REGISTERD UID::::::::: " + uid);
quantity = fromCart.getIntExtra("quantity", 1);
productName = fromCart.getStringExtra("cart_product_name");
// total = fromCart.getDoubleExtra("total", 0.0);
emailCart = preferences.getString("email", null);
}else if (loginflagforguest){
}else{
}
}
}
you don't need to use this Intent fromCart = getIntent();,because in constructor you already pass intent ,then just use intent object
dvId = intent.getStringExtra("Advid");
price = intent.getDoubleExtra("price", 0.0);
num = intent.getStringExtra("num");
uid = intent.getStringExtra("uid");
Log.d(TAG, "--- REGISTERD UID::::::::: " + uid);
quantity = intent.getIntExtra("quantity", 1);
productName = intent.getStringExtra("cart_product_name");
// total = intent.getDoubleExtra("total", 0.0);
You have already pass parameter intent to addToCart function, so instead of advId = fromCart.getStringExtra("Advid");, you can use advId = intent.getStringExtra("Advid");
there is two ways to passing the data to the next activity you can either use intent or can use local broadcast receiver
if you want to fetch data from the previous activity then use
String a= getIntent().getStringExtra( "");// pass the name that you used in the previous activity
I made a code where user put value between some range and my code generate random number for them. Randomization working properly but when fields are blank my app is crash how should I fix it.
randNum.java
Button generateNum = findViewById(R.id.generate_number);
generateNum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
// if(sNum == null || fNum == null){
//
// ans.setText(getString(R.string.enterNumError));
//
// }
// else
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}
});
I try to use null but it is not working.
You need to put validation first on button click. (For checking if user has entered nothing or just spaces in any of edittexts).
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strNum1 = edtl.getText().toString().trim();
strNum2 = edt2.getText().toString().trim();
if (strNum1.length() == 0)
{
showAlert("Please enter Num 1");
}
else if (strNum2.length() == 0)
{
showAlert("Please enter Num 2");
}
else
{
int numvalue1 = Integer.parseInt(strNum1);
int numvalue2 = Integer.parseInt(strNum2);
generateNum (numvalue1, numvalue2); //Call your function for generation of random number here
//do your stuff here
}
}
});
Hope this helps you understand the validation of forms for empty input fields.
P.S: I would recommend you put inputType attribute for your EditTexts if you have not added it already in xml file like:
android:inputType="number"
So you can avoid exception at Integer.parseInt if user enters any alphabet or symbol.
You need to handle NumberFormatException thrown by Integer.valueOf() function
try {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}catch(NumberFormatException e){
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}
I implemented Sharing intent button in my application. I have strings in textviews, but it is not always filled with any text. So, I would like to check it is empty or not. If a string is empty, sharing intent should ignore/remove/get ride of this string and go to next string. I tried to do this programmatically, but without success. How can I do this? I need some helpo:
public void buttonClick2(View view) {
TextView textView1 = (TextView)findViewById(R.id.word);
TextView textView2 = (TextView)findViewById(R.id.definition);
TextView textView3 = (TextView)findViewById(R.id.definition2);
TextView textView4 = (TextView)findViewById(R.id.definition3);
boolean hasDefinition2 = false;
if (textView3 !=null){
String text3 = textView3.getText().toString();
if(text3 !=null && !text3.isEmpty()){
hasDefinition2 = true;
}
}
String def2 ="";
if(hasDefinition2){
def2 +="\n Definition 2: "+textView3.getText().toString();
}
boolean hasDefinition3 = false;
if (textView4 !=null){
String text4 = textView4.getText().toString();
if(text4 !=null && !text4.isEmpty()){
hasDefinition3 = true;
}
}
String def3 ="";
if(hasDefinition3){
def3 +="\n Definition 3: "+textView4.getText().toString();
}
Intent shareIntent1 = new Intent(android.content.Intent.ACTION_SEND);
shareIntent1.setAction(android.content.Intent.ACTION_SEND);
shareIntent1.setType("text/plain");
shareIntent1.putExtra(android.content.Intent.EXTRA_SUBJECT, "Word"); //<=adding blank quotes
shareIntent1.putExtra(Intent.EXTRA_TEXT, textView1.getText().toString()+
"\n"+Definition: +textView2.getText().toString()+
"\n"+def2+
"\n"+def3+
"\n"+"\n"+"#2016 Dictionary"+
"\n"+"Visit us:");
startActivity(Intent.createChooser(shareIntent1, "Share"));
}
you can try the following to check if textView3/4 is empty or not: -
String extra =textView1.getText().toString()+
"\n"+Definition: +textView2.getText().toString();
if (textView3 !=null){
String text = textView3.getText().toString();
if(text !=null && !text.isEmpty()){
extra +="\n Definition 2:"+ textView3.getText().toString();
}
}
if (textView4 !=null){
String text = textView4.getText().toString();
if(text !=null && !text.isEmpty()){
extra +="\n Definition 3:"+ textView4.getText().toString();
}
}
extra += "\n"+"\n"+"#2016 Dictionary"+
"\n"+"Visit us:"
shareIntent.putExtra(Intent.EXTRA_TEXT, extra);
startActivity( ... )
also do consider using StringBuilder instead of String for the extra.
I have a way that I know is not the best way of sending them over rite now but I'm sending them as strings and converting them to an Int on the reciver side, the problem is when I do the conversion it crashes on my phone. This is what I have on my sender side:
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, PayTracker.class);
// hourly wage send
EditText editText = (EditText) findViewById(R.id.hourly_wage);
String message1 = editText.getText().toString();
intent.putExtra(MESSAGE_1, message1);
// ot wage send
EditText editText1 = (EditText) findViewById(R.id.ot_wage);
String message2 = editText1.getText().toString();
intent.putExtra(MESSAGE_2, message2);
// hours per day send
EditText editText2 = (EditText) findViewById(R.id.hours_day);
String message3 = editText2.getText().toString();
intent.putExtra(MESSAGE_3, message3);
// start new activity
startActivity(intent);
And this is what is on my reciving side:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_tracker);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Receive messages from options page
Intent intent = getIntent();
String message1 = intent.getStringExtra(Options.MESSAGE_1);
String message2 = intent.getStringExtra(Options.MESSAGE_2);
String message3 = intent.getStringExtra(Options.MESSAGE_3);
// convert string to integer
int HW = Integer.valueOf(message1);
int OTW = Integer.valueOf(message2);
int HPD = Integer.valueOf(message3);
Ive tested everything and its the conversion that is causing the app to crash, i was hoping somebody could help me make it not crash or give me a whole new way sending an int to my second activity insted of sending a string and converting it.
Thank you!
=======================================================================
Here is my new code with all your help!
Sending:
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, PayTracker.class);
// Gather text from text boxes
EditText editText = (EditText) findViewById(R.id.hourly_wage);
EditText editText1 = (EditText) findViewById(R.id.ot_wage);
EditText editText2 = (EditText) findViewById(R.id.hours_day);
//Create String from text
String message1 = editText.getText().toString();
String message2 = editText1.getText().toString();
String message3 = editText2.getText().toString();
//Convert String to Int
int HW = 0, OTW = 0, HPD = 0;
try{
HW = Integer.valueOf(message1);
OTW = Integer.valueOf(message2);
HPD = Integer.valueOf(message3);
}
catch(NumberFormatException nfe){
//do something else here
//for e.g. initializing default values to your int variables
}
// Send Integers to PayTracker.java
intent.putExtra(MESSAGE_HW, HW);
intent.putExtra(MESSAGE_OTW, OTW);
intent.putExtra(MESSAGE_HPD, HPD);
// start new activity
startActivity(intent);
}
Receiving side:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_tracker);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Receive messages from options page
Intent intent = getIntent();
int HW = intent.getIntExtra(Options.MESSAGE_HW, 0);
int OTW = intent.getIntExtra(Options.MESSAGE_OTW, 0);
int HPD = intent.getIntExtra(Options.MESSAGE_HPD, 0);
// set textview
TextView textView = (TextView) this.findViewById(R.id.yourpay);
textView.setText(String.valueOf(HW));
}
You don't need to pass Integers as Strings to be converted back in the receiving Activity. Intents can hold Integers as well as Strings.
Simply add your data like you normally would:
int foo = 5;
Intent intent = new Intent(this, bar.class);
intent.putExtra("foobar", foo);
And then retrieve your int from the intent in the receiving Activity as follows.
Intent intent = getIntent();
int foo = intent.getIntExtra("foobar", 0);
Intents can hold more data than just Strings. In fact, take a look at the documentation. You can see that Intents can hold Longs, Doubles, Floats, Parcelables, etc.
Pass data from one activity to another activity "String" value.useing intent
Activityone
Intent intent = new Intent(Activityone.this,Activitytwo.class)
intent.putExtra("TYPE", type);
startActivity(intent);
Activitytwo
Intent intent =getIntent();
Receivevalue =intent.getExtras().getString("TYPE");
(OR)
Receivevalue = getIntent().getExtras().getString("TYPE");
Pass data from one activity to another activity "Integer" value.useing intent
Activityone
Intent intent = new Intent(Activityone.this,Activitytwo.class)
intent.putExtra("TYPE", type);
startActivity(intent);
Activitytwo
Intent intent = getIntent();
value = intent.getIntExtra("TYPE", 0);
// Type = intent.getIntExtra(name, defaultValue);
Try something like this on the send side:
String message1 = editText.getText().toString();
intent.putExtra("MESSAGE_1", message1);
String message2 = editText1.getText().toString();
intent.putExtra("MESSAGE_2", message2);
String message3 = editText2.getText().toString();
intent.putExtra("MESSAGE_3", message3);
Receive side:
if (getIntent() != null) {
if (getIntent().getExtras() != null) {
String mess1 = getIntent().getExtras().getString("MESSAGE_1");
String mess2 = getIntent().getExtras().getString("MESSAGE_2");
String mess3 = getIntent().getExtras().getString("MESSAGE_3");
}
}
You can achieve your goal using following code
In Your Calling Activity
Intent value = new Intent(YourCallingActivity.this,DestinationActivity.class);
value.putExtra("integerone", integeronevalue);
value.putExtra("integertwo", integertwovalue);
value.putExtra("integerthree", integertwovalue);
startActivity(value);
In Destination Activity
int integerone = getIntent().getExtras().getInt("integerone");
int integertwo = getIntent().getExtras().getInt("integertwo");
int integerthree = getIntent().getExtras().getInt("integerthree");
Hope it helps
Encapsulate the conversion part within try/catch block, because your strings may not be convertible into integer values.
int HW, OTW, HPD;
try{
HW = Integer.valueOf(message1);
OTW = Integer.valueOf(message2);
HPD = Integer.valueOf(message3);
}
catch(NumberFormatException nfe){
//do something else here
//for e.g. initializing default values to your int variables
}
*Or more appropriately, pass the integer values in your sending part and receive them as it is.