How to Change a TextView with the values in an EditText - android

I am completely new to App making and I want to make something in which there are two EditTexts (number only), which are then divided and turned into a percentage and displayed in a TextView. Unfortunately, I have no idea if what I am doing is correct. Here is my code
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.EditText;
import android.widget.TextView;
public class FirstInformation extends Activity {
EditText eT4 = (EditText)findViewById(R.id.editText4);
EditText eT5 = (EditText)findViewById(R.id.editText5);
TextView tV6 = (TextView)findViewById(R.id.textView6);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_information);
if (eT4 != null && eT5 != null){
double numerator = (double) Integer.parseInt(eT4.getText().toString());
double denominator = (double) Integer.parseInt(eT5.getText().toString());
double textView = Math.round(numerator/denominator)*100;
tV6.setText(textView+"");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first_information, menu);
return true;
}
public void updateTextView() {
if (eT4 != null && eT5 != null){
double numerator = (double) Integer.parseInt(eT4.getText().toString());
double denominator = (double) Integer.parseInt(eT5.getText().toString());
double textView = Math.round(numerator/denominator)*100;
tV6.setText(textView+"");
}
return;
}
}
Any feedback at all would be great. Thank you so much!

findViewById() in onCreate()
Division by zero

Your issue here is with the following code:
EditText eT4 = (EditText)findViewById(R.id.editText4);
EditText eT5 = (EditText)findViewById(R.id.editText5);
TextView tV6 = (TextView)findViewById(R.id.textView6);
findViewById method returns null for all those calls because you're doing UI related tasks before the setContentView method has finished. So you can declare the variables there and then initialize them after setContentView method.

Just as the other guys said, the findViewById() calls go into the onCreate() method otherwise they shall return null.
One other thing: updateTextView() is never called. You could use a TextWatcher or simply an onClickListener:
tv6.setOnClickListener(new onClickListener() {
#Override
public void onClick(View v) {
updateTextView();
}
});
And the result will be updated every time you click on the result textView. By the way using a TextWatcher (with afterTextChanged() method) is a better practice. I suggest you to take a guide/tutorial and try that ;)

Related

Saving UI state when moving between screens/activities Android app

