I'm a beginner in application development. My problem is, that when I run my app and I click on the Calculate button, the program stops. The code:
public class screen1 extends Activity {
private EditText name;
private CheckBox box1;
private Spinner spinner;
private TextView text1, text2, text3, text4, text5, text6;
private Button calcbutton, closebutton;
String strength;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner hubSpinner = (Spinner) findViewById(R.id.myspinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.military_ranks , android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
hubSpinner.setAdapter(adapter);
name = (EditText)findViewById(R.id.editText1);
strength = name.getText().toString();
box1 = (CheckBox)findViewById(R.id.checkBox1);
text1 = (TextView)findViewById(R.id.textView4);
text2 = (TextView)findViewById(R.id.textView6);
text3 = (TextView)findViewById(R.id.textView8);
text4 = (TextView)findViewById(R.id.textView10);
text5 = (TextView)findViewById(R.id.textView12);
text6 = (TextView)findViewById(R.id.textView14);
final Button calcbutton = (Button) findViewById(R.id.button1);
calcbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int str = Integer.valueOf(strength);
int rank = spinner.getSelectedItemPosition()+1;
double sebzes;
if(box1.isChecked()){
sebzes = (((rank-1)/20+0.3)*((str/10)+40))*1*(1+1/100);
text1.setText(Double.toString(sebzes));
}
else{
sebzes = (((rank-1)/20+0.3)*((str/10)+40))*1;
text1.setText(Double.toString(sebzes));
}
}
});
final Button closebutton = (Button) findViewById(R.id.button2);
closebutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}
In the edittext component you should be able to write numbers only. I don't know why it's not working.
The problem are these two lines:
int str = Integer.valueOf(strength);
int rank = spinner.getSelectedItemPosition()+1;
The first won't fail if you use only numbers in your EditText but it would be better to ensure that or at least catch the exception that is thrown when you try to convert a character to a numberical value. Additionally you could also use Integer.valueOf(strength).intValue(); even so it is normally not really necessary.
The real problem is the second line. You declared the variable spinner but you never instantiate it. That's why you will get a NullPointerException there.
On an unrelated note: You also should start your class name with a capital letter to follow the Java naming conventions.
You're not instantiating spinner anywhere, but you're referencing it in the second line of your button click method. Probably a null reference problem.
Related
Learning how to produce random numbers from arrays. The code will pick a random string during the onCreate method, but when the button is clicked there is no change to the string. Am I messing up the scope of my variables somehow? I really do not know what it wrong.
public class MainActivity extends AppCompatActivity {
String[] qArray; //initialize qArray
private static final Random rgen = new Random(); //sets the new Random method to the keyword rgen
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qArray = getResources().getStringArray(R.array.qArray); //grabs string array in the XML file
String q = qArray[rgen.nextInt(qArray.length)];//generates a random index of qArray to set to q
TextView question = (TextView) findViewById(R.id.question); //sets the TextView to "question"
question.setText(q); //sets the text in "question" to q
}
public void onClick(View view){
Button button = (Button) view.findViewById(R.id.button_click);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
/*This should do the same thing as onCreate but each time
the button is pressed. I think the error is here.*/
String q = qArray[rgen.nextInt(qArray.length)];
TextView question = (TextView) findViewById(R.id.question);
question.setText(q);
}
});
}
}
First of all you haven't set click listener on button properly you made onClick method which is never called . Also you are getting the references of view multiple times you should do it like this.
public class MainActivity extends AppCompatActivity {
String[] qArray; //initialize qArray
private static final Random rgen = new Random(); //sets the new Random method to the keyword rgen
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qArray = getResources().getStringArray(R.array.qArray); //grabs string array in the XML file
String q = qArray[rgen.nextInt(qArray.length)];//generates a random index of qArray to set to q
TextView question = (TextView) findViewById(R.id.question); //sets the TextView to "question"
question.setText(q); //sets the text in "question" to q
Button button = (Button) view.findViewById(R.id.button_click);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
/*This should do the same thing as onCreate but each time
the button is pressed. I think the error is here.*/
String q = qArray[rgen.nextInt(qArray.length)];
question.setText(q);
}
});
}
}
You either need to set the onClickListener in xml (in which case you don't need to set the listener in code), or you need to set the listener in onCreate. Right now its being set in a function named onClick, which is never called.
First, you never set the onClickListeren. You have a method which adds one, but you never call it. Move the code in the onClick method to your onCreate method. This will probably fix your problem.
If not, don't make your Random final and add this to your #Override onClick():
rgen = new Random(System.currentTimeMillis());
This will use a different seed every time
problem: I set point breaks at the following code:
intent.putExtra(WorkoutRoutinesActivity.EXTRA_WORKOUT_NAME, workoutName);
intent.putExtra(WorkoutRoutinesActivity.EXTRA_WORKOUT_DAYS, workoutDays);
, both showed up as null when I ran the app in debug mode. workoutName contains a simple String that is passed to a new activity, whereas workoutDays constains an array of String.
the full code is provided below:
public class CreateWorkoutActivity extends Activity {
public final String TAG = this.getClass().getSimpleName();
protected String[] workoutDays = new String[7];
protected String workoutName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_workout);
Button mNextButton = (Button) findViewById(R.id.next_button1);
CheckBox satBox = (CheckBox) findViewById(R.id.sat_checkbox);
CheckBox sunBox = (CheckBox) findViewById(R.id.sun_checkbox);
CheckBox monBox = (CheckBox) findViewById(R.id.mon_checkbox);
CheckBox tuesBox = (CheckBox) findViewById(R.id.tues_checkbox);
CheckBox wedBox = (CheckBox) findViewById(R.id.wed_checkbox);
CheckBox thursBox = (CheckBox) findViewById(R.id.thurs_checkbox);
CheckBox friBox = (CheckBox) findViewById(R.id.fri_checkbox);
final EditText mWorkoutName = (EditText) findViewById(R.id.workout_name1);
workoutName = mWorkoutName.getText().toString();
Log.i(TAG, workoutName);
if (satBox.isChecked()) {
workoutDays[0] = new String(satBox.getText().toString());
}
if (sunBox.isChecked()) {
workoutDays[1] = new String(sunBox.getText().toString());
}
if (monBox.isChecked()) {
workoutDays[2] = new String(monBox.getText().toString());
}
if (tuesBox.isChecked()) {
workoutDays[3] = new String(tuesBox.getText().toString());
}
if (wedBox.isChecked()) {
workoutDays[4] = wedBox.getText().toString();
}
if (thursBox.isChecked()) {
workoutDays[5] = satBox.getText().toString();
}
if (friBox.isChecked()) {
workoutDays[6] = friBox.getText().toString();
Log.i(TAG, workoutDays[6]);
}
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, workoutDays.toString());
Intent intent = new Intent(CreateWorkoutActivity.this, WorkoutRoutinesActivity.class);
intent.putExtra(WorkoutRoutinesActivity.EXTRA_WORKOUT_NAME, workoutName);
intent.putExtra(WorkoutRoutinesActivity.EXTRA_WORKOUT_DAYS, workoutDays);
Log.i(TAG, workoutDays.toString());
startActivity(intent);
}
});
}
The problem is not in the intent, but in the way you obtain workoutName (this is the null value). You create the activity, set up final EditText mWorkoutName = (EditText) findViewById(R.id.workout_name1); and then immediately ask for the input value through workoutName = mWorkoutName.getText().toString();, but at this time the user still hasn't entered anything. You should put that second line in the listener below (so its activated only after the user presses mNextButton. It's a good idea to put some check after it and send a message to user that they need to fill in that field (if it is indeed necessary).
Looks like the values for workoutName and workoutDays are not filled in initially when the view is created. You should move retrieving the value from the text fields to your onClickListener function.
you checking the CheckBox and EditText in onCreate, absolutely the EditText will be empty and all CheckBox it not checked
I have a problem. I do not know how to call a different class. the code is for a button (when you click the button a message appears in random) so i thought it would be better if i placed it in a different class as i have also used arrays.Now i do not know how to call the class.
This is my code.I want to call "Firstin" inside SecondActivity.
public class SecondActivity extends Activity {
private Firstin mFirst = new Firstin ();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//finds textview
final Text Ftext = (Text) findViewById(R.id.textView2);
#SuppressWarnings("unused")
final Text Stext = (Text) findViewById(R.id.textView3);
//finds button view
Button btnView = (Button) findViewById(R.id.button1);
#SuppressWarnings("unused")
Button btnView2 = (Button) findViewById(R.id.button2);
btnView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String Answer = mFirst.firstAnswer();
Ftext.setTextContent(Answer);
}
});
this is the class I'm trying to call:
package com.example.insultgenerator;
import java.util.Random;
public class Firstin {
public String firstAnswer(){
String [] mResults={
"its cool",
"we cool",
"im cool",
"he cool",
"she cool"
};
// the button was clicked so replace the answer label with answer
String Answer = "" ;
// the two double is a 'empty string
Random RandomGen = new Random();// telling the program to construct a random generator
int RandomNum= RandomGen.nextInt(mResults.length);
Answer = mResults[RandomNum];
return(Answer);
}
}
You should cast to TextView
final TextViewFtext = (TextView) findViewById(R.id.textView2);
#SuppressWarnings("unused")
final TextViewStext = (TextView) findViewById(R.id.textView3);
then use TextView.setText(...) method:
String Answer = mFirst.firstAnswer();
Ftext.setText(new Firstin().firstAnswer());
}
});
then last call the method from the other class with new Firstin().firstAnswer() which creates a instance of the class and executes the method.
I am making an application in which i have to fetch item name and price from first activity to another and i am able to do that but in second activity i am allowing user to put quantity in numbers and whenever user will click on button a TextView to show total amount, but not able to calculate total Amount for item.
I know this is very simple task to do but i am getting error while write this line in button onClick():
txtResult=txtCost*txtQty
here i am placing second activity code,
please correct this one:-
public class SecondScreenActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
TextView txtName = (TextView) findViewById(R.id.txtName);
TextView txtCost = (TextView) findViewById(R.id.txtCost);
EditText txtQty=(EditText)findViewById(R.id.txtQty);
Button btnClose = (Button) findViewById(R.id.btnCalculate);
TextView txtResult = (TextView) findViewById(R.id.txtResult);
Intent i = getIntent();
// Receiving the Data
String name = i.getStringExtra("name");
String cost = i.getStringExtra("cost");
// Displaying Received data
txtName.setText(name);
txtCost.setText(cost);
// Binding Click event to Button
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Closing SecondScreen Activity
//finish();
txtResult=txtCost*txtQty;
}
});
}
}
You can do it by
int cost = Integer.parseInt(txtCost.getText().toString());
int qty = Integer.parseInt(txtQty.getText().toString());
int result = cost*qty;
and then set this result into txtResult
txtResult.setText(result+"");
or you can convert int to String and then apply setText
Why are to multiplying value in Textview
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Float f_name = new Float(name);
Float f_cost = new Float(cost);
Float f_result=f_name *f_cost ;
txtResult.setText(f_result);
}
});
}
}
txtResult=txtCost*txtQty;
These are TextView objects. You can't do maths on objects. Get the textview's values into integers and then try to multiply.
Do something like this.. depending on the type of variable you want (integer, float, double).
int a = new Integer(txtCost.getText().toString());
int b = new Integer(txtQty.getText().toString());
int c = a * b;
txtResult.setText(d);
There are 2 changes that needs to be made.
Make both txtCost and txtQty global variables.
both these variables cannot be directly multiplied. Instead do somthing like this.
double cost = Double.parseDouble(txtCost.getText().toString());
double qty = Double.parseDouble(txtQty.getText().toString());
txtResult = cost * qty ;
I am unsure as to how to approach this.
I have taken some guidelines given by another person on here and have now gotten to the point of it crashing when I push the button (the monitor)
http://i.stack.imgur.com/C8WgN.png
I want to be able to post a toast notification when the button is pushed, and then have it go away after a few seconds
Also, is there a way to do it to where it will still create a toast notification although some of the info (like line2) is empty?
basic.java:
public class Basic extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic);
Spinner spinner = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.state_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final Button display = (Button) findViewById(R.id.Button01);
display.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText firstField = (EditText) findViewById(R.id.First);
EditText lastField = (EditText) findViewById(R.id.Last);
EditText line1Field = (EditText) findViewById(R.id.Line1);
EditText line2Field = (EditText) findViewById(R.id.Line2);
EditText cityField = (EditText) findViewById(R.id.City);
EditText stateField = (EditText) findViewById(R.id.Spinner01);
EditText zipField = (EditText) findViewById(R.id.Zip);
//EditText phoneField = (EditText) findViewById(R.id.Telephone);
final Editable firstName = firstField.getText();
final Editable lastName = lastField.getText();
final Editable lineOne = line1Field.getText();
final Editable lineTwo = line2Field.getText();
final Editable city = cityField.getText();
final Editable state = stateField.getText();
final Editable zip = zipField.getText();
//final Editable phoneNumber = phoneField.getText();
Toast toDisplay = Toast.makeText(null, firstName, 10);
toDisplay.show();
}
});
}
}
I would like the layout of the toast to be multi-lined, and looking like a postal address
First Last
Street Line 1
Line 2
City, State Zip
Toast.makeText(Change.this, "First Last \n Street Line 1 \n Line 2 \n City, State Zip", Toast.LENGTH_SHORT).show();
By using above toast we can display the output in multilines.In above statement i am using static text in that place u put required fieds like
Toast.makeText(Change.this, firstField.getText().toString()+"\n"+ lastField.getText().toString()+"\n"+ City.getText().toString(), Toast.LENGTH_SHORT).show();