I am new to android programming and am trying to the program to run but the problem is that the app builds and runs successfully but crashes whenever I press the GO button. My professor gave me this to accomplish as something to get started with android programming as he thought it would be challenging task that will be motivational and interesting. I looked everywhere for the solution but could not find it. My professor himself is unable to debug the code and hence.
The code is as given below:
**CODE 1**
package com.example.thispc.myapplication;
import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import java.util.Scanner;
import edu.princeton.cs.algs4.EdgeWeightedDigraph;
import edu.princeton.cs.algs4.DirectedEdge;
import edu.princeton.cs.algs4.BellmanFordSP;
public class Arbitrage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_arbitrage);
Button Check_Arbitrage = findViewById(R.id.Check_Arbitrage);
Check_Arbitrage.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View view) {
EditText inputcurrencynumber;
EditText inputdata;
TextView outputarbitrage;
inputcurrencynumber = findViewById(R.id.GetNoCurrencies);
inputdata = findViewById(R.id.currency_table_input);
outputarbitrage = findViewById(R.id.result);
inputcurrencynumber = findViewById(R.id.GetNoCurrencies);
int V;
V = Integer.parseInt(inputcurrencynumber.getText().toString());
outputarbitrage = findViewById(R.id.result);
double rate,stake;
inputdata = findViewById(R.id.currency_table_input);
EdgeWeightedDigraph G = new EdgeWeightedDigraph(V);
outputarbitrage.setText("Hello World");
String [] name = new String[V];
// The error occures here when i try to take an input
for (int v = 0; v < V ; v++)
{`enter code here`
name[v] = inputdata.getText().toString();
for (int w = 0; w < V ; w++)
{
rate = Double.parseDouble(inputdata.getText().toString());
DirectedEdge e = new DirectedEdge(v, w, -Math.log(rate));
G.addEdge(e);
}
}
BellmanFordSP spt = new BellmanFordSP(G,0);
if (spt.hasNegativeCycle())
{
stake = 1000;
for (DirectedEdge e : spt.negativeCycle())
{
//outputarbitrage.setText((Double.toString(stake) + name[e.from()]) + " " + (Double.toString(stake) + name[e.to()]) + "\n");
outputarbitrage.setText("%10.5f %s " + stake + name[e.from()]);
stake = stake * Math.exp(-e.weight());
outputarbitrage.setText("= %10.5f %s\n" + stake + name[e.to()]);
}
}
else
{
outputarbitrage.setText("No Arbitrage Opportunity Found");
}
}
});
}
}
Note : This code works perfectly in java IDE (I use netbeans) but crashes in android studio.
======================================================================================================================================================
EDIT 1
Added the log as below :
com.example.thispc.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.thispc.myapplication, PID: 4876
java.lang.NumberFormatException: For input string: "USD 1 1.6 4
CAD 2.3 1 1.3
CHF 4 8 1"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:539)
at com.example.thispc.myapplication.Arbitrage$1.onClick(Arbitrage.java:57)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
======================================================================================================================================================
EDIT 2
output
Its getting crash because of the below line
rate = Double.parseDouble(inputdata.getText().toString());
You are trying to parse the string and parseDoubel() expects the string value which only holds numeric value, but in your case inputdata.getText().toString() contains character other than numbers.
Try extracting digits form the inputdata before passing to parseDouble() method
str.replaceAll("[^0-9]", "");
I'm new to android development, I trying to create a simply Pythagorean Calculator, I need help with reading if a lines blank, but still calculates instead of failing.
Here is my code
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText sideAObj;
private EditText sideBObj;
private EditText sideCObj;
private EditText outputObj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sideAObj = (EditText) findViewById(R.id.SideAInput);
sideBObj = (EditText) findViewById(R.id.SideBInput);
sideCObj = (EditText) findViewById(R.id.SideCInput);
outputObj = (EditText) findViewById(R.id.OutputText);
}
public void calculateClick(View v){
try {
double sideA = Double.parseDouble(sideAObj.getText().toString());
double sideB = Double.parseDouble(sideBObj.getText().toString());
double sideC = Double.parseDouble(sideCObj.getText().toString());
if (sideAObj.getText().toString().equalsIgnoreCase("0")) {
double pt = Math.sqrt((sideC * sideC) - (sideB * sideB));
outputObj.setText(String.format("%.2f", pt));
}
}
catch (NumberFormatException ex){
Toast errMess = Toast.makeText(getApplicationContext(),"Enter Numbers Only",Toast.LENGTH_SHORT);
errMess.show();
outputObj.setText(String.format("%2.f",0.00));
return;
}
}
public void clearClick(View v){
sideAObj.setText("");
sideBObj.setText("");
sideCObj.setText("");
outputObj.setText("");
sideAObj.requestFocus();
}
}
My program will calculate if their is a Zero on 1 line, but if I leave it blank the program fails entirely, whats the best way to prevent that.
It will obviously fail as it doesn't know how to parse a blank value into a double. Just use something like this during instantiation itself:
double sideB = (sideBObj.getText().toString() == "") ? 0 : (Double.parseDouble(sideBObj.getText().toString()));
double sideC = (sideCObj.getText().toString() == "") ? 0 : (Double.parseDouble(sideCObj.getText().toString()));
Basically, you will be assigning the value 0 if the edit text field is 0 else, you will parse the value entered to a double.
Assuming you want to consider a 0 if there is a blank edit text field.
========================================================================
UPDATE
if(sideAObj.getText().toString() != ""){
double sideA = Double.parseDouble(sideAObj.getText().toString());
}
The simple solution for this problem would be to check each edittext whether they are blank or not and then perform the task.
Get the value of each Edittext to a int variable and then use loop and with the help of edittext.length() method verify if it is equal to 0, if yes, then assign a value to 0 to a new global variable, else assign the exact value to global variable.
and then perform the calculation with the new variables.
Sample code for better understanding :-
String a = et.getText().toString();
int l = a.length();
if (l == 0){
// set the value of global variable = 0;
} else {
// set the value of global variable = a {Actual Digit}
}
On running the application, it displays an error as"Unable to start activity.. ComponenInfo" with length =64 and index=64 and the app crashes. Is there any solution to it?
package com.mayank.app.quizoclash;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class game extends AppCompatActivity implements View.OnClickListener {
private TextView ques, score, quesno,time;
Button opt1, opt2, opt3, opt4,image;
String phone,phone1,name,college,regno;
int count1=0;
int count=0;
int i=0,j=0,k=1;
private String[] question={"What was Slade Wilson's alter ego?","What is the name of this episode?","Which Dire-wolf belonged to Robb?","What is the color of the couch in the coffee shop in F.R.I.E.N.D.S?","How does Sherlock first have his coffee?","Who told the Flash to wear a mask or suit?","What is Kristy Stapleton's rabbit called?",
"What was the name of Monica's Boyfriend who was an alcoholic","What are Daenerys Dragons called","Phoebe changes her name to?","In How I Met Your mother, What is Robin's occupation?","How many friends does Sheldon have on MySpace?(BBT)","Rachel gets a tattoo. What is it?","Which man did this woman go on a date with?",
"In the series \"Arrow,\" who is character Oliver Queen's best friend?","What two characters featured prominently in the TV series did not appeear in the comics version?(The Walking Dead)","This police inspector regularly calls on Holmes to help solve difficult cases.","In what drug (now illegal) was Holmes known to imbibe, from time to time.",
"Who does Sheldon believe has an \"unresolved Oedipus complex\"?(BBT)","What card did Joey think was stolen by the guy who robbed the apartment?","What is \"Arrow\" character John Diggle's profession?","What is the setting for Holmes and Moriarty's final, fatal encounter?","What instrument does Leonard play?(BBT)","How many blocks was Rachel's childhood dog LaPooh dragged?",
"What was T-Dog's real name?(The Walking Dead)","What is Daredevil's alter ego?","What phrase did the Arrow use when he questioned someone on his father's list?","In Season 2, who is the manager of Central Perk?(Friends)","Where did Amy go to college?(BBT)","How did Holmes describe himself professionally?","Unlike many superheroes, Daredevil is deeply religious. What is his faith?",
"Which girl did this guy date?","What was the pendant on the necklace Andrea planned to give Amy for her birthday?","What catastrophic event was the Undertaking, that destroyed a large part of The Glades?","What was the London address of the famous sleuth and his faithful companion, Dr. Watson?","Halfway through the movie, Colin Farrell is introduced as Kingpin's assassin of choice. What is the name of his character, who \"can turn anything into a weapon\"?","In \"The One With the Lottery,\" what is the power ball number?","What does CDC Dr. Edwin Jenner liken the zombie virus to?",
"Barry served as best man at whose wedding?","Who accompanies Sheldon and Amy on their first dinner date?(BBT)","Who turned out to be Thea's biological father, who saved her from one of Slade's superhuman soldiers?","Barry's longtime girlfriend was Iris West. What century is she from?","'Suits' is set in a law office. Can you name it?","After they've fallen in love, Elektra gets Daredevil's alter ego a ticket to a ball. He goes, accompanied by his partner at work. What does Elektra wear?","Phoebe's brother let her name one of his triplets. What did she name her?",
"In Sherlock, Benedict Cumberbatch is Sherlock Holmes but who plays Doctor Watson?","How many dragons did Daenerys Targaryen originally have in The Game of Thrones?","What does VALAR MORGHULIS signify?","What was the name of the witch burned alive by Danerys on the funeral pyre of Khal Dargo?","In Breaking Badwhat was Walter White baby daughter's first name?","Sybil Buchanan is a character from which of these US TV series?","Margaret Schroeder is a character from which TV series","What is Monica's last name in tv series Friends?","What name is given to the seat of House Baratheon? ","Heisenberg?","An FX original, each season has a new story but some of same actors?","News program featuring real life cases?","Travel Chanel-Zak,Aaron,Billy,Jay and spirits?","Spin off from The Walking Dead?"
,"The Braverman's were the family on what drama series?","The Ghost Adventures Crew are originally from what city?","Sunday night AMC,- Rick, Daryl, Glen?","General Hospital takes place in what city?","Damon,Stefon,Elena,Bonnie and Caroline"};
MyCountDownTimer countDownTimer = new MyCountDownTimer(12000 /* 12 Sec */,
1000);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Toast.makeText(this," fgd",Toast.LENGTH_SHORT).show();
Intent i = getIntent();
phone = i.getStringExtra("phone");
phone1 = i.getStringExtra("phone1");
name = i.getStringExtra("name");
college = i.getStringExtra("college");
regno = i.getStringExtra("regno");
countDownTimer.start();
toolbar.setTitle("TV Series");
setSupportActionBar(toolbar);
opt1=(Button)findViewById(R.id.opt1);
count1=0;
opt2=(Button)findViewById(R.id.opt2);
opt3=(Button)findViewById(R.id.opt3);
opt4=(Button)findViewById(R.id.opt4);
time = (TextView) findViewById(R.id.time);
opt1.setOnClickListener(this);
opt2.setOnClickListener(this);
opt3.setOnClickListener(this);
opt4.setOnClickListener(this);
ques=(TextView)findViewById(R.id.ques);
quesno=(TextView)findViewById(R.id.quesno);
Toast.makeText(this," fgd",Toast.LENGTH_SHORT).show();
shuffleArray1(question, (Gamesupport2.option1), (Gamesupport2.option2), (Gamesupport2.option3), (Gamesupport2.option4));
ques.setText(question[0]);
opt1.setText(Gamesupport.option1[0]);
opt2.setText(Gamesupport.option2[0]);
opt3.setText(Gamesupport.option3[0]);
opt4.setText(Gamesupport.option4[0]);
}
#Override
public void onClick(View v) {
if(v==opt2)
{
++count;
next();
}
else
next();
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
static void shuffleArray1(String[] q, String[] option1, String[] option2, String[] option3, String[] option4) {
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = q.length; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
String a = q[index];
q[index] = q[i];
q[i] = a;
String e = option1[index];
option1[index] = option1[i];
option1[i] = e;
String b = option2[index];
option2[index] = option2[i];
option2[i] = b;
String c = option3[index];
option3[index] = option3[i];
option3[i] = c;
String d = option4[index];
option4[index] = option4[i];
option4[i] = d;
}
}
private void next() {
for(i=i+1;i<=question.length;i++,j++)
{
count1++;
countDownTimer.start();
if(count1==64)
{
countDownTimer.cancel();
String str=""+count;
Intent i = new Intent(this, Score.class);
i.putExtra("phone", phone);
i.putExtra("score", str);
i.putExtra("name",name);
i.putExtra("phone1",phone1);
i.putExtra("college",college);
i.putExtra("regno", regno);
startActivity(i);
break;
}
ques.setText(question[i]);
opt1.setText(Gamesupport.option1[i]);
opt2.setText(Gamesupport.option2[i]);
opt3.setText(Gamesupport.option3[i]);
opt4.setText(Gamesupport.option4[i]);
if(count1==1||count1==2 || count1==3 || count1==4|| count1==5||count1==6||count1==7||count1==8||count1==9||count1==10||count1==11||count1==12||count1==13||count1==14||count1==15||count1==16 || count1==17 || count1==18|| count1==19||count1==20||count1==21||count1==22||count1==23||count1==24||count1==25||count1==26||count1==27||count1==28||count1==29||count1==30||count1==31||count1==32||count1==33||count1==34||count1==35||count1==36||count1==37||count1==38||count1==39||count1==40||count1==41||count1==42||count1==43||count1==44||count1==45||count1==46 || count1==47 || count1==48|| count1==49||count1==50||count1==51||count1==52||count1==53||count1==54||count1==55||count1==56||count1==57||count1==58||count1==59||count1==60 || count1==61 || count1==62||count1==63||count1==64||count1==65)
{ quesno.setText("Question No :" + (i + 1));
break;
}
}
}
}
Arrays in Java are indexed from 0 and in following loop you are counting down from 64 to 1:
for (int i = q.length; i > 0; i--)
And you are trying to access non-existent item few lines below:
q[i]
You have to change your loop to:
for (int i = q.length - 1; i >= 0; i--)
I have two arrays :
String []myExpressions = {"20+10","50+50","25+25","10+15"};
String []answers = {"30#","100#","50#","25#"};
When the user clicks the generate button it generates an expression from the array myExpressions and displays it in text-field. Then I require the user to enter the answer using the buttons provided. The answer is displayed in a EditText. When the user enters an answer they should enter a #(like a submit button) and if is the correct answer it should display correct in a text-field. So if the position in the expression array is 1, the correct answer is in the answer array in the same position. How would i check if they are in the same position?
For example: myExpressions[1] correct answer to this is answers[1].
Here is my code:
package com.gamesup.braingame;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Easy extends Activity implements OnClickListener{
EditText display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easy);
display = (EditText)findViewById(R.id.displayText);
display.setText("?");
final String []myExpressions = {"20+10","50+50","25+25","10+15"};
final String []answers = {"30#","100#","50#","25#"};
final TextView displayExpression = (TextView) findViewById(R.id.expression);
Button generate = (Button) findViewById(R.id.random_gen);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random ranGenerate = new Random ();
int random = ranGenerate.nextInt(4) ;
displayExpression.setText(myExpressions[random]);
}
});
}
static boolean isEmpty = true;
public void num_Clicked(View v){
Button btn = (Button) findViewById(v.getId());
//getting the button object and using a view to get the id of the buttons
if (v.getId()== R.id.del_button){
String s = display.getText().toString();
s = s.substring(0, s.length() - 1);
display.setText(s);
return;
}
if(isEmpty){
display.setText(btn.getText());
isEmpty = false;
}
else{
display.append(btn.getText().toString());
// storing the existing number into editText and current text is set
//to current button value
//display.setText(number+btn.getText().toString());
//the total in the editText
}
if (v.getId()== R.id.hash_button){
String userAns = display.getText().toString();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
For starters arrays in Java Begin at Index 0 so therefore , to compare the first items of the Array you should be using something like this to check if things are equal:
EditText myAnswer = (EditText) findViewById(R.id.myAnswer);
String answer = myAnswer.getText().toString();
// Notice my loop starts at 0 because the first index of an array is 0
for(int i = 0 ; i < answers.length; i++)
{
if(answers[i].equals(answer))
{
// Congratulate the User for getting it Right
}
}
It seems as though you have a little bit of a shaky logic. IMHO you should be using a multidimensional Array.
With a multidimensional Array you can essentially set up keys and values.
This is how I think your application should be configures
// This Array says , I am an array that holds arrays
String [][] multiArray = {{"4 + 5", "9"},
{"20 * 3","60"},
{"99 - 9","90"}};
// Fetch your random question, since we know our questions are the first item in out Array we can use the index [x][0] depending on the index you pull from
String question = multiArray[0][0];
// To do this randomly
Random ranGenerate = new Random ();
int random = ranGenerate.nextInt(4) ;
String question = multiArray[random][0];
// Get the Answer from yout EditText
String answer = myAnswer.getText().toString();
// Using a for loop iterate on the base index
for(int i = 0; i < multiArray.length ; i++)
{
// if the answer is in position 1 of Array [i]
if(answer.equals(mutliArray[i][1])
{
// We have found the answer, Congratulate the User
}else{
// Tell them how bad they are since they can't solve simple equations!
// ....joking obviously we would be nice and let them know its not the answer
}
}
In this line
int random = ranGenerate.nextInt(4) ;
why don't you make random an instance variable inside your class? This way you would preserve the index, and you would know which index to use to compare the answer.
I'm currently trying to write an app to calculate BMI and calories needed by a person (male / female).
My apps have 2 parts:
1. BMI calculation
2. Calories needed
The first part works well (so I excluded the code for this part), but for the 2nd part, calories needed calculation, it is not able to show up the result as expected (after I click on 'calories needed' button). Probably something is still missing but I cant find it so far.
Everything looks fine in the code, no error.
Can anyone help to have a look on it? :) thanks in advance.
Code as below:
package com.example.caloriescalculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.RadioButton;
public class BMIcalculation extends Activity
{
EditText weightE;
EditText heightE ;
EditText ageE ;
TextView caloriesresult ;
RadioButton male;
RadioButton female;
Button calories;
EditText weightText ;
EditText heightText ;
EditText ageText;
TextView resultText;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.bmilayout_main);
weightE = (EditText)findViewById(R.id.weightText);
heightE = (EditText)findViewById(R.id.heightText);
ageE = (EditText)findViewById(R.id.ageText);
caloriesresult = (TextView)findViewById(R.id.caloriesText);
male = (RadioButton) findViewById(R.id.maleradio);
female = (RadioButton) findViewById(R.id.femaleradio);
Button calories = (Button) findViewById(R.id.caloriesButton);
calories.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
int caloriesneed = 0, weight = 0, height = 0, age = 0;
try {
if ((!weightE.equals("")) && (!heightE.equals("")) && (!ageE.equals("")))
{
weightE = (EditText) findViewById(R.id.weightText);
weight = Integer.parseInt(weightE.getText().toString().trim());
heightE = (EditText) findViewById(R.id.heightText);
height = Integer.parseInt(heightE.getText().toString().trim());
ageE = (EditText) findViewById(R.id.ageText);
age = Integer.parseInt(ageE.getText().toString().trim());
if (male.isSelected())
{
caloriesneed = (int) Math.round (655 + 9.6*weight + 1.8*height - 4.7*age);
caloriesresult.setText(caloriesneed);
}
else if (female.isSelected())
{
caloriesneed = (int) Math.round (66 + 13.7*weight + 5*height - 6.8*age);
caloriesresult.setText(caloriesneed);
}
}
}
catch (Exception k)
{ System.out.println(k);
}
}
});
}
caloriesresult.setText(caloriesneed);
This is problem. In Android if you assign pure int variable to some TextWidget, error will be thrown because Android will interpret it as resouce id of stored String in strings.xml.
So for this reason you need explicit casting. You can achieve it with concentation or an usage of String.valueOf(int value) or Integer.toString(int value) method:
textWidget.setText(Integer.toString(value)); // best approach
textWidget.setText(String.valueOf(value));
textWidget.setText("" + value);
Note: This is absolutely normal behaviour since if you are developing comercial application, usually you want to have support for more languages - and this feature requires localised Strings stored in proper XML file(s).
I guess it's because you try to input an integer to settext() which requires a string for input parameter, so you can try:
caloriesresult.setText("" + caloriesneed);
or
caloriesresult.setText(Integer.toString(caloriesneed));
or
caloriesresult.setText(String.valueOf(caloriesneed));