Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am making a distance converter app.
The code compiles perfectly and runs too. But when i click on the button "Calculate" it says
The application Converter(process com.example.converter) has stopped
unexpectedly.Please try again
The Logcat Screenshot:
The MainActivity.java code is :
package com.example.converter;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends Activity {
// public var
private EditText text;
// default func
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// findViewById = Finds a view that was identified by the id attribute
// from the XML that was processed in onCreate(Bundle).
// (EditText) = typecast
text = (EditText) findViewById(R.id.editText1);
}
// default func
#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;
}
/*
* Will be executed by clicking on the calculate button because we assigned
* "calculate" to the "onClick" Property!
*/
public void calculate(View view) {
RadioButton mileButton = (RadioButton) findViewById(R.id.radio0);
RadioButton kmhButton = (RadioButton) findViewById(R.id.radio1);
// if the text field is empty show the message "enter a valid number"
if (text.getText().length() == 0) {
// Toast = focused floating view that will be shown over the main
// application
Toast.makeText(this, "enter a valid number", Toast.LENGTH_LONG)
.show();
} else {
//parse input Value from Text Field
double inputValue = Double.parseDouble(text.getText().toString());
// convert to...
if (mileButton.isChecked()) {
text.setText(String.valueOf(convertToMiles(inputValue)));
// uncheck "to miles" Button
mileButton.setChecked(false);
// check "to km/h" Button
kmhButton.setChecked(true);
} else { /* if kmhButton isChecked() */
text.setText(String.valueOf(convertToKmh(inputValue)));
// uncheck "to km/h" Button
kmhButton.setChecked(false);
// check "to miles" Button
mileButton.setChecked(true);
}
}
}
private double convertToMiles(double inputValue) {
// convert km/h to miles
return (inputValue * 1.609344);
}
private double convertToKmh(double inputValue) {
// convert miles to km/h
return (inputValue * 0.621372);
}
}
In code you are saying calculate(View v) while in XML (which is where I am assuming you have defined the onClick) you are saying calc. So basically change it to calculate and it should work.
Related
I want visible button has removed it text from TextView
i am making keyboard typing in text view I have 4 buttons b1,b2,b3,backspace.
when I clicking on b1 typing in textview "A" and b1 invisible
then when I clicking backspace button its remove last char but does not appear last button has clicked
my project
https://youtu.be/_pLEUevM8aA
java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//my buttons
Button b1,b2,b3,backspace;
//my text view
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView)findViewById(R.id.txt);
b1 = (Button)findViewById(R.id.b1);
b2 = (Button)findViewById(R.id.b2);
b3 = (Button)findViewById(R.id.b3);
backspace = (Button)findViewById(R.id.backspace);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
backspace.setOnClickListener(this);
}
//on clike listener
#Override
public void onClick(View view) {
switch (view.getId()){
//b1 on click
case R.id.b1:
txt.setText(txt.getText().toString() + b1.getText());
b1.setVisibility(View.INVISIBLE);
break;
//b2 on click
case R.id.b2:
txt.setText(txt.getText().toString() + b2.getText());
b2.setVisibility(View.INVISIBLE);
break;
//b3 on click
case R.id.b3:
txt.setText(txt.getText().toString() + b3.getText());
b3.setVisibility(View.INVISIBLE);
break;
//here is my problem last char has deleted button of that char must be get visible
//backspace on click
case R.id.backspace:
//I want visible button has removed it text from TextView
//appear last button has clicked
txt.setText(txt.getText().toString().substring(0,txt.getText().toString().length()-1));
break;
}//end switch
} //I hope get answer in this website
}
//thank for ALL helping
You could create a Stack of pressed buttons, so that you would know in which order they are pressed:
public class MainActivity extends ... implements ...{
Stack<View> pressedButtons = new Stack<>();
...
#Override
public void onClick(View view) {
// If it is a number, not a backspace key - remember that we pressed it
if(view.getId() != R.id.backspace) {
pressedButtons.push(view);
txt.setText(txt.getText().toString() + ((Button) view).getText());
view.setVisibility(View.INVISIBLE);
}
else { // backspace key
String text = txt.getText().toString();
if(text.isEmpty())
return; // do this to prevent crash
txt.setText(text.substring(0, text.length() - 1));
// make the button visible again
View lastPressedButton = pressedButtons.pop();
lastPressedButton.setVisibility(View.VISIBLE);
}
}
}
You can try this:
case R.id.backspace:
//try like this
if(string.substring(string.length() - 1).equals(b3.getText()))
b3.setVisibility(View.VISIBLE);
...
txt.setText(txt.getText().toString().substring(0,txt.getText().toString().length()-1));
I'm developing a "guess the number" app, it generates a random number between 1 and 10,000 and you have to try guessing, it will tell you if your prediction it is too big , etc
But when you press the button to probe your number, it generates a new random number every time you press the button.Keep in mind i'm a newbie so i'm learning java for android, but i want to know how to make this simple app.
Here's my code:
package com.boodle.guessthenumber;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void guess (View view){
EditText textguess = (EditText) findViewById ( R.id.textguess );
TextView resulta = (TextView) findViewById(R.id.resulto);
String guessStr = textguess.getText().toString();
int theGuess = Integer.parseInt(guessStr);
int rand = (int) (Math.random()*10000+1);
if (theGuess > rand) {
resulta.setText(textguess.getText() + " is too big" );
}
if (theGuess < rand) {
resulta.setText(textguess.getText() + " is too small" );
}
if (rand == theGuess){
resulta.setText(textguess.getText() + " is the answer" );
}
}
}
Create rand as a member variable in your class:
public class MainActivity extends ActionBarActivity {
int rand;
initialize in onCreate():
rand = (int) (Math.random()*10000+1);
remove the initialization in your guess() function:
// not needed anymore:
// int rand = (int) (Math.random()*10000+1);
To make the number persist during orientation changes, add this code to your Activity:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("rand", rand);
super.onSaveInstanceState(savedInstanceState);
}
and then in onCreate() change your random number generation code to this:
if (savedInstanceState != null)
rand = savedInstanceState.getInt("rand");
else
rand = (int) (Math.random()*10000+1);
After you generate the number you have to store it in a persistent storage, for which you have many options: SharedPreferences (which can be passed between activities), a file, SQLiteDatabase...
When the activity starts, only if the number is not there - generate it!
The solution would be to create your random number in onCreate such that it is only created once and then simply access that variable in your guess method. Modify your code as follows:
public class MainActivity extends ActionBarActivity
{
private int rand;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
rand = (int) (Math.random()*10000+1);
}
// rest of code...
And then in guess remove the initialization and simply access the variable by name:
public void guess (View view)
{
// rest of code...
//int rand = (int) (Math.random()*10000+1);
if (theGuess > rand) {
resulta.setText(textguess.getText() + " is too big" );
}
// rest of code...
}
Also, just as a note, it is not necessary to post all the import statements and other similar code. Only posting the code relevant to your issue is the best way to invite concise answers.
The following solution will generate the number when the activity is started and the number will NOT change when the user rotates the screen. It will also make the activity a little bit more effective.
public class MainActivity extends ActionBarActivity {
TextView mResult;
EditText mTextGuess;
private int mNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
// you find your views in onCreate once, they don't change, it's effective
mResult = (TextView) findViewById(R.id.resulto);
mTextGuess = (EditText) findViewById(R.id.textguess);
// BRO-TIP: Google "Butterknife".
// Now you need to initialize the random number
// BUT you want it to stay the same when user rotates the screen, right?
if (savedInstanceState == null) {
// when the user first opens the app, generate new number
mNumber = (int) (Math.random()*10000+1);
} else {
// otherwise load the previously generated number from saved state
mNumber = savedInstanceState.getInt("mNumber");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// here you save the number across orientation changes
outState.putInt("mNumber", mNumber);
}
public void guess(View v) {
int theGuess = Integer.parseInt(mTextGuess.getText().toString());
// else-if is better for you: when the first is true, you don't need to check the others and so on...
if (theGuess > rand) {
mResult.setText(textguess.getText() + " is too big" );
} else if (theGuess < rand) {
mResult.setText(textguess.getText() + " is too small" );
} else if (rand == theGuess){
mResult.setText(textguess.getText() + " is the answer" );
}
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
package com.elitiv.calculatorvamalv2;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
private EditText editYear;
private EditText editCapacity;
private EditText Result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView Year = (TextView)findViewById(R.id.Year);
TextView Capacity = (TextView)findViewById(R.id.Capacity);
editYear = (EditText)findViewById(R.id.editYear);
editCapacity = (EditText)findViewById(R.id.editCapacity);
Result = (EditText)findViewById(R.id.Result);
Button calc =(Button)findViewById(R.id.calc);
final RadioButton RadioD = (RadioButton)findViewById(R.id.radioD);
final RadioButton RadioB = (RadioButton)findViewById(R.id.radioB);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double editYear = editYear.getText().toString();
double editCapacity = editYear.getText().toString();
if(RadioB.isChecked()){
switch(editYear){
case 2014:
if(editCapacity >0 && NCapacity <1000){
Result = editCapacity*0.57;
}
if(editCapacity >1000 && editCapacity <1500){
Result = editCapacity*0.67;
}
if(editCapacity >1501 && editCapacity <2000){
Result = editCapacity*1.00;
}
break;
}
}
});
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
});
}
}
I'm trying to make a simple app that is adding 2 values by a condition, itdidn't compile the app yet because of 2 errors:
Syntax error on token ")", { expected MainActivity.java /CalculatorVamalV2/src/com/elitiv/calculatorvamalv2 line 65 Java Problem
Syntax error, insert "}" to complete ClassBody MainActivity.java /CalculatorVamalV2/src/com/elitiv/calculatorvamalv2 line 86 Java Problem
When android studio gives me a problem i switch to eclipse and viceversa.
The error messages are very descriptive. Check file MainActivity.java, line 65 and fix it. Similar for line 86.
Anyway, these are the errors:
Syntax error on token ")", { expected MainActivity.java /CalculatorVamalV2/src/com/elitiv/calculatorvamalv2 line 65 Java Problem
You missed a close brace } in the inner class definition:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView Year = (TextView)findViewById(R.id.Year);
TextView Capacity = (TextView)findViewById(R.id.Capacity);
editYear = (EditText)findViewById(R.id.editYear);
editCapacity = (EditText)findViewById(R.id.editCapacity);
Result = (EditText)findViewById(R.id.Result);
Button calc =(Button)findViewById(R.id.calc);
final RadioButton RadioD = (RadioButton)findViewById(R.id.radioD);
final RadioButton RadioB = (RadioButton)findViewById(R.id.radioB);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double editYear = editYear.getText().toString();
double editCapacity = editYear.getText().toString();
if(RadioB.isChecked()){
switch(editYear){
case 2014:
if(editCapacity >0 && NCapacity <1000){
Result = editCapacity*0.57;
}
if(editCapacity >1000 && editCapacity <1500){
Result = editCapacity*0.67;
}
if(editCapacity >1501 && editCapacity <2000){
Result = editCapacity*1.00;
}
break;
}
}
} // <-- add this here
});
}
Syntax error, insert "}" to complete ClassBody MainActivity.java /CalculatorVamalV2/src/com/elitiv/calculatorvamalv2 line 86 Java Problem
You don't have an anonymous class here, so there's no need to have );:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Besides this, you have an additional brace } at the end of the definition of your class.
How to avoid these problems?
Indent your code. Since you're using eclipse and android development studio (based on Eclipse), you have this shortcut to let the IDE auto format the code automatically for you: Ctrl + Shift + F.
There's a quick and easy way to identify } ) and ; errors in Eclipse. I can see your spacing and indentation is off and not standardized.
While in Eclipse, highlight your entire class, or press ctrl-a.
Then hold down shift-ctrl and press f. This automatically formats your code and indents properly. This should make it easy to find out where you are missing the }. I know this works in the Windows build of Eclipse.
While trying to run my app, I noticed that a few errors claiming that many variables can not be resolved, even though declared in the code
i changed it to the following code, but once I enter the app, it collapses:
public String GetErr(){
String error="";
if(Facebook_name.toString().equals("")&& Facebook_chk.isChecked())//check with title if not available.
{
error+="facebook account not entered/n";//also check if not available
}
if(Name.toString().equals(""))
error+="Name not entered/n";
if(Id.toString().contains("[a-zA-Z]+") || Id.toString().equals(""))
error+="Id entered is invalid/n";
if(Pass.toString().length()<5 || Pass.toString().equals(""))
error+="Passwords must contain 5 or more digits";
// int day= Date.getDayOfMonth();
// int month = Date.getMonth();
// int year=Date.getYear();
//Calendar enter = Calendar.getInstance();
// Calendar today = Calendar.getInstance();
// enter.set(year,month,day);
// today.set(Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_MONTH);
//if((enter.getTime().before(today.getTime())))
// error+="Date entered either passed or not available.";
return error;
}
EDIT: Now the geterr() returns an empty string at all times.
You are declaring variables in the onCreate() method, so that is their scope. You can not use them outside this function. So when you use them in the GetErr() method, you get an error. You can solve this by moving the variables you need in multiple methods to global variables (so declare them in the class instead of in the method.
Edit
package com.example.app;
//import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
//import android.widget.DatePicker;
import android.widget.TextView;
public class Second extends Activity implements OnClickListener {
CheckBox Facebook_chk;
TextView Facebook_name;
TextView Name;
TextView Id;
TextView Txterr;
TextView Pass;
Button Btn1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.second);
Btn1 = (Button) findViewById(R.id.Btn1);
Facebook_chk = (CheckBox)findViewById(R.id.Cfbook);//Represents the facebook checkbox.
Facebook_name = (TextView)findViewById(R.id.Face);//represents the facebook text.
Name = (TextView)findViewById(R.id.Name);//represents the Name text.
Id = (TextView)findViewById(R.id.Id);//represents the Id text.
Txterr = (TextView)findViewById(R.id.Txterr);//represents the Id text.
Pass = (TextView)findViewById(R.id.Pass);//represents the Pass text.
Btn1.setOnClickListener(this);
Facebook_chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if(Facebook_chk.isChecked())
Facebook_name.setEnabled(true);
else
Facebook_name.setEnabled(false);
;
}
});
}
public String GetErr(){
String error="";
if(Facebook_name==null && Facebook_chk.isChecked())//check with title if not available.
{
error+="facebook account not entered/n";//also check if not available
}
if(Name==null)
error+="Name not entered/n";
if(Id.toString().contains("[a-zA-Z]+") || Id==null)
error+="Id entered is invalid/n";
if(Pass.toString().length()<5)
error+="Passwords must contain 5 or more digits";
// int day= Date.getDayOfMonth();
// int month = Date.getMonth();
// int year=Date.getYear();
//Calendar enter = Calendar.getInstance();
// Calendar today = Calendar.getInstance();
// enter.set(year,month,day);
// today.set(Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_MONTH);
//if((enter.getTime().before(today.getTime())))
// error+="Date entered either passed or not available.";
return error;
}
#Override
public void onClick(View v) {
if(v == Btn1){
String err = GetErr();
if(err != ""){
Txterr.setText(err);
}
}
}
}
define:
CheckBox Facebook_chk
TextView Facebook_name
TextView Name
TextView Id
TextView Txterr
TextView Pass
As Global Variables, like:
public class Second extends Activity implements OnClickListener {
CheckBox Facebook_chk;
TextView Facebook_name;
TextView Name;
TextView Id;
TextView Txterr;
TextView Pass;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.second);
Facebook_chk = (CheckBox)findViewById(R.id.Cfbook);//Represents the facebook checkbox.
Facebook_name = (TextView)findViewById(R.id.Face);//represents the facebook text.
Name = (TextView)findViewById(R.id.Name);//represents the Name text.
Id = (TextView)findViewById(R.id.Id);//represents the Id text.
Txterr = (TextView)findViewById(R.id.Txterr);//represents the Id text.
Pass = (TextView)findViewById(R.id.Pass);//represents the Pass text.
...
}
...
}
UPDATE:
If you would like to make a View to respond for Click Event, you'll need to make sure you've set that View clickable.
Since you did:
View v = findViewById(R.id.Btn1);
v.setOnClickListener((OnClickListener) this);
I've no idea R.id.Btn1 is really a Button or just a View. If it is a Button, please change to:
Button button = findViewById(R.id.Btn1);
button.setOnClickListener(this);
If it's not a button, just some View and you want it to respond to your Click, please add one line after findViewById
v.setClickable(true);
Again, if you intend to use this v sometime later in your code, you need to declare it as a global variable just like you did on your TextViews
Ref public void setClickable (boolean clickable)
I'm working on an app that involved comparing to numbers inputted by the user via text box, but wen I put in any if statements the program crashes whenever they are called. Otherwise the program runs just fine without any crashes or errors.
package improvecredit.app.basic;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.text.Editable;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ImprovrCreditBasicActivity extends Activity {
/** Called when the activity is first created. */
public int minCredScore = 300;
public int maxCredScore = 850;
public int inputScore;
public int idealScore;
public Editable inputString;
public Editable idealString;
public EditText user;
public EditText desired;
public TextView output;
public Button submit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
user = (EditText) findViewById(R.id.user_text);
desired = (EditText) findViewById(R.id.desired_text);
output = (TextView) findViewById(R.id.output_text);
submit = (Button) findViewById(R.id.submit_button);
//submit.setOnClickListener(new View.OnClickListener());
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//inputString = user.getText();
//idealString = desired.getText();
inputScore = Integer.getInteger(user.getText().toString());
idealScore = Integer.getInteger(desired.getText().toString());
if (inputScore >= 0 && idealScore >= 0){
if (inputScore < minCredScore || idealScore < minCredScore){
output.setText("Invalid Entries");
}
if (inputScore > maxCredScore || idealScore > maxCredScore){
output.setText("Invalid Entries");
}
if (inputScore > idealScore){
output.setText("Nice Credit Score!");
}
if (inputScore < idealScore){
output.setText("For more information on how to improve your credit score, please visit" + "/n" + "http://www.creditscoresandcredit.com/");
}
}
else{
output.setText("Please enter valid credit scores");
}
}
});
}
If someone can point out what may have been done wrong in the code I would really appreciate it.
On first glance, don't use Integer.getInteger(), use Integer.parseInt().
If that doesn't fix it, please include the crash log from the console so we can see exactly what exception is being raised.
I'm betting that there is a null value introduced. If you check for null before using the variables idealScore and inputScore in the If statement, it will avoid this error. Until you paste the error trace, we can only guess for you.