I am really new at programming. I am trying to run a simple average calculator and getting a force close, this is what the logcat is showing. I am running android studio version 2.3.3
FATAL EXCEPTION: main
Process: com.vu.gradingapp, PID: 6312
java.lang.NumberFormatException: For input string: ""
at java.lang.Integer.parseInt(Integer.java:620)
at java.lang.Integer.valueOf(Integer.java:794)
at com.vu.gradingapp.AverageActivity$1.onClick(AverageActivity.java:37)
at android.view.View.performClick(View.java:6219)
at android.view.View$PerformClick.run(View.java:24482)
at android.os.Handler.handleCallback(Handler.java:769)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
The code i am using is as follow
public class AverageActivity extends AppCompatActivity {
EditText editmanner, editinstances, editshortstance, editstrikes, editboxingskills, editknocks, editkicks, editResults;
Button btnResults;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.average_page);
editmanner =(EditText)findViewById(R.id.editText8);
editinstances = (EditText)findViewById(R.id.editText9);
editshortstance = (EditText)findViewById(R.id.editText10);
editstrikes = (EditText)findViewById(R.id.editText11);
editboxingskills = (EditText)findViewById(R.id.editText12);
editknocks = (EditText)findViewById(R.id.editText13);
editkicks = (EditText)findViewById(R.id.editText14);
editResults = (EditText)findViewById(R.id.editText15);
btnResults = (Button) findViewById(R.id.button10);
btnResults.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
int first, second, third, fourth, fifth, sixth, seventh, results;
first=Integer.valueOf(editmanner.getText().toString());
second=Integer.valueOf(editinstances.getText().toString());
third=Integer.valueOf(editshortstance.getText().toString());
fourth=Integer.valueOf(editstrikes.getText().toString());
fifth=Integer.valueOf(editboxingskills.getText().toString());
sixth=Integer.valueOf(editknocks.getText().toString());
seventh=Integer.valueOf(editkicks.getText().toString());
results=(first+second+third+fourth+fifth+sixth+seventh)/7;
editResults.setText(String.valueOf(results));
}
});
}
public void knowtheresults (View view) {
String button_text;
button_text = ((Button) view).getText().toString();
if (button_text.equals("Summary")) {
Intent intent = new Intent(this, ResultActivity.class);
startActivity(intent);
} else if (button_text.equals("Back")) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
WHat am I doing wrong :D
Thanks Guys
Error says you cannot convert "" value to number Its a java.lang.NumberFormatException. So use 0 instead of number is blank first check if edittext is blank than set its value to 0
int first;
if(editmanner.getText().toString().equals("")){
first = 0
}else{
first = Integer.valueOf(editmanner.getText().toString());
}
do this for your all int variables.
Update your code with such verification for each int variable:
if (editmanner().toString().isEmpty())
first = 0;
else
first = Integer.parseInt(editmanner().toString());
Since you have int variables (not Integer) it is preferable to use parseInt instead valueOf
Thanks guys, I just filled in the textedits with (0) and now is working. Please apologize for my silly questions.
Is there any way to hide this zeros on the textview so it shows blanks.
java.lang.NumberFormatException
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
The logcat already stated what is the cause of the crash. One or all of your EditText has empty string. To convert string to Integer, the string must be numeric(0,1,2 etc). You need to set EditText with numeric value (eg: 0).
Related
so I want to create a Rock Paper Scissors app that should work like this:
In the first screen you enter the names of the 2 players.
In the second screen there are the names of the players and the score of each player near it.The progress is that you need to click a button,and after you click it,in each player's side,random image(rock paper or scissors) will appear and the winner will get a point,or nobody will if its a draw.
NOTE:This might not be an error in the code based on what i've seen when I tried to search for the message i'm getting while debugging so you may want to look at it first.
I would appreciate some comments on the code though.
I checked if the names that i'm passing from the first activity to the second one before I had started to work on the button and the app worked fine.
But after I wrote the code for the OnClickListener, the app just crashes instantly after the first activity when I run it. It is my first time working with images like that so i'm not sure that if used it properly. I have created some functions so the code will be more readable without knowing exactly what i'm doing though because i'm pretty new to android.
first activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startBtn;
startBtn = findViewById(R.id.startBtn);
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText p2Name=findViewById(R.id.p2EditText);
EditText p1Name=findViewById(R.id.p1EditText);
String name1=p2Name.getText().toString();
String name2=p1Name.getText().toString();
Intent intent1 = new Intent(MainActivity.this, Game.class);
intent1.putExtra("name1",name1);
intent1.putExtra("name2",name2);
MainActivity.this.startActivity(intent1);
}
});
}
second activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
String p1Name;
String p2Name;
if (getIntent().hasExtra("name1")) {
p1Name = getIntent().getStringExtra("name1");
TextView p1NView = findViewById(R.id.p1);
p1NView.setText(p1Name);
}
if (getIntent().hasExtra("name2")) {
p2Name = getIntent().getStringExtra("name2");
TextView p2NView = findViewById(R.id.p2);
p2NView.setText(p2Name);
}
Button NRound=findViewById(R.id.newRoundBtn);
NRound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView score1=findViewById(R.id.score1View);
TextView score2=findViewById(R.id.score2View);
int p1Score = Integer.parseInt(score1.getText().toString());
int p2Score = Integer.parseInt(score2.getText().toString());
String[] RPS = new String[]{"rock", "paper", "scissors"};
Random r = new Random();
String p1Hand;
String p2Hand;
p1Hand = RPS[r.nextInt(3)];
p2Hand = RPS[r.nextInt(3)];
showImages(p1Hand,p2Hand);
String result=findWinner(p1Hand,p2Hand);
switch (result){
case "player1":
p1Score++;
score1.setText(String.valueOf(p1Score));
case "player2":
p2Score++;
score2.setText(String.valueOf(p2Score));
if(score1.getText().equals('3') || score2.getText().equals('3')){
Intent end=new Intent(Game.this,EndScreen.class);
Game.this.startActivity(end);
}
}
}
});
update();
}
public static String findWinner(String hand1,String hand2){
if(hand1.equals(hand2)){
return "draw";
}
String both=hand1.concat(hand2);
if(both.equals("rockscissor") || both.equals("paperrock")||both.equals("scissorspaper")){
return "player1";
}else{
return "player2";
}
}
public void showImages(String hand1,String hand2){
ImageView rock1=findViewById(R.id.rock1);
ImageView paper1=findViewById(R.id.paper1);
ImageView scissors1=findViewById(R.id.scissors1);
ImageView rock2=findViewById(R.id.rock2);
ImageView paper2=findViewById(R.id.paper2);
ImageView scissors2=findViewById(R.id.scissors2);
switch (hand1){
case "rock":
rock1.setVisibility(View.VISIBLE);
case "paper":
paper1.setVisibility(View.VISIBLE);
case "scissors":
scissors1.setVisibility(View.VISIBLE);
}
switch (hand2){
case "rock":
rock2.setVisibility(View.VISIBLE);
case "paper":
paper2.setVisibility(View.VISIBLE);
case "scissors":
scissors2.setVisibility(View.VISIBLE);
}
}
public void update(){
ImageView[] images=new ImageView[6];
for (ImageView image:images)
{
if(image.getVisibility()==View.VISIBLE){
image.setVisibility(View.GONE);
}
}
}
Logs
Edit:now after I have posted and seen the logs I understood what was the problem. I forgot to initialize the imageView array in a function and I was just looping over null array,trying to get its visibility.And Now it does not crash.
I didn't know about this so thanks anyways for telling me to post it.(thought errors should show up in the console or something).
Now I am dealing with another problem,I will try to solve it on my own though.
Process: com.example.rockpaperscissors, PID: 11607
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rockpaperscissors/com.example.rockpaperscissors.Game}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.ImageView.getVisibility()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3260)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3396)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2009)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.ImageView.getVisibility()' on a null object reference
at com.example.rockpaperscissors.Game.update(Game.java:71)
at com.example.rockpaperscissors.Game.onCreate(Game.java:65)
at android.app.Activity.performCreate(Activity.java:7783)
at android.app.Activity.performCreate(Activity.java:7772)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3235)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3396)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2009)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
I tried to debug the app and at the last line of the first activity,the message that shows up is: source code does not match the byte code.
First try to clean the project and rebuild it.
In order for us to help you with the crash, we need to see the logs. Please add that as well.
About your code:
MainActivity.class
Try validating user input before passing it to the next activity.
Game.class (assuming this is also an activity so try renaming it to GameActivity.class)
When you are retrieving data from the intent, it's best practice to create a constant and make it public that you can use in the main activity as well (if you make a typo, it's hard to find the problem)
Something like: public static final String NAME_ONE_KEY = "name1";
I don't see the need of using a string array, identify those actions by integer and comment it so you and others who read your code can understand it.
It seems like you have a lot of child elements in your game layout file
Add the images into the drawable folder, create one image view for each player and update the image source.
Finally, save the state so you don't loose the data on device rotation.
I am newbie at this javascript and android stuff.
I'm tried to add two number taken from "EditView" and display it in other activity.
But it's didn't show up anything.
here are the code.
public void lihathasil(View v) {
thn1 = (EditText) findViewById(R.id.datat1);
thn2 = (EditText) findViewById(R.id.datat2);
thn3 = (EditText) findViewById(R.id.datat3);
thn4 = (EditText) findViewById(R.id.datat4);
thn1cus = Integer.parseInt(thn1.getText().toString());
thn2cus = Integer.parseInt(thn2.getText().toString());
thn3cus = Integer.parseInt(thn3.getText().toString());
thn4cus = Integer.parseInt(thn4.getText().toString());
ab = thn1cus + thn2cus + thn3cus + thn4cus;
Intent i = new Intent(getApplicationContext(), GeneralReport.class);
i.putExtra("pertama",ab);
startActivity(i);
}
And here are the code in other activity to view the result
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_general_report);
tam1=(TextView) findViewById(R.id.tampilsatu);
val1=getIntent().getExtras().getString("pertama");
tam1.setText(val1);
}
when i run it's display nothing.
can anyone help to solved it.
thanks
You pass the integer value in one activity and get the string value in other activity.
Other activty code :
val1=getIntent().getExtras().getIntExtra("pertama",0);
tam1.setText(String.valueof(val1));
In your second Activity change this
val1=getIntent().getExtras().getString("pertama");
to this
val1=getIntent().getIntExtra("pertama", 0);
and change this
tam1.setText(val1);
to this
tam1.setText(String.valueOf(val1));
// Assuming val1 is defined as integer
I was trying to make a quiz app, that would change the question every time you submit, and it should work except for .equals doesn't work, and it cannot resolve the symbol.
its crazy! Any nelp would be apreciated
I guess you have added above code portion outside of a Method(life-cycle callback method or your own method) that's why you are getting error:
cannot resolve symbol 'equals'.
SOLUTION:
Just move your code portion inside a method. Here is an example:
#Override
protected void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
..........
.................
int QuizSelection = 20;
Intent gotosetone = getIntent();
Intent gotosetone2 = getIntent();
String randomintent1 = gotosetone.getStringExtra(AlarmClock.EXTRA_MESSAGE);
String randomintent2 = gotosetone2.getStringExtra(AlarmClock.EXTRA_MESSAGE);
if (randomintent1.equals("Quiz One")){
QuizSelection = 1;
} else if (randomintent2.equals("Quiz Two")){
QuizSelection = 2;
}
...........
..................
}
Hope this will help~
I was wanting to be able to have a button which would launch the Google Maps app, however I cannot really seem to be able to get it to work, could I have some help? Really sorry if this seems easy, i'm still a newbie with android, below is my oncreate method with the relavent Intents
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setIcon(R.drawable.ic_action_headphones);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
Button mapsbtn = (Button) findViewById(R.id.mapbtn);
mapsbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String uri = String.format(Locale.ENGLISH, "geo:%f,%f");
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);
}
});
}
My app keeps crashing when the button is pressed, and the error i am receiving is
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: juddsafc.actionbarexample, PID: 2980
java.util.MissingFormatArgumentException: Format specifier: f
Thanks in advance!
When you put %f,%f you need to provide values afterwards... So change this:
String uri = String.format(Locale.ENGLISH, "geo:%f,%f");
to this:
String uri = String.format(Locale.ENGLISH, "geo:%f,%f", 35.6833, -139.7667); // numbers are just some random coordinates
String uri = String.format(Locale.ENGLISH, "geo:%f,%f");
The %f is a formatter. Your program expects a value to replace %f, but there's not enough arguments for your function to accomplish this.
You could do the following:
String uri = String.format(Locale.ENGLISH, "geo:%f,%f", 100, 200);
And instead of using 100 and 200, you pass along the values you want to display.
In the Following code I am taking an answer from a user for a mathematical question. When the answer is entered the question then updates to a new one.
How would I add validation so that when a user enters letters or hits submit without entering an answer, the question just stays the same and allows the user to enter again. At the minute, when that happens the app crashes. (note: Main functionality I am refering to occurs in onClick).
public class PracticeTest extends Activity implements View.OnClickListener{
//declare vars
int multiplier;
int[] results=new int[12];
int numberPassed;
TextView question;
EditText answer;
int score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.practicetest);
// This declares and int variable, assigns it an int value from the
// calling Intent if its not there it is defaulted to 0
numberPassed = getIntent().getIntExtra("convertedNumber2", 0);
//setting up vars(possibly do this in different method?
Button submit = (Button) findViewById(R.id.btnGoPractice2); //declared here as it is only used once
answer = (EditText) findViewById(R.id.etEnterNumberPractice2);
question = (TextView) findViewById(R.id.tvTopPractice2);
//setting listeners
submit.setOnClickListener(this);
updateQuestion();
}
public void onClick(View view) {
// sets text view equal to whats typed in in editText
final String entry = answer.getText().toString();
// convert from string value to int
int a = Integer.parseInt(entry); //note: maybe change name
results[multiplier-1]=a;
score++;//Irrelevant?
if(multiplier<12){
//called after an answer is given
updateQuestion();
} else{
//System.out.println(score);
Intent intent = new Intent(this, Results.class);
intent.putExtra("results", results);
intent.putExtra("numberPassed", numberPassed);
this.startActivity(intent);
}
}
public void updateQuestion(){
multiplier++;
//string to hold quest
String q= numberPassed + "x" + multiplier + "=";
question.setText(q);
answer.setText("");
}
}
So entry is the answer you get? Maybe try regex, you can use this code after submitting the answer or you could check this when a user edits the EditText. The last thing can be done with a TextWatcher, but that would make it a bit more complicated than necessary.
if(entry.matches("[0-9]+") {
// new question
} else {
// warning no valid answer
}
If you want your users only have the option to input numbers. You should set in your EditText:
android:inputType="number"