I am doing a multiscreen quiz app. For each question I have a separate activity / screen. At the bottom of each screen there are next/previous "buttons" which navigate to the next/previous screen. Please see the UI example of a screen with a question:
I have a problem though. Let's assume a user selects answers to a question 2 and then clicks "Previous", selects an answer in question 1 and hits "Next".
I would like to save the UI state of the Question 2, so the selected answer stays if a user comes back to a question either by clicking previous or next.
One thing I managed to accomplish is when a user clicks "previous" the UI stays, I used the following code in the manifest file:
android:launchMode="singleTask"
However I cannot make it saved when a user comes bak to a question via "next". Here is my code for the activity with the question 2:
package com.example.justynagolawska.quizappiteration2;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class Question2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question2);
ActionBar actionbar = getSupportActionBar();
// Applies the custom action bar style
getSupportActionBar().setDisplayOptions(actionbar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.action_bar);
// Changes the action bar title
TextView title = (TextView) getSupportActionBar().getCustomView().findViewById(R.id.action_bar_title);
title.setText(R.string.q2_name);
//Getting the intent with score for question 1
Intent question2Intent = getIntent();
final int resultQ1 = question2Intent.getIntExtra("q1result", 0);
// Find the View that shows the next TextView
TextView nextQuestion = (TextView) findViewById(R.id.next);
// Set a click listener on that View
nextQuestion.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when next View is clicked on.
#Override
public void onClick(View view) {
//Getting the answer to question 2 checkbox 1
CheckBox checkBox1Q2 = (CheckBox) findViewById(R.id.checkbox1Q2);
boolean isCheckBox1Q2 = checkBox1Q2.isChecked();
//Getting the answer to question 2 checkbox 2
CheckBox checkBox2Q2 = (CheckBox) findViewById(R.id.checkbox2Q2);
boolean isCheckBox2Q2 = checkBox2Q2.isChecked();
//Getting the answer to question 2 checkbox 3
CheckBox checkBox3Q2 = (CheckBox) findViewById(R.id.checkbox3Q2);
boolean isCheckBox3Q2 = checkBox3Q2.isChecked();
//Calculate Question 2 score
int resultQ2 = calculateResultQ2(isCheckBox1Q2, isCheckBox2Q2, isCheckBox3Q2);
Intent question3Intent = new Intent(Question2Activity.this, Question3Activity.class);
question3Intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
question3Intent.putExtra ("q1result", resultQ1);
question3Intent.putExtra ("q2result", resultQ2);
startActivity(question3Intent);
}
});
// Find the View that shows the next TextView
TextView previousQuestion = (TextView) findViewById(R.id.previous);
// Set a click listener on that View
previousQuestion.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when next View is clicked on.
#Override
public void onClick(View view) {
Intent question1Intent = new Intent(Question2Activity.this, Question1Activity.class);
startActivity(question1Intent);
}
});
}
/**
* Check which checkbox was selected in the question 2
*
* #param checkBox1 is whether or not the user checked the checkbox1
* #param checkBox2 is whether or not the user checked the checkbox2
* #param checkBox3 is whether or not the user checked the checkbox3
* #return the score the user got for question 2
*/
private int calculateResultQ2(boolean checkBox1, boolean checkBox2, boolean checkBox3) {
int result = 0;
if (checkBox1 && checkBox2 && checkBox3) {
result = 1;
}
return result;
}
I would appreciate very much if anyone could help me out. Thank you!
EDIT: Below is my working code using sharedPreferences, the solution proposed by #tahsinRupam
package com.example.justynagolawska.quizappiteration2;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class Question2Activity extends AppCompatActivity {
SharedPreferences mypref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question2);
final CheckBox checkBox1Q2 = (CheckBox) findViewById(R.id.checkbox1Q2);
final CheckBox checkBox2Q2 = (CheckBox) findViewById(R.id.checkbox2Q2);
final CheckBox checkBox3Q2 = (CheckBox) findViewById(R.id.checkbox3Q2);
mypref = PreferenceManager.getDefaultSharedPreferences(this);
ActionBar actionbar = getSupportActionBar();
// Applies the custom action bar style
getSupportActionBar().setDisplayOptions(actionbar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.action_bar);
// Changes the action bar title
TextView title = (TextView) getSupportActionBar().getCustomView().findViewById(R.id.action_bar_title);
title.setText(R.string.q2_name);
//Getting the intent with score for question 1
Intent question2Intent = getIntent();
final int resultQ1 = question2Intent.getIntExtra("q1result", 0);
// Find the View that shows the next TextView
TextView nextQuestion = (TextView) findViewById(R.id.next);
// Set a click listener on that View
nextQuestion.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when next View is clicked on.
#Override
public void onClick(View view) {
//Getting the answer to question 2 checkbox 1
boolean isCheckBox1Q2 = checkBox1Q2.isChecked();
//Getting the answer to question 2 checkbox 2
boolean isCheckBox2Q2 = checkBox2Q2.isChecked();
//Getting the answer to question 2 checkbox 3
boolean isCheckBox3Q2 = checkBox3Q2.isChecked();
//Calculate Question 2 score
int resultQ2 = calculateResultQ2(isCheckBox1Q2, isCheckBox2Q2, isCheckBox3Q2);
Intent question3Intent = new Intent(Question2Activity.this, Question3Activity.class);
question3Intent.putExtra ("q1result", resultQ1);
question3Intent.putExtra ("q2result", resultQ2);
startActivity(question3Intent);
}
});
// Find the View that shows the next TextView
TextView previousQuestion = (TextView) findViewById(R.id.previous);
// Set a click listener on that View
previousQuestion.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when next View is clicked on.
#Override
public void onClick(View view) {
Intent question1Intent = new Intent(Question2Activity.this, Question1Activity.class);
startActivity(question1Intent);
}
});
}
/**
* Check which checkbox was selected in the question 2
*
* #param checkBox1 is whether or not the user checked the checkbox1
* #param checkBox2 is whether or not the user checked the checkbox2
* #param checkBox3 is whether or not the user checked the checkbox3
* #return the score the user got for question 2
*/
private int calculateResultQ2(boolean checkBox1, boolean checkBox2, boolean checkBox3) {
int result = 0;
if (checkBox1 && checkBox2 && checkBox3) {
result = 1;
}
return result;
}
#Override
protected void onPause() {
super.onPause();
//Getting the answer to question 2 checkbox 1
CheckBox checkBox1Q2 = (CheckBox) findViewById(R.id.checkbox1Q2);
boolean isCheckBox1Q2 = checkBox1Q2.isChecked();
//Getting the answer to question 2 checkbox 2
CheckBox checkBox2Q2 = (CheckBox) findViewById(R.id.checkbox2Q2);
boolean isCheckBox2Q2 = checkBox2Q2.isChecked();
//Getting the answer to question 2 checkbox 3
CheckBox checkBox3Q2 = (CheckBox) findViewById(R.id.checkbox3Q2);
boolean isCheckBox3Q2 = checkBox3Q2.isChecked();
if(isCheckBox1Q2 == true){
mypref.edit().putBoolean("Iscb1Checked", true).apply();
}
else if(isCheckBox1Q2 == false){
mypref.edit().putBoolean("Iscb1Checked", false).apply();
}
if(isCheckBox2Q2 == true){
mypref.edit().putBoolean("Iscb2Checked", true).apply();
}
else if(isCheckBox2Q2 == false){
mypref.edit().putBoolean("Iscb2Checked", false).apply();
}
if(isCheckBox3Q2 == true){
mypref.edit().putBoolean("Iscb3Checked", true).apply();
}
else if(isCheckBox3Q2 == false){
mypref.edit().putBoolean("Iscb3Checked", false).apply();
}
}
#Override
protected void onResume() {
super.onResume();
//Getting the answer to question 2 checkbox 1
CheckBox checkBox1Q2 = (CheckBox) findViewById(R.id.checkbox1Q2);
//Getting the answer to question 2 checkbox 2
CheckBox checkBox2Q2 = (CheckBox) findViewById(R.id.checkbox2Q2);
//Getting the answer to question 2 checkbox 3
CheckBox checkBox3Q2 = (CheckBox) findViewById(R.id.checkbox3Q2);
if(mypref.contains("Iscb1Checked")){
if(mypref.getBoolean("Iscb1Checked",false)){
checkBox1Q2.setChecked(true);
}
}
if(mypref.contains("Iscb2Checked")){
if(mypref.getBoolean("Iscb2Checked",false)){
checkBox2Q2.setChecked(true);
}
}
if(mypref.contains("Iscb3Checked")){
if(mypref.getBoolean("Iscb3Checked",false)){
checkBox3Q2.setChecked(true);
}
}
}
}
Please note that I replaced the below in the onPause(); method as I was getting null exception:
checkBox1Q2.isChecked()
!checkBox1Q2.isChecked()
with
isCheckBox1Q2 == true
isCheckBox1Q2 == false
You can use SharedPreference to store your value.
1) Declare checkbox and SharedPreference publicly:
CheckBox checkBox1Q2;
CheckBox checkBox2Q2;
CheckBox checkBox3Q2;
SharedPreferences mypref;
2) In your onCreate() initialize SharedPreference:
mypref = PreferenceManager.getDefaultSharedPreferences(this);
3) Save Checkbox states in onPause() (cause onPause() is called when the back button is pressed). You could declare in onStop() or onDestroy() too.
#Override
protected void onPause() {
super.onPause();
if(checkBox1Q2.isChecked()){
mypref.edit().putBoolean("Iscb1Checked", true).apply();
}
else if(!checkBox1Q2.isChecked()){
mypref.edit().putBoolean("Iscb1Checked", false).apply();
}
if(checkBox2Q2.isChecked()){
mypref.edit().putBoolean("Iscb2Checked", true).apply();
}
else if(!checkBox2Q2.isChecked()){
mypref.edit().putBoolean("Iscb2Checked", false).apply();
}
if(checkBox3Q2.isChecked()){
mypref.edit().putBoolean("Iscb3Checked", true).apply();
}
else if(!checkBox3Q2.isChecked()){
mypref.edit().putBoolean("Iscb3Checked", false).apply();
}
}
4) Get CheckBox states in onResume() method:
#Override
protected void onResume() {
super.onResume();
if(mypref.contains("Iscb1Checked")){
if(mypref.getBoolean("Iscb1Checked",false)){
checkBox1Q2.setChecked(true);
}
}
if(mypref.contains("Iscb2Checked")){
if(mypref.getBoolean("Iscb2Checked",false)){
checkBox2Q2.setChecked(true);
}
}
if(mypref.contains("Iscb3Checked")){
if(mypref.getBoolean("Iscb3Checked",false)){
checkBox3Q2.setChecked(true);
}
}
}
You're now getting the Checkbox view in onClick. Try to avoid that. Always get views (findViewById) in the initial part of onCreate (After setContentView).

How can i have a handler if one of these fields don't have values when user pressed post?

I have this fields where every field is important and I don't have an idea how to do this. Where I want it if I pressed post there will be a message that not all fields have values. Here is my code.
InsertActivity
package com.example.kun.carkila;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import java.util.HashMap;
public class InsertActivity extends AppCompatActivity implements View.OnClickListener {
EditText etCarModel,etCarType,etCapacity,etImageURL,etFuelType,etPlateNumber;
Button btnPost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
etCarModel = (EditText)findViewById(R.id.etCarModel);
etCarType = (EditText)findViewById(R.id.etCarType);
etCapacity = (EditText)findViewById(R.id.etCapacity);
etImageURL = (EditText)findViewById(R.id.etImageURL);
etFuelType = (EditText)findViewById(R.id.etFuelType);
etPlateNumber = (EditText)findViewById(R.id.etPlateNumber);
btnPost = (Button)findViewById(R.id.btnPost);
btnPost.setOnClickListener(this);
}
#Override
public void onClick(View v) {
HashMap postData = new HashMap();
postData.put("txtCarModel",etCarModel.getText().toString());
postData.put("txtCarType",etCarType.getText().toString());
postData.put("txtCapacity",etCapacity.getText().toString());
postData.put("txtImage",etImageURL.getText().toString());
postData.put("txtFuelType",etFuelType.getText().toString());
postData.put("txtPlateNumber",etPlateNumber.getText().toString());
PostResponseAsyncTask taskPost = new PostResponseAsyncTask(InsertActivity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
if(s.contains("New records created successfully")){
Toast.makeText(InsertActivity.this, "Car Posted!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(InsertActivity.this, ownerhome.class);
startActivity(in);
}else{
}
}
});
taskPost.execute("http://carkila.esy.es/insert.php");
}
}
Hope for a kind response and I wanted to learn in an easy way. Thank you guys.
Before executing your asynctask you have to check is any EdiText feilds are empty or not. Like
TextUtils.isEmpty(etCarModel.getText().toString())
You have to check for each EditText In starting of OnClick method and if any editText is empty then show alert and do not execute your asynktask.
Check first if each field is empty:
#Override
public void onClick(View v) {
HashMap postData = new HashMap();
if (TextUtils.isEmpty(etCarModel.getText().toString())) {
Toast.makeText(this, "Car model is empty", LENGTH_SHORT).show()
return;
}
postData.put("txtCarModel",etCarModel.getText().toString());
if (TextUtils.isEmpty(etCarType.getText().toString())) {
Toast.makeText(this, "Car type is empty", LENGTH_SHORT).show();
return;
}
postData.put("txtCarType",etCarType.getText().toString());
//and so on
}
Yours is a simple problem. I have, because I needed these checks a lot, created a couple of utility methods for this purpose. You may place them in any class that you want.
safeGetText() to get text from a TextView:
public static String safeGetText(TextView textView, boolean isNullable)
{
String result = null;
if(textView != null)
{
CharSequence text = textView.getText();
if(text != null)
{
result = text.toString();
}
}
if(result == null && !isNullable)
{
// This check is for situations where the text cannot be null.
// Now, I find this utterly pointless, but what the hell.
result = "";
}
return result;
}
'isStringNullOrEmpty()' to check for null/empty strings:
public static boolean isStringNullOrEmpty(#Nullable String input)
{
if (input == null || input.length() <= 0)
{
return true;
}
else
{
return false;
}
}
Although these methods don't do anything magical, they helped me clean up the way I checked for Strings in my TextViews.
When you need to check the input (possibly in onClick()), put up empty checks for each field like:
boolean isEmpty = isStringNullOrEmpty(safeGetText(field, true)); // true/false in arg2 doesn't matter here
You would need to apply this check for every field in your current implementation. You could make arrangements to iterate through all fields in a loop like this:
boolean areFieldsValid = true;
for(TextView field : arrayOfAllFields)
{
boolean isCurrentFieldValid = isStringNullOrEmpty(safeGetText(field, true));
areFieldsValid &= isCurrentFieldValid;
}
// Here, the flag 'areFieldsValid' will only be true if all fields are valid
Let me know if this solves your purpose, and/or if you need more help.
You can use an editText array so that you can use a for loop instead of writing it all over. For key name in Hashmap you can use id name of editText in a for loop
String str = editText[i].getResources().getResourceName(id);
str = str.substring(str.lastIndexOf(":id/") + 4);
postData.put(str,editText[i].getText().toString());
This code will be in a for loop to put all the data.
and in similar way you can check where this strings are null or not.
for(int i=0;i<6;i++){
if(editText[i].getText().toString().equals("")){
//Error alert
}
}
I think this will reduce a lot of LOC.

Numerous errors on one line of code?

I am nearly complete with my first android app, which is a basic tip calculator. I am having trouble with line 36
amountDisplayTextView = (TextView) findViewById(R.id.amountDisplayTextView);
I am getting these errors:
Multiple markers at this line
-Syntax error, insert ";" to complete FieldDeclaration
-Syntax error on token ".", ... expected
-Syntax error on token "amountDisplayTextView", VariableDeclaratorId expected after this token
-Return type for the method is missing
-Syntax error on token ")", { expected after this token
-Syntax error on token "amountDisplayTextView", VariableDeclaratorId expected after this token
I have tried to trouble shoot, but I hit a wall. Any assistance is appreciated! Here is the rest of the class.
package com.example.tipcalc;
import java.text.NumberFormat;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextWatcher;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class MainActivity extends Activity {
//currency and percent formatters
private static final NumberFormat currencyFormat =
NumberFormat.getCurrencyInstance();
private static final NumberFormat percentFormat =
NumberFormat.getPercentInstance();
private double billAmount = 0.0; //bill amount entered by the user
private double customPercent = 0.18; //initial custom percent value
private TextView amountDisplayTextView; //shows formatted bill amount
private TextView percentCustomTextView;//shows custom tip percentage
private TextView tip15TextView; // shows 15% tip
private TextView total15TextView; // shows total with 15% tip
private TextView tipCustomTextView; // shows custom tip amount
private TextView totalCustomTextView; //shows total with custom tip
//called when activity is first created
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //call superclass's version
setContentView(R.layout.activity_main); //inflate GUI
}
//get references to the TextViews
//that MainActivity interacts with programmatically
amountDisplayTextView = (TextView) findViewById(R.id.amountDisplayTextView);
percentCustomTextView = (TextView) findViewById(R.id.percentCustomTextView);
tip15TextView = (TextView) findViewById(R.id.tip15TextView);
total15TextView = (TextView) findViewById(R.id.total15TextView);
tipCustomTextView = (TextView) findViewById(R.id.tipCustomTextView);
totalCustomTextView = (TextView) findViewById(R.id.totalCustomTextView);
}
//update 15% textviews
private void updateStandard()
{
//calculate 15% tip and total
double fifteenPercentTip = billAmount * 0.15;
double fifteenPercentTotal = billAmount + fifteenPercentTip;
//display 15% tip and total formatted as currency
tip15TextView.setText(currencyFormat.format(fifteenPercentTip));
total15TextView.setText(currencyFormat.format(fifteenPercentTotal));
} //end method updateStandard
//updates the custom tip and total TextViews
private void updateCustom()
{
//show customPercent in percentCustomTextView formatted as %
percentCustomTextView.setText(percentFormat.format(customPercent));
//calculate the custom tip and total
double customTip = billAmount * customPercent;
double customTotal = billAmount + customTip;
//display custom tip and total formatted as currency
tipCustomTextView.setText(currencyFormat.format(customTip));
totalCustomTextView.setText(currencyFormat.format(customTotal));
}//end updateCustom
//called when the user changes the position of SeekBar
private OnSeekBarChangeListener customSeekBarListener =
new OnSeekBarChangeListener()
{
//update customPercent, then call updateCustom
#Override
publicvoid onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
//set customPercent to position of the SeekBar's thumb
customPercent = progress / 100.0; //update the custom tip TextViews
updateCustom(); //update the custom tip TextView's
}; //end method onProgressChanged
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}// end method onStartTrackingTouch
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}// end method onStopTrackingTouch
};//end OnSeekBarChangeListener
//event-handling object that responds to amountEditText's events
private TextWatcher amountEditTextWatcher = new TextWatcher()
{
//called when the user enters a number
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
//convert amountEditText's text to a double
try
{
billAmount = Double.parseDouble(s.toString()) / 100.0;
} //end try
catch (NumberFormatException e)
{
billAmount = 0.0; //default if an exception occurs
}//end catch
//display currency formatted bill amount
amountDisplayTextView.setText(currencyFormat.format(billAmount));
updateStandard(); //update the 15% tip Textviews
updateCustom(); //update the custom tip TextViews
}; //end method onTextChanged
#Override
public void afterTextChanged(Editable s)
{
}//end method afterTextChanged
#Override
public void beforeTextChanged (CharSequence s, int start, int count, int after)
{
} // end method before TextChanged
}; //end amountEditTextWatcher
}//end mainActivity class
its all about your {}{} your declaring your variables at class level and trying to instantiate them too if you instantiate them inside of onCreate where they should be it will work
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //call superclass's version
setContentView(R.layout.activity_main); //inflate GUI
//get references to the TextViews
//that MainActivity interacts with programmatically
amountDisplayTextView = (TextView) findViewById(R.id.amountDisplayTextView);
percentCustomTextView = (TextView) findViewById(R.id.percentCustomTextView);
tip15TextView = (TextView) findViewById(R.id.tip15TextView);
total15TextView = (TextView) findViewById(R.id.total15TextView);
tipCustomTextView = (TextView) findViewById(R.id.tipCustomTextView);
totalCustomTextView = (TextView) findViewById(R.id.totalCustomTextView);
}

Android String to int crashes my app

I am trying to make an app where the user inputs a phone number into a EditText variable NumberBox which is than converted to int from string and used in the method intent.putExtra("address", PhoneNumberint); When I try to do this, the app just crashes, so please let me know what the problem is here. Is the conversion from string to int wrong in some way?
package com.example.module09;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
//variables
EditText NumberBox;
Button SMSButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
NumberBox = (EditText) findViewById(R.id.NumberBox);
SMSButton = (Button) findViewById(R.id.SMSButton);
final int PhoneNumberint = Integer.parseInt(NumberBox.getText().toString());
//onclick
SMSButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("address", PhoneNumberint);
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Just move this :
final int PhoneNumberint = Integer.parseInt(NumberBox.getText().toString());
from your onCreate method to the onClick method.
The app crashes because you have placed the above code in your onCreate method. Since at the time of Activity creation the value of EditText is null the String contains null. When null is parsed to Integer it throws an exception.
you try get value on onCreate method that is null, you must get value of that on button click like following code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
NumberBox = (EditText) findViewById(R.id.NumberBox);
SMSButton = (Button) findViewById(R.id.SMSButton);
//onclick
SMSButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
PhoneNumberint = Integer.parseInt(NumberBox.getText().toString());
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("address", PhoneNumberint);
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
}
});
You can't perform this on onCreate() method
final int PhoneNumberint = Integer.parseInt(NumberBox.getText().toString());
At first time your String contains null data because it always be null values for your EditText and that's why you will be always get null pointer because you can't parse null value to int.
So better way it to move that line on Click event of Button.
The app crashes because of NumberFormatException
The problem lies where you are extracting text from EditText before it is being set. If the content of EditText is empty/null string, Integer.parseInt will throw java.lang.NumberFormatException
The culprit is this line:
final int PhoneNumberint = Integer.parseInt(NumberBox.getText().toString());
To fix this, move this line under onClick(). But the App will still crash, if the button is clicked without inputting anything in EditText.
Before parsing the String to Int, write to check if the String is empty/null.
On the lighter side, there is no need of final keyword here.

Hiding and showing a single Menu Button

I have a project for an Android class, so I'm still learning and this should be a basic question. We were given a tip calculator and already made some modifications, now we have to add a menu.
When it starts up, it will be in multi-person mode. Gives a text box and Text Field for how many people you want the bill split into. When you hit menu, it should show a Single person mode which eliminates a text box and text field. The menu then changes to show a multi-person mode button in the menu.
I've got everything to work except it's showing both buttons, I cannot figure out how to hide a button temporarily. The main error is:
Cannot invoke setVisibility(int) on the primitive type int
on the statement:
multiple_button.setVisibility(View.GONE);
I've tried every combination of hiding the button I can think of, and think that the above line is correct, but unsure of how make it work.
one_person_button = View.VISIBLE;
multiple_button = View.GONE;
I have this in the code, but it's not doing anything either.
Any help would be greatly appreciated.
edit: code. I've read through the link, but considering I don't have a OnPrepareOptions section, I need to re-read it
package com.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Button;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class tipcalc extends Activity
{
public static int one_person_button = Menu.FIRST;
private int multiple_button = Menu.FIRST +1;
static final private int reset_button = Menu.FIRST +2;
private static final int MENU_ITEM = 0;
private EditText txtbillamount;
private EditText txtpeople;
private EditText txtpercentage;
private TextView txtperperson;
private TextView txttipamount;
private TextView txttotal;
private Button btncalculate;
private Button btnreset;
private double billamount = 0;
private double percentage = 0;
private double numofpeople=0;
private double tipamount = 0;
private double totaltopay = 0;
private double perperson = 0;
private View view;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem itemOne = menu.add(0, one_person_button, Menu.NONE,
R.string.one_person);
MenuItem itemMultiple = menu.add(1, multiple_button, Menu.NONE,
R.string.multiple);
MenuItem itemReset = menu.add(2, reset_button, Menu.NONE,
R.string.reset);
itemOne.setIcon(R.drawable.ic_menu_invite);
itemMultiple.setIcon(R.drawable.ic_menu_allfriends);
itemReset.setIcon(R.drawable.ic_menu_refresh);
one_person_button.setGroupVisible(0, true);
multiple_button.setVisibility(View.GONE);
one_person_button = View.VISIBLE;
multiple_button = View.GONE;
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (one_person_button == View.VISIBLE) {
((TextView)findViewById(R.id.txtpeople)).setVisibility(View.INVISIBLE) ;
((TextView)findViewById(R.id.widget30)).setVisibility(View.INVISIBLE) ;
multiple_button = View.VISIBLE;
one_person_button = View.GONE;
numofpeople = 1; }
else if (multiple_button == View.VISIBLE) {
((TextView)findViewById(R.id.txtpeople)).setVisibility(View.VISIBLE) ;
((TextView)findViewById(R.id.widget30)).setVisibility(View.VISIBLE) ;
multiple_button = View.GONE;
one_person_button = View.VISIBLE;
}
return false;
}
private void initControls()
{
txtbillamount = (EditText)findViewById(R.id.txtbillamount);
txtpeople = (EditText)findViewById(R.id.txtpeople);
txtperperson=(TextView)findViewById(R.id.txtperperson);
txttipamount=(TextView)findViewById(R.id.txttipamount);
txttotal=(TextView)findViewById(R.id.txttotal);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ reset(); }});
}
private void calculate()
{
billamount=Double.parseDouble(txtbillamount.getText().toString());
numofpeople=Double.parseDouble(txtpeople.getText().toString());
RadioButton poorButton = (RadioButton) findViewById(R.id.radioButton1);
RadioButton goodButton = (RadioButton) findViewById(R.id.radioButton2);
RadioButton excellentButton = (RadioButton) findViewById(R.id.radioButton3);
if (poorButton.isChecked()){
percentage = Double.parseDouble(poorButton.getText().toString());
} else if (goodButton.isChecked()){
percentage = Double.parseDouble(goodButton.getText().toString());
} else if (excellentButton.isChecked()){
percentage = Double.parseDouble(excellentButton.getText().toString());
}
tipamount=(billamount*percentage)/100;
totaltopay=billamount+tipamount;
perperson=totaltopay/numofpeople;
txttipamount.setText(Double.toString(tipamount));
txttotal.setText(Double.toString(totaltopay));
txtperperson.setText(Double.toString(perperson));
}
private void reset()
{
txtbillamount.setText("");
txtpeople.setText("");
txtperperson.setText("");
txttipamount.setText("");
txttotal.setText("");
}
}
Post all of your relavent source code. Without it, we cannot give you specific advice about what is going wrong.
I can tell you though you'll be needing to override onPrepareOptionsMenu() and inside there you'll want to check which mode your in and make the proper button be visible. But you need to call setVisibility(View.VISIBLE); on a reference to the button widget, not on an int.
This page holds the answer to your questions.
try calling setVisibility with 8

Categories

Resources