Application can't run properly while using spinner in Android - java

application terminated when using the Button in Layout
I have used spinner widget for my application & switch statements...
this is my mainactivity.java file
package com.example.edward.converter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import static java.lang.System.exit;
public class MainActivity extends AppCompatActivity {
private Button btn;
private TextView txt;
private EditText etxt;
private Spinner spn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
txt = (TextView) findViewById(R.id.textView);
etxt = (EditText) findViewById(R.id.editText);
spn = (Spinner) findViewById(R.id.spinner);
spn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0 :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double result = 0.0;
double multiplier = 2.54;
if(etxt.getText().toString().equals("")){
txt.setText(R.string.error);
txt.setTextColor(Color.RED);
}else {
double valueMetre = Double.parseDouble(etxt.getText().toString());
result = valueMetre*multiplier;
txt.setText(String.format("%.2f",result + " cm" ));
txt.setVisibility(v.VISIBLE);
txt.setTextColor(Color.WHITE);
}
}
});
break;
case 1 :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double result = 0.0;
double multiplier = 0.393701;
if(etxt.getText().toString().equals("")){
txt.setText(R.string.error);
txt.setTextColor(Color.RED);
}else {
double valueMetre = Double.parseDouble(etxt.getText().toString());
result = valueMetre*multiplier;
txt.setText(String.format("%.2f",result + " Inch"));
txt.setVisibility(v.VISIBLE);
txt.setTextColor(Color.WHITE);
}
}
});
break;
case 2 :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double result = 0.0;
double multiplier = 0.0254;
if(etxt.getText().toString().equals("")){
txt.setText(R.string.error);
txt.setTextColor(Color.RED);
}else {
double valueMetre = Double.parseDouble(etxt.getText().toString());
result = valueMetre*multiplier;
txt.setText(String.format("%.2f",result + " Metre"));
txt.setVisibility(v.VISIBLE);
txt.setTextColor(Color.WHITE);
}
}
});
break;
case 3 :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double result = 0.0;
double multiplier = 39.9701;
if(etxt.getText().toString().equals("")){
txt.setText(R.string.error);
txt.setTextColor(Color.RED);
}else {
double valueMetre = Double.parseDouble(etxt.getText().toString());
result = valueMetre*multiplier;
txt.setText(String.format("%.2f",result + "Inch"));
txt.setVisibility(v.VISIBLE);
txt.setTextColor(Color.WHITE);
}
}
});
break;
case 4 :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double result = 0.0;
double multiplier = 0.01;
if(etxt.getText().toString().equals("")){
txt.setText(R.string.error);
txt.setTextColor(Color.RED);
}else {
double valueMetre = Double.parseDouble(etxt.getText().toString());
result = valueMetre*multiplier;
txt.setText(String.format("%.2f",result + " Metre"));
txt.setVisibility(v.VISIBLE);
txt.setTextColor(Color.WHITE);
}
}
});
break;
case 5 :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double result = 0.0;
double multiplier = 100;
if(etxt.getText().toString().equals("")){
txt.setText(R.string.error);
txt.setTextColor(Color.RED);
}else {
double valueMetre = Double.parseDouble(etxt.getText().toString());
result = valueMetre*multiplier;
txt.setText(String.format("%.2f",result + " cm"));
txt.setVisibility(v.VISIBLE);
txt.setTextColor(Color.WHITE);
}
}
});
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
exit(0);
}
});
}
}
& this is activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/blue"
tools:context="com.example.edward.converter.MainActivity">
<Spinner
android:id="#+id/spinner"
android:layout_width="205dp"
android:layout_height="46dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:entries="#array/convert"
android:gravity="center"
android:longClickable="false"
android:spinnerMode="dialog"
app:layout_constraintBottom_toTopOf="#+id/editText"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView" />
<ImageView
android:id="#+id/imageView"
android:layout_width="72dp"
android:layout_height="71dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:contentDescription="#string/todo"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/converter" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="38dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="96dp"
android:background="#drawable/circular"
android:ems="10"
android:gravity="center"
android:hint="#string/enter_value"
android:inputType="textPersonName|number"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView" />
<Button
android:id="#+id/button"
android:layout_width="112dp"
android:layout_height="39dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="#drawable/circular"
android:longClickable="true"
android:text="#string/convert"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText"
app:layout_constraintVertical_bias="0.189" />
<TextView
android:id="#+id/textView"
android:layout_width="398dp"
android:layout_height="45dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:gravity="center"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button" />
</android.support.constraint.ConstraintLayout>
This is what i have used in strings.xml
<resources>
<string name="app_name">Converter</string>
<string name="enter_value">Enter Value</string>
<string name="todo">TODO</string>
<string name="convert">Convert</string>
<string name="error">Please Enter A Valid Number</string>
<string-array name="convert">
<item>Inch-cm</item>
<item>cm-Inch</item>
<item>Inch-Metre</item>
<item>Metre-Inch</item>
<item>cm-Metre</item>
<item>Metre-cm</item>
</string-array>
</resources
layout:
Please Help in understanding this spinner concept & this error...

Related

how to get the int score to view on my second activity

i am creating a quiz app that is multiple choice
in my first activity(MainActivity) is the question(text) and choices
and in my second activity( QuizImage1)is the question(image) and choices
how will i get the result of the score in main activity to view also in quizimage1
the second image is my error on quizimage1 because i did not copy the first activity score
i hope you understand what iam talking about
plss fix my codes
iam beginner in java
Main_Activity.java
package com.example.ltoexam;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private com.example.ltoexam.QuestionLibrary nQuestionLibrary = new com.example.ltoexam.QuestionLibrary();
public TextView nScoreView;
private TextView nQuestionView;
private Button nButtonChoice1;
private Button nButtonChoice2;
private Button nButtonChoice3;
private Button quit;
private String nAnswer;
public int nScore = 0;
private int nQuestionNumber = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nScoreView = (TextView) findViewById(R.id.score);
nQuestionView = (TextView) findViewById(R.id.question);
nButtonChoice1 = (Button) findViewById(R.id.choice1);
nButtonChoice2 = (Button) findViewById(R.id.choice2);
nButtonChoice3 = (Button) findViewById(R.id.choice3);
quit = (Button) findViewById(R.id.quit) ;
updateQuestion();
//Start of Button Listener for Button1
nButtonChoice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//My logic for Button goes in here
if (nButtonChoice1.getText() == nAnswer){
nScore =nScore + 1;
updateScore(nScore);
updateQuestion();
//This line of code is optional
Toast.makeText(MainActivity.this, "correct", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "wrong the answer is " + nAnswer, Toast.LENGTH_SHORT).show();
updateQuestion();
}
}
});
//End of Button Listener for Button2
//Start of Button Listener for Button2
nButtonChoice2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//My logic for Button goes in here
if (nButtonChoice2.getText() == nAnswer){
nScore =nScore + 1;
updateScore(nScore);
updateQuestion();
//This line of code is optional
Toast.makeText(MainActivity.this, "correct", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "wrong the answer is " + nAnswer, Toast.LENGTH_SHORT).show();
updateQuestion();
}
}
});
quit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
finish();
System.exit(0);
}
});
//End of Button Listener for Button2
//Start of Button Listener for Button3
nButtonChoice3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//My logic for Button goes in here
if (nButtonChoice3.getText() == nAnswer){
nScore =nScore + 1;
updateScore(nScore);
updateQuestion();
//This line of code is optional
Toast.makeText(MainActivity.this, "correct", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "wrong the answer is " + nAnswer, Toast.LENGTH_SHORT).show();
updateQuestion();
}
}
});
//End of Button Listener for Button2
}
private void updateQuestion(){
if(nQuestionNumber==7){
openQuizImage1();}
else {
nQuestionView.setText(nQuestionLibrary.getQuestion(nQuestionNumber));
nButtonChoice1.setText(nQuestionLibrary.getChoice1(nQuestionNumber));
nButtonChoice2.setText(nQuestionLibrary.getChoice2(nQuestionNumber));
nButtonChoice3.setText(nQuestionLibrary.getChoice3(nQuestionNumber));
nAnswer = nQuestionLibrary.getCorrectAnswer(nQuestionNumber);
nQuestionNumber++;
}
}
public void updateScore(int point){
nScoreView.setText("" + nScore);
}
public void openQuizImage1() {
Intent intent = new Intent(this, QuizImage1.class);
startActivity(intent);
}
}
QuestionLibrary.java
package com.example.ltoexam;
public class QuestionLibrary {
private String nQuestions [] = {
"1.The three colors of the traffic lights are:",
"2.Yellow triangular signs provide what kind of information",
"3.Which of the following traffic signs are blue?",
"4.Steady green light means",
"5.A flashing yellow light at a road crossing signifies",
"6.A solid white line on the right edge of the highway slopes in towards your left. This shows that",
"7.You are in a No-Passing zone when the center of the road is marked by"
};
private String nChoices [] [] = {
{"red, green and yellow", "red, green and blue", "yellow, green and blue"},
{"warning", "hospital across", "speed limit"},
{"regulatory signs", "information signs", "danger warning signs"},
{"you must yield to all pedestrians and other motorists using the intersection", "go, it is safe to do so", "proceed cautiously through the intersection before the light changes to red."},
{"Caution - slow down and proceed with caution", "Stop and stay until light stops flashing", "Wait for the green light"},
{"there is an intersection joint ahead", "the road will get narrower", "you are approaching a construction area"},
{"a broken yellow line","a broken white line","two solid yellow lines"}
};
private String nCorrectAnsers[] = {"red, green and yellow", "warning", "information signs", "go, it is safe to do so", "Caution - slow down and proceed with caution", "the road will get narrower", "two solid yellow lines"};
public String getQuestion(int a) {
String question = nQuestions[a];
return question;
}
public String getChoice1(int a) {
String choice0 = nChoices[a] [0];
return choice0;
}
public String getChoice2(int a) {
String choice1 = nChoices[a] [1];
return choice1;
}
public String getChoice3(int a) {
String choice2 = nChoices[a] [2];
return choice2;
}
public String getCorrectAnswer(int a) {
String answer = nCorrectAnsers[a];
return answer;
}
}
QuizImage1.java (this is my second activity)
package com.example.ltoexam;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class QuizImage1 extends AppCompatActivity {
private Button but1;
private Button but2;
private Button but3;
public TextView nScoreView;
public int nScore;
public TextView nScoreView() {
return nScoreView;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_image1);
but1 = (Button) findViewById(R.id.but1);
but2 = (Button) findViewById(R.id.but2);
but3 = (Button) findViewById(R.id.but3);
nScoreView = (TextView) findViewById(R.id.score);
but1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(QuizImage1.this, "wrong the answer is Road goes left or right", Toast.LENGTH_SHORT).show();
openQuizImage2();
}
});
but2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(QuizImage1.this, "wrong the answer is Road goes left or right", Toast.LENGTH_SHORT).show();
openQuizImage2();
}
});
but3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(QuizImage1.this, "correct", Toast.LENGTH_SHORT).show();
openQuizImage2();
nScore =nScore + 1;
updateScore(nScore);
}
});
}
public void updateScore(int point){
nScoreView.setText("" + nScore);}
public void openQuizImage2(){
Intent intent = new Intent(this, QuizImage2.class);
startActivity(intent);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:layout_marginBottom="40dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Score"
android:textSize="20sp"
android:layout_alignParentLeft="true"
android:id="#+id/score_text"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_alignParentRight="true"
android:text="0"
android:id="#+id/score"/>
</RelativeLayout>
<TextView
android:id="#+id/question"
android:layout_width="match_parent"
android:layout_height="116dp"
android:layout_marginBottom="40dp"
android:fontFamily="#font/carter_one"
android:padding="8dp"
android:text="Which thing is alive?"
android:textSize="20sp"
android:textStyle="bold|italic" />
<Button
android:id="#+id/choice1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:background="#0091EA"
android:fontFamily="#font/carter_one"
android:padding="8dp"
android:text="bird"
android:textColor="#fff" />
<Button
android:id="#+id/choice2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:background="#0091EA"
android:fontFamily="#font/carter_one"
android:padding="8dp"
android:text="door"
android:textColor="#fff" />
<Button
android:id="#+id/choice3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:background="#0091EA"
android:fontFamily="#font/carter_one"
android:padding="8dp"
android:text="rock "
android:textColor="#fff" />
<Button
android:id="#+id/quit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:background="#871C1C"
android:fontFamily="#font/carter_one"
android:padding="8dp"
android:text="Quit"
android:textColor="#fff" />
</LinearLayout>
activity_quiz_image1.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".QuizImage1">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:layout_marginBottom="40dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Score"
android:textSize="20sp"
android:layout_alignParentLeft="true"
android:id="#+id/score_text"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_alignParentRight="true"
android:text="0"
android:id="#+id/score"/>
</RelativeLayout>
<Button
android:id="#+id/but1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="317dp"
android:layout_marginBottom="238dp"
android:background="#0091EA"
android:fontFamily="#font/carter_one"
android:padding="8dp"
android:text="road ends"
android:textColor="#fff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/but2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="396dp"
android:layout_marginBottom="159dp"
android:background="#0091EA"
android:fontFamily="#font/carter_one"
android:padding="8dp"
android:text="crossroads"
android:textColor="#fff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="#+id/but3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="476dp"
android:layout_marginBottom="79dp"
android:background="#0091EA"
android:fontFamily="#font/carter_one"
android:padding="8dp"
android:text="Road goes left or right"
android:textColor="#fff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/quit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="549dp"
android:layout_marginBottom="6dp"
android:background="#871C1C"
android:fontFamily="#font/carter_one"
android:padding="8dp"
android:text="Quit"
android:textColor="#fff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView4"
android:layout_width="249dp"
android:layout_height="182dp"
app:srcCompat="#drawable/road_goes_left_right_road_traffic_sign"
tools:layout_editor_absoluteX="81dp"
tools:layout_editor_absoluteY="67dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
To transfer information from one activity to another, use the following :
Intent intent = new Intent(this, ActivityNext.class);
intent.putExtra("NSCORE_KEY", nScore );
startActivity(intent);
And in another activity get :
int nScore = getIntent().getIntExtra("KEY",1);
To send data through activities you have to use the same intent you use to navigate to the activity as below.
Intent intent = new Intent(this, QuizImage1.class);
intent.putExtra("keyScore",nScore);
startActivity(intent);
In the second activity QuizImage1.class in OnCreate method add the following code
int score = getIntent().getIntExtra("keyScore",1);
Please take a look at the official tutorial from android developer website

I am unable to evaluate string using eval()

I am trying to make a calculator application.I want to evaluate the contents of a TextView and display it as a toast message. The eval() statement throws an exception for ScriptException as below.
"Unhandled exception: javax.script.ScriptException"
Even when I have imported javax.script.ScriptException. I am not getting from why it is throwing exception.
Here is my xml code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginTop="95dp"
android:textAlignment="center"
android:textSize="36sp" />
<Button
android:id="#+id/n1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="18dp"
android:layout_marginTop="194dp"
android:text="1" />
<Button
android:id="#+id/n2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/n1"
android:layout_centerHorizontal="true"
android:text="2" />
<Button
android:id="#+id/n3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/n1"
android:layout_marginEnd="16dp"
android:text="3" />
<Button
android:id="#+id/n4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/n1"
android:layout_centerVertical="true"
android:text="4" />
<Button
android:id="#+id/n5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="5" />
<Button
android:id="#+id/n6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/n3"
android:layout_centerVertical="true"
android:text="6" />
<Button
android:id="#+id/n7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignStart="#+id/n1"
android:layout_marginBottom="194dp"
android:text="7" />
<Button
android:id="#+id/n8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/n7"
android:layout_centerHorizontal="true"
android:text="8" />
<Button
android:id="#+id/n9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/n3"
android:layout_alignTop="#+id/n7"
android:text="9" />
<Button
android:id="#+id/n0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="129dp"
android:text="0" />
<Button
android:id="#+id/clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/n3"
android:layout_alignTop="#+id/n0"
android:text="CLEAR" />
<Button
android:id="#+id/plus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="73dp"
android:text="+" />
<Button
android:id="#+id/equal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/n3"
android:layout_alignTop="#+id/plus"
android:text="=" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
and here is my java code:
package com.example.poopypigeon.calx;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class MainActivity extends AppCompatActivity {
Button n1;
Button n2;
Button n3;
Button n4;
Button n5;
Button n6;
Button n7;
Button n8;
Button n9;
Button n0;
Button clear;
Button plus;
Button equal;
TextView value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
value = findViewById(R.id.textView);
n1 = findViewById(R.id.n1);
n1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"1");
}
});
n2 = findViewById(R.id.n2);
n2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"2");
}
});
n3 = findViewById(R.id.n3);
n3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"3");
}
});
n4 = findViewById(R.id.n4);
n4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"4");
}
});
n5 = findViewById(R.id.n5);
n5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"5");
}
});
n6 = findViewById(R.id.n6);
n6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"6");
}
});
n7 = findViewById(R.id.n7);
n7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"7");
}
});
n8 = findViewById(R.id.n8);
n8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"8");
}
});
n9 = findViewById(R.id.n9);
n9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"9");
}
});
n0 = findViewById(R.id.n0);
n0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"0");
}
});
clear = findViewById(R.id.clear);
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
value.setText("");
}
});
plus = findViewById(R.id.plus);
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val + "+");
}
});
equal = findViewById(R.id.equal);
equal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
Object ans = engine.eval(val);
Toast toast = Toast.makeText(MainActivity.this,"the ans is: "+ ans,Toast.LENGTH_SHORT);
toast.show();
}
});
}
}
PS. i need a reply as soon as possible as this is for a school project
I would do it like this to further investigate:
try{
ScriptEngineManager manager = new ScriptEngineManager()
ScriptEngine engine = manager.getEngineByExtension("js");
Object ans = engine.eval(val);
Toast toast = Toast.makeText(MainActivity.this,"the ans is: "+ ans,Toast.LENGTH_SHORT);
toast.show();
catch(ScriptEngineManager e) {
// handle exception
System.err.println("Error making calculation: " + e.getMessage());
}
EDIT: Change:
String val = value.getText().toString();
value.setText(val+"1");
You have only the value in the String val - but you need the content of value textfield. In the String val there has to be something like "4+4".
You just add numbers to the textfield but no operators.
value.setText(val+"1"); -> You just add the Number 1 to the Textfield, so after clicking some Buttons you have like this in your Textfield "512312"
Copy this import statement
import javax.script.ScriptException;
Try is code:
try {
Object ans = engine.eval(val);
System.out.println("It worked!:" + ans.toString());
}
catch (ScriptException se) {
System.out.println("Problem in eval:", se.getmessage());
}
Change ScriptException with Exception
try {
ans = engine.eval(val);
} catch (Exception e) {
e.printStackTrace();
}
You are not sure for which type of exception it may trigger so it will display the same message for all the exceptions and user may not be able to understand which exception occurred. Thats the reason you should place is at the end of all the specific exception catch blocks
To simplify the debugging here, focus on this line:
Object ans = engine.eval(val);
Print the value of val so we can see the source that is being evaluated.
Wrap that line in a try catch block and print the full stack trace so we can see the full error diagnostic.

My android app keeps on crashing

I want to make a Scientific Calculator(Android app) but some problems appears. I don't know Java but I understand the code because I know C++.
I had modified the code of a normal Calculator into a Scientific Calculator but the code doesn't seems to work.
Only the basic functions like +,-,*,/ work but the functions which I added like Sin,Cos,Tan,Sqrt,Pow,Exp etc. doesn't seems to work when I use those functions the app crashes.
This is my source code.
MainActivity.java
package com.example.anant.scientificcalculator;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import static java.lang.Math.*;
import java.text.DecimalFormat;
import com.example.anant.scientificcalculator.databinding.MainActivityBinding;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private MainActivityBinding binding;
private static final char FACT = '!';
private static final char POWER = '^';
private static final String SQRT = "SQRT";
private static final String SIN = "SIN";
private static final String COS = "COS";
private static final String TAN = "TAN";
private static final String LOG = "LOG";
private static final char LEFTC = '(';
private static final char RIGHTC = ')';
private static final String EXP = "EXP";
private static final String PIE = "PIE";
private static final char ADD = '+';
private static final char SUBTRACT = '-';
private static final char MULTIPlY = '*';
private static final char DIVIDE = '/';
private char CURRENT_ACTION;
private String ADVANCE_ACTION;
private double valueOne = Double.NaN;
private double valueTwo;
private double valueTemp;
private DecimalFormat decimalFormat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
decimalFormat = new DecimalFormat("#.##########");
binding = DataBindingUtil.setContentView(this, R.layout.main_activity);
binding.buttonDot.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + ".");
}
});
binding.buttonZero.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "0");
}
});
binding.buttonOne.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "1");
}
});
binding.buttonTwo.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "2");
}
});
binding.buttonThree.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "3");
}
});
binding.buttonFour.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "4");
}
});
binding.buttonFive.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "5");
}
});
binding.buttonSix.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "6");
}
});
binding.buttonSeven.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "7");
}
});
binding.buttonEight.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "8");
}
});
binding.buttonNine.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "9");
}
});
binding.buttonLeftC.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "(");
}
});
binding.buttonRightC.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + ")");
}
});
binding.buttonExp.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
computeCalculation();
ADVANCE_ACTION = EXP;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "EXP");
binding.editText.setText(null);
}
});
binding.buttonPie.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
computeCalculation();
ADVANCE_ACTION = PIE;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "PIE");
binding.editText.setText(null);
}
});
binding.buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = ADD;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "+");
binding.editText.setText(null);
}
});
binding.buttonSubtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = SUBTRACT;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "-");
binding.editText.setText(null);
}
});
binding.buttonMultiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = MULTIPlY;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "*");
binding.editText.setText(null);
}
});
binding.buttonDivide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = DIVIDE;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "/");
binding.editText.setText(null);
}
});
binding.buttonFact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = FACT;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "!");
binding.editText.setText(null);
}
});
binding.buttonPow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = POWER;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "^");
binding.editText.setText(null);
}
});
binding.buttonSqrt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
ADVANCE_ACTION = SQRT;
binding.infoTextView.setText("SQRT(" + decimalFormat.format(valueOne) + ")");
binding.editText.setText(null);
}
});
binding.buttonSine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
ADVANCE_ACTION = SIN;
binding.infoTextView.setText("SIN(" + decimalFormat.format(valueOne) + ")");
binding.editText.setText(null);
}
});
binding.buttonCosine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
ADVANCE_ACTION = COS;
binding.infoTextView.setText("COS(" + decimalFormat.format(valueOne) + ")");
binding.editText.setText(null);
}
});
binding.buttonTangent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
ADVANCE_ACTION = TAN;
binding.infoTextView.setText("TAN(" + decimalFormat.format(valueOne) + ")");
binding.editText.setText(null);
}
});
binding.buttonLog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
ADVANCE_ACTION = LOG;
binding.infoTextView.setText("LOG(" + decimalFormat.format(valueOne) + ")");
binding.editText.setText(null);
}
});
binding.buttonEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
binding.infoTextView.setText(binding.infoTextView.getText().toString() +
decimalFormat.format(valueTwo) + " = " + decimalFormat.format(valueOne));
valueOne = Double.NaN;
CURRENT_ACTION = '0';
}
});
binding.buttonClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(binding.editText.getText().length() > 0) {
CharSequence currentText = binding.editText.getText();
binding.editText.setText(currentText.subSequence(0, currentText.length()-1));
}
else {
valueOne = Double.NaN;
valueTwo = Double.NaN;
binding.editText.setText("");
binding.infoTextView.setText("");
}
}
});
}
private void computeCalculation() {
if(!Double.isNaN(valueOne)) {
valueTwo = Double.parseDouble(binding.editText.getText().toString());
binding.editText.setText(null);
if(CURRENT_ACTION == ADD)
valueOne = this.valueOne + valueTwo;
else if(CURRENT_ACTION == SUBTRACT)
valueOne = this.valueOne - valueTwo;
else if(CURRENT_ACTION == MULTIPlY)
valueOne = this.valueOne * valueTwo;
else if(CURRENT_ACTION == DIVIDE)
valueOne = this.valueOne / valueTwo;
else if(CURRENT_ACTION == FACT)
{
valueTemp = this.valueOne;
int i,valueThree=1;
for(i=(int) valueTemp;i>0;i--) //type conversion
{
valueThree *= i;
}
valueOne = valueThree;
}
else if(CURRENT_ACTION == POWER) {
valueTemp = this.valueOne;
valueTemp = Math.pow(valueOne, valueTwo);
valueOne = valueTemp;
}
else if(ADVANCE_ACTION == SQRT) {
valueTemp = this.valueOne;
valueOne = Math.sqrt(valueTemp);
}
else if(ADVANCE_ACTION == SIN) {
valueTemp = this.valueOne;
valueOne = Math.sin(valueTemp);
}
else if(ADVANCE_ACTION == COS) {
valueTemp = this.valueOne;
valueOne = Math.cos(valueTemp);
}
else if(ADVANCE_ACTION == TAN) {
valueTemp = this.valueOne;
valueOne = Math.tan(valueTemp);
}
else if(ADVANCE_ACTION == LOG) {
valueTemp = this.valueOne;
valueOne = Math.log(valueTemp);
}
else if(ADVANCE_ACTION == PIE) {
valueTemp = this.valueOne;
valueTemp = Math.PI;
valueOne = valueTemp;
}
else if(ADVANCE_ACTION == EXP) {
valueTemp = this.valueOne;
valueTemp = Math.E;
valueOne = valueTemp;
}
}
else {
try {
valueOne = Double.parseDouble(binding.editText.getText().toString());
}
catch (Exception e){}
}
}
}
Can anyone tell me why my app keeps on crashing?
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<layout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.anant.scientificcalculator.MainActivity">
<TextView
android:id="#+id/infoTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:textSize="30sp" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/infoTextView"
android:enabled="false"
android:gravity="bottom"
android:hint="0"
android:inputType="numberDecimal"
android:lines="2"
android:maxLines="2"
android:textAlignment="textEnd"
android:textColor="#android:color/black"
android:textSize="40sp" />
<Button
android:id="#+id/buttonFact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:text="#string/buttonFact"
android:textSize="20sp" />
<Button
android:id="#+id/buttonPow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_toRightOf="#id/buttonFact"
android:text="#string/buttonPow"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSqrt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_toRightOf="#id/buttonPow"
android:text="#string/buttonSqrt"
android:textSize="20sp" />
<Button
android:id="#+id/buttonClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/buttonSqrt"
android:layout_below="#id/editText"
android:text="#string/buttonClear"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSine"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonFact"
android:text="#string/buttonSine"
android:textSize="20sp" />
<Button
android:id="#+id/buttonCosine"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonPow"
android:layout_toRightOf="#id/buttonSine"
android:text="#string/buttonCosine"
android:textSize="20sp" />
<Button
android:id="#+id/buttonTangent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonSqrt"
android:layout_toRightOf="#id/buttonCosine"
android:text="#string/buttonTangent"
android:textSize="20sp" />
<Button
android:id="#+id/buttonLog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonClear"
android:layout_toRightOf="#id/buttonTangent"
android:text="#string/buttonLog"
android:textSize="20sp" />
<Button
android:id="#+id/buttonLeftC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonSine"
android:text="#string/buttonLeftC"
android:textSize="20sp" />
<Button
android:id="#+id/buttonRightC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonCosine"
android:layout_toRightOf="#id/buttonLeftC"
android:text="#string/buttonRightC"
android:textSize="20sp" />
<Button
android:id="#+id/buttonExp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonTangent"
android:layout_toRightOf="#id/buttonRightC"
android:text="#string/buttonExp"
android:textSize="20sp" />
<Button
android:id="#+id/buttonPie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonLog"
android:layout_toRightOf="#id/buttonExp"
android:text="#string/buttonPie"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSeven"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonLeftC"
android:text="#string/buttonSeven"
android:textSize="20sp" />
<Button
android:id="#+id/buttonEight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonRightC"
android:layout_toRightOf="#id/buttonSeven"
android:text="#string/buttonEight"
android:textSize="20sp" />
<Button
android:id="#+id/buttonNine"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonExp"
android:layout_toRightOf="#id/buttonEight"
android:text="#string/buttonNine"
android:textSize="20sp" />
<Button
android:id="#+id/buttonFour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonSeven"
android:text="#string/buttonFour"
android:textSize="20sp" />
<Button
android:id="#+id/buttonFive"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonEight"
android:layout_toRightOf="#id/buttonFour"
android:text="#string/buttonFive"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSix"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonNine"
android:layout_toRightOf="#id/buttonFive"
android:text="#string/buttonSix"
android:textSize="20sp" />
<Button
android:id="#+id/buttonOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonFour"
android:text="#string/buttonOne"
android:textSize="20sp" />
<Button
android:id="#+id/buttonTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonFive"
android:layout_toRightOf="#id/buttonOne"
android:text="#string/buttonTwo"
android:textSize="20sp" />
<Button
android:id="#+id/buttonThree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonSix"
android:layout_toRightOf="#id/buttonTwo"
android:text="#string/buttonThree"
android:textSize="20sp" />
<Button
android:id="#+id/buttonDot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonOne"
android:text="#string/buttonDot"
android:textSize="20sp" />
<Button
android:id="#+id/buttonZero"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonTwo"
android:layout_toRightOf="#id/buttonDot"
android:text="#string/buttonZero"
android:textSize="20sp" />
<Button
android:id="#+id/buttonEqual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#id/buttonNine"
android:layout_below="#id/buttonThree"
android:text="#string/buttonEqual"
android:textSize="20sp" />
<Button
android:id="#+id/buttonDivide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/buttonNine"
android:layout_toRightOf="#id/buttonNine"
android:text="#string/buttonDIvide"
android:textSize="20sp" />
<Button
android:id="#+id/buttonMultiply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/buttonSix"
android:layout_toRightOf="#id/buttonSix"
android:text="#string/buttonMultiply"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSubtract"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/buttonThree"
android:layout_toRightOf="#id/buttonThree"
android:text="#string/buttonSubtract"
android:textSize="20sp" />
<Button
android:id="#+id/buttonAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/buttonEqual"
android:layout_toRightOf="#id/buttonEqual"
android:text="#string/buttonAdd"
android:textSize="20sp" />
</RelativeLayout>
</layout>
I managed to run your code with minor changes.
The problem seems to be here:
private void computeCalculation() {
if(!Double.isNaN(valueOne)) {
valueTwo = Double.parseDouble(binding.editText.getText().toString());
binding.editText.setText(null);
If you check down below the Android Monitor after the crash you will see something like this:
04-10 13:01:01.531 20742-20742/com.johnurrutia.so_43315233 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.johnurrutia.so_43315233, PID: 20742
java.lang.NumberFormatException: Invalid double: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:267)
at java.lang.Double.parseDouble(Double.java:301)
at com.johnurrutia.so_43315233.MainActivity.computeCalculation(MainActivity.java:303)
at com.johnurrutia.so_43315233.MainActivity.access$100(MainActivity.java:11)
...
It tells you have a FATAL EXCEPTION because of an ivalid double. Which you can track to MainActivity.java in line 303 (you will have a different line most likely).
With the debugger on that line you can check and see what is happening.
I think you are trying to convert an empty String to a Double.
The changes I did to run you code are the following.
1) In the layout file:
a) Changed the layout tag with the android name space.
b) Added an empty placeholder (not sure if its necessary or not)
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
</data>
<RelativeLayout
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.johnurrutia.so_43315233.MainActivity">
...
</layout>
c) In the EditText there is an alignment to "endText" that seems to be incompatible with the selected gravity so I just erased it.
d) As you haven't posted it, just make sure you have all your #string/stringname set in your res/values/string.xml file.
2) As you are working with Data Binding, check your Gradle App Module file. You have to have:
android {
...
dataBinding {
enabled = true
}
}
3) After that look at your files and check you see nothing in red.
4) Hit Build->Clean Project. And then Run.
you need something like this to solve your issue..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}

Activity to Fragment error having trouble getting value to shared preferences

I'm currently developing a calorie app for my class project. I had started using a activity for the layout but my professor wants me to use a fragment instead. While trying to convert the code to fragment I came across some issues having difficulty saving the value to the shared preference xml. The page i'm currently working on gets information from the user and depending what the user selects determines their calories. That value is then saved in shared preference where it is displayed in the main activity.
Thanks in advance for the help, I'm new to android studio and developing apps.
profile java file
`public class Profile extends Fragment implements View.OnClickListener {
//adaptors spinners
ArrayAdapter<String> HeightFeetAdapter;
ArrayAdapter<String> WeightLBSAdapter;
//references UI elements
Button SaveButton;
Spinner weightSpinner;
Spinner heightSpinner;
Spinner goal;
Spinner gender;
Spinner activityLevel;
EditText age;
private Animation anim;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_profile, container,
false);
String username =
getActivity().getIntent().getStringExtra("Username");
TextView userMain = (TextView) myView.findViewById(R.id.User);
userMain.setText(username);
age =(EditText)myView.findViewById(R.id.editText3);
age.setInputType(InputType.TYPE_CLASS_NUMBER);
heightSpinner = (Spinner) myView.findViewById(R.id.HeightSpin);
weightSpinner = (Spinner) myView.findViewById(R.id.WeightSpin);
activityLevel = (Spinner) myView.findViewById(R.id.activity_level);
ArrayAdapter<CharSequence> adapter_activity =
ArrayAdapter.createFromResource(getActivity(),
R.array.activity_level, android.R.layout.simple_spinner_item);
adapter_activity.setDropDownViewResource
(android.R.layout.simple_spinner_dropdow
n_item);
activityLevel.setAdapter(adapter_activity);
goal = (Spinner) myView.findViewById(R.id.goal);
ArrayAdapter<CharSequence> adapter_goal =
ArrayAdapter.createFromResource(getActivity(),
R.array.goal, android.R.layout.simple_spinner_item);
adapter_goal.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
goal.setAdapter(adapter_goal);
gender = (Spinner) myView.findViewById(R.id.gender);
ArrayAdapter<CharSequence> adapter_gender =
ArrayAdapter.createFromResource(getActivity(),
R.array.gender, android.R.layout.simple_spinner_item);
adapter_gender.setDropDownViewResource
(android.R.layout.simple_list_item_activated_1);
gender.setAdapter(adapter_gender);
SaveButton = (Button) myView.findViewById(R.id.savebutton);
SaveButton.setOnClickListener(this);
initializeSpinnerAdapters();
loadLBVal();
loadFTVal();
anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
heightSpinner.startAnimation(anim);
anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
weightSpinner.startAnimation(anim);
anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
SaveButton.startAnimation(anim);
SharedPreferences userInfo =
PreferenceManager.getDefaultSharedPreferences(getActivity());
PreferenceManager.setDefaultValues(getActivity(),
R.xml.activity_preference, false);
return myView;
}
public void loadLBVal() {
weightSpinner.setAdapter(WeightLBSAdapter);
// set the default lib value
weightSpinner.setSelection(WeightLBSAdapter.getPosition("170"));
}
// load the feets value range to the height spinner
public void loadFTVal() {
heightSpinner.setAdapter(HeightFeetAdapter);
// set the default value to feets
heightSpinner.setSelection(HeightFeetAdapter.getPosition("5\"05'"));
}
public void initializeSpinnerAdapters() {
String[] weightLibs = new String[300];
// loading spinner values for weight
int k = 299;
for (int i = 1; i <= 300; i++) {
weightLibs[k--] = String.format("%3d", i);
}
// initialize the weightLibsAdapter with the weightLibs values
WeightLBSAdapter = new ArrayAdapter<String>(getContext(),
R.layout.activity_spinner_item, weightLibs);
WeightLBSAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
String[] heightFeets = new String[60];
// loading values 3"0' to 7"11' to the height in feet/inch
k = 59;
for (int i = 3; i < 8; i++) {
for (int j = 0; j < 12; j++) {
heightFeets[k--] = i + "\"" + String.format("%02d", j) + "'";
}
}
// initialize the heightFeetAdapter with the heightFeets values
HeightFeetAdapter = new ArrayAdapter<String>(getContext(),
R.layout.activity_spinner_item, heightFeets);
HeightFeetAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.savebutton:
int activityLevel, goal, gender, age;
// Get preferences
float height = getSelectedHeight();
float weight = getSelectedWeight();
activityLevel =
((Spinner)getActivity().findViewById
(R.id.activity_level)).getSelectedItemPosition();
goal = ((Spinner)getActivity().
findViewById(R.id.goal)).getSelectedItemPosition();
gender= ((Spinner)getActivity().
findViewById(R.id.gender)).getSelectedItemPosition();
age = Integer.parseInt(((EditText).
getActivity().findViewById(R.id.editText3)));
int tdee = calculateTDEE(height,weight,activityLevel,age,gender,
goal);
// Save preferences in XML
SharedPreferences userInfo = getSharedPreferences("userInfo",
0);
SharedPreferences.Editor editor = userInfo.edit();
editor.putInt("tdee", tdee);
editor.commit();
break;
}
}
public float getSelectedWeight() {
String selectedWeightValue = (String)weightSpinner.getSelectedItem();
return (float) (Float.parseFloat(selectedWeightValue) * 0.45359237);
}
public float getSelectedHeight() {
String selectedHeightValue = (String)heightSpinner.getSelectedItem();
// the position is feets and inches, so convert to meters and return
String feets = selectedHeightValue.substring(0, 1);
String inches = selectedHeightValue.substring(2, 4);
return (float) (Float.parseFloat(feets) * 0.3048) +
(float) (Float.parseFloat(inches) * 0.0254);
}
public int calculateTDEE(float height, float weight, int activityLevel,
int
age, int gender, int goal) {
double bmr = (10 * weight) + (6.25 * height) - (5 * age) + 5;
if(gender == 1) {
bmr = (10* weight) + (6.25 * height) - (5*age) - 161;
}
double activity = 1.25;
switch(activityLevel) {
case 1:
activity = 1.375;
break;
case 2:
activity = 1.55;
break;
case 3:
activity = 1.725;
break;
case 4:
activity = 1.9;
break;
}
double tdee = bmr * activity;
switch(goal) {
case 0:
tdee -=500;
break;
case 2:
tdee +=500;
break;
}
tdee += .5;
return (int) tdee;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
`
fragment_profile xml
`
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/imgbackground2"
android:weightSum="1">
<TextView
android:layout_width="180dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/emptyString"
android:id="#+id/User"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:layout_alignParentTop="true"
android:layout_alignEnd="#+id/tv_main_title" />
<TextView
android:layout_width="294dp"
android:layout_height="65dp"
android:text="Please Complete Information"
android:textColor="#color/colorBackground"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:textSize="20dp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="60dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Age"
android:id="#+id/textView12"
android:layout_above="#+id/gender"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5" />
<EditText
android:layout_width="50dp"
android:layout_height="50dp"
android:inputType="number"
android:ems="10"
android:id="#+id/editText3"
android:imeOptions="actionDone"
android:layout_alignTop="#+id/gender"
android:layout_alignLeft="#+id/editText"
android:layout_marginLeft="0dp"
android:layout_column="1" />
</TableRow>
</TableLayout>
<RelativeLayout
android:layout_width="194dp"
android:layout_height="26dp"></RelativeLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Gender"
android:id="#+id/textView11"
/>
<Spinner
android:layout_width="113dp"
android:layout_height="40dp"
android:id="#+id/gender"
android:layout_above="#+id/textView5"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_alignStart="#+id/textView4"
android:layout_alignEnd="#+id/textView3"
android:spinnerMode="dropdown"
android:popupBackground="#color/colorBackground" />
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="329dp"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="15dp" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="#string/weightLabel"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/colorBackground"
android:textSize="25dp"
android:paddingRight="0dp"
android:paddingLeft="-2dp" />
<Spinner
android:id="#+id/WeightSpin"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:prompt="#string/weightLabel"
android:spinnerMode="dropdown"
android:layout_weight="2"
android:textAlignment="center"
android:popupBackground="#drawable/graybackground2"
android:layout_span="2"
android:layout_column="1" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="15dp" >
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="#string/heightLabel"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/colorBackground"
android:textSize="25dp"
android:layout_column="0"
android:layout_marginLeft="5dp" />
<Spinner
android:id="#+id/HeightSpin"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:prompt="#string/heightLabel"
android:layout_weight="2"
android:popupBackground="#drawable/graybackground2"
android:spinnerMode="dropdown"
android:layout_marginTop="0dp"
android:layout_margin="0dp"
android:layout_marginBottom="0dp"
android:layout_column="1"
android:paddingTop="0dp"
android:paddingBottom="0dp"
android:textAlignment="center"
android:paddingStart="5dp"
android:layout_marginLeft="0dp"
android:layout_span="0"
android:layout_marginRight="0dp" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Activity Level"
android:id="#+id/textView7"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp" />
<Spinner
android:layout_width="200dp"
android:layout_height="50dp"
android:id="#+id/activity_level"
android:layout_below="#+id/textView7"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Goal"
android:id="#+id/textView8"
android:layout_below="#+id/activity_level"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp" />
<Spinner
android:layout_width="200dp"
android:layout_height="50dp"
android:id="#+id/goal"
android:layout_below="#+id/textView8"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:spinnerMode="dropdown" />
</TableRow>
</TableLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="#+id/savebutton"
android:radius="10dp"
android:textColor="#color/colorBackground"
android:onClick="saveAction"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#+id/editText3"
android:layout_gravity="right" />
</LinearLayout>
`
Fragmenthome.java
import java.util.ArrayList;
public class FragmentHome extends Fragment implements
View.OnClickListener {
private TextView caloriesTotal;
private TextView caloriesRemain;
private ListView listView;
private LinearLayout mLayout;
private Animation anim;
ImageButton AddEntrybtn;
ImageButton ResetEntry;
Context context;
int goalCalories;
int totalCalorie;
Button mButton;
//Database
private DatabaseHandler dba;
private ArrayList<Food> dbFoods = new ArrayList<>();
private CustomListViewAdapter foodAdapter;
private Food myFood ;
//fragment
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
public FragmentHome() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_home, container,
false);
caloriesTotal = (TextView) myView.findViewById(R.id.tv_calorie_amount);
caloriesRemain = (TextView) myView.findViewById(R.id.calorieRemain);
listView = (ListView) myView.findViewById(R.id.ListId);
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getActivity());
PreferenceManager.setDefaultValues(getActivity(),
R.xml.activity_preference, false);
goalCalories =
Integer.parseInt(prefs.getString("prefs_key_daily_calorie_amount",
"2000"));
AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
AddEntrybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
((appMain) getActivity()).loadSelection(4);
}
});
ResetEntry = (ImageButton) myView.findViewById(R.id.ResetEntry);
ResetEntry.setOnClickListener(this);
refreshData();
anim= AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
listView.startAnimation(anim);
return myView;
}
public void reset () {
//
dbFoods.clear();
dba = new DatabaseHandler(getActivity());
ArrayList<Food> foodsFromDB = dba.getFoods();
//Loop
for (int i = 0; i < foodsFromDB.size(); i ++){
String name = foodsFromDB.get(i).getFoodName();
String date = foodsFromDB.get(i).getRecordDate();
int cal = foodsFromDB.get(i).getCalories();
int foodId = foodsFromDB.get(i).getFoodId();
Log.v("Food Id", String.valueOf(foodId));
myFood= new Food();
myFood.setFoodId(foodId);
myFood.setFoodName(name);
myFood.setCalories(cal);
myFood.setRecordDate(date);
dbFoods.clear();
dbFoods.remove(myFood);
foodsFromDB.remove(myFood);
dba.deleteFood(foodId);
}
dba.close();
//setting food Adapter:
foodAdapter = new CustomListViewAdapter(getActivity(),
R.layout.row_item,dbFoods);
listView.setAdapter(foodAdapter);
foodAdapter.notifyDataSetChanged();
anim= AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
listView.startAnimation(anim);
}
public void refreshData (){
dbFoods.clear();
dba = new DatabaseHandler(getActivity());
ArrayList<Food> foodsFromDB = dba.getFoods();
totalCalorie = dba.totalCalories();
String formattedCalories = Utils.formatNumber(totalCalorie);
String formattedRemain = Utils.formatNumber(goalCalories -
totalCalorie);
//setting the editTexts:
caloriesTotal.setText("Total Calories: " + formattedCalories);
caloriesRemain.setText(formattedRemain);
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getContext());
PreferenceManager.setDefaultValues(getActivity(),
R.xml.activity_preference, false);
goalCalories =
Integer.parseInt(prefs.getString("prefs_key_daily_calorie_amount",
"2000"));
//Loop
for (int i = 0; i < foodsFromDB.size(); i ++){
String name = foodsFromDB.get(i).getFoodName();
String date = foodsFromDB.get(i).getRecordDate();
int cal = foodsFromDB.get(i).getCalories();
int foodId = foodsFromDB.get(i).getFoodId();
Log.v("Food Id", String.valueOf(foodId));
myFood= new Food();
myFood.setFoodId(foodId);
myFood.setFoodName(name);
myFood.setCalories(cal);
myFood.setRecordDate(date);
dbFoods.add(myFood);
}
dba.close();
//setting food Adapter:
foodAdapter = new CustomListViewAdapter(getActivity(),
R.layout.row_item,dbFoods);
listView.setAdapter(foodAdapter);
foodAdapter.notifyDataSetChanged();
anim= AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
listView.startAnimation(anim);
}
//save prefs
public void savePrefs(String key, int value) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.apply();
}
//get prefs
public int loadPrefs(String key, int value) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getContext());
return sharedPreferences.getInt(key, value);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle username = getActivity().getIntent().getExtras();
String username1 = username.getString("Username");
TextView userMain= (TextView) getView().findViewById(R.id.User);
userMain.setText(username1);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
startActivity( new Intent(getContext(),MainActivity.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddItems:
AddEntry addEntry = new AddEntry();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.FragmentHolder,addEntry)
.commit();
break;
case R.id.action_settings:
Intent preferenceScreenIntent = new Intent(getContext(),
PreferenceScreenActivity.class);
startActivity(preferenceScreenIntent);
break;
case R.id.ResetEntry:
reset();
anim= AnimationUtils.loadAnimation(getActivity(),
R.anim.fading);
listView.startAnimation(anim);
break;
}
}
}
preference.xml
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="User Settings">
<EditTextPreference
android:title="Daily Calorie Amount"
android:inputType="number"
android:defaultValue="2000"
android:key="#string/prefs_key_daily_calorie_amount"
android:summary="#string/prefs_description_daily_calorie_amount" />
</PreferenceCategory>
</PreferenceScreen>
You can use getContext() or getActivity() before the functions you want to invoke. getContext().getSharedPreferences(), getContext().getFilesDir(), etc.

Android App crashed and showing a white blank Screen

Note: Sorry if my problem may be really easy to fix, I'm a total beginner in this, I literally started learning this just 2 days ago.
So anyway, I'm making this basic calculator app for androids. I built the .apk and sent it to my phone but it just shows a blank white screen and then it crashes. Here's the xml code and the java code:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#drawable/numbs" >
<TextView
android:id="#+id/title"
android:text="Calculator"
android:textColor="#E11608"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="35sp"
android:layout_gravity="top|center"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#000000"
/>
<EditText
android:id="#+id/value1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:inputType="number"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:layout_gravity="center"
android:layout_marginBottom="80dp"
android:hint="Type in your next value"
/>
<EditText
android:id="#+id/value2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:inputType="number"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:layout_gravity="center"
android:layout_marginBottom="148dp"
android:hint="Type in your first value"
/>
<Button
android:id="#+id/add"
android:text="+"
android:layout_gravity="center|left"
android:onClick="onClick"
/>
<Button
android:id="#+id/minus"
android:text="-"
android:layout_gravity="center"
android:layout_marginRight="40dp"
android:onClick="onClick"
/>
<Button
android:id="#+id/divide"
android:text="÷"
android:layout_gravity="center"
android:layout_marginLeft="40dp"
android:onClick="onClick"
/>
<Button
android:id="#+id/multiply"
android:text="×"
android:layout_gravity="center|right"
android:onClick="onClick"
/>
<TextView
android:id="#+id/answer"
android:text="Your answer should display here"
android:textColor="#E11608"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10sp"
android:layout_gravity="bottom|center"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp"
android:background="#FFFFFF"
/>
</FrameLayout>
Java code:
package com.Drift.app;
import android.app.*;
import android.os.*;
import java.io.*;
import android.widget.*;
import android.view.View.*;
import android.view.*;
public class MainActivity extends Activity
{
int val1;
int val2;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
work();
}
public void work()
{
//create parameter for add button
Button add = (Button) findViewById(R.id.add);
Button multiply = (Button) findViewById(R.id.multiply);
Button minus = (Button) findViewById(R.id.minus);
Button divide = (Button) findViewById(R.id.divide);
TextView title = (TextView) findViewById(R.id. title);
final TextView answer = (TextView) findViewById(R.id. answer);
final EditText value1 = (EditText) findViewById(R.id. value1);
final EditText value2 = (EditText) findViewById(R.id. value2);
val1 = Integer.parseInt(value1.getText().toString());
final Integer val1 = new Integer(value1.getText().toString());
val2 = Integer.parseInt(value2.getText().toString());
final Integer val2 = new Integer(value2.getText().toString());
add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
answer.setText(String.valueOf(val1 + val2));
}
});
multiply.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
answer.setText(String.valueOf(val1 * val2));
}
});
minus.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
answer.setText(String.valueOf(val1 - val2));
}
});
divide.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
answer.setText(String.valueOf(val1 / val2));
}
});
}
}
Sorry for not commenting much. Can someone please tell me what I did wrong or maybe propose a better code. P.s sorry again if nearly everything here is wrong but like I said, I'm a total beginner. Thanks.
Okay, thanks for the answers this is is what I ended up with
package com.Drift.app;
import android.app.*;
import android.os.*;
import java.io.*;
import android.widget.*;
import android.view.View.*;
import android.view.*;
public class MainActivity extends Activity
{
int val1;
int val2;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
work();
}
public void work()
{
//create parameter for add button
Button add = (Button) findViewById(R.id.add);
Button multiply = (Button) findViewById(R.id.multiply);
Button minus = (Button) findViewById(R.id.minus);
Button divide = (Button) findViewById(R.id.divide);
TextView title = (TextView) findViewById(R.id. title);
final TextView answer = (TextView) findViewById(R.id. answer);
final EditText value1 = (EditText) findViewById(R.id. value1);
final EditText value2 = (EditText) findViewById(R.id. value2);
if(value1.getText()!=null)
{val1 = Integer.parseInt(value1.getText().toString());}
if(value2.getText()!=null)
{val2 = Integer.parseInt(value2.getText().toString());}
add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
answer.setText(String.valueOf(val1 + val2));
}
});
multiply.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
answer.setText(String.valueOf(val1 * val2));
}
});
minus.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
answer.setText(String.valueOf(val1 - val2));
}
});
divide.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
answer.setText(String.valueOf(val1 / val2));
}
});
}
}
But it's still giving me a blank white page, I'm using gradle by the way
Here's the Android manifest file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.Drift.app" >
<application
android:allowBackup="true"
android:icon="#drawable/calc"
android:label="#string/app_name"
android:theme="#android:style/Theme.Holo.Light" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
java.lang.RuntimeException: Binary XML file line #51: You must supply a layout_width attribute.
All views must have android:layout_width and android:layout_height defined. At least your Buttons don't have either.
Try to check EditText value before use it :
if(value1.getText().toString().trim().length()>0){
val1 = Integer.parseInt(value1.getText().toString());
}
if(value2.getText().toString().trim().length()>0){
val2 = Integer.parseInt(value2.getText().toString());
}
It is a probably a problem with a parsing. You are getting value from empty editText. You should not do that in on create method. You should check if value2 and value1 are null before using it.
if(value2.getText()!=null){val2 = Integer.parseInt(value2.getText().toString());}
here is the full working code. i have executed this and its working fine.
ur activity
public class MainAvtivity extends Activity {
int val1;
int val2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seekbar);
work();
}
public void work() {
// create parameter for add button
Button add = (Button) findViewById(R.id.add);
Button multiply = (Button) findViewById(R.id.multiply);
Button minus = (Button) findViewById(R.id.minus);
Button divide = (Button) findViewById(R.id.divide);
TextView title = (TextView) findViewById(R.id.title);
final TextView answer = (TextView) findViewById(R.id.answer);
final EditText value1 = (EditText) findViewById(R.id.value1);
final EditText value2 = (EditText) findViewById(R.id.value2);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!"".equals(value1.getText().toString())) {
val1 = Integer.parseInt(value1.getText().toString());
}
if (!"".equals(value2.getText().toString())) {
val2 = Integer.parseInt(value2.getText().toString());
}
answer.setText(String.valueOf(val1 + val2));
}
});
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!"".equals(value1.getText().toString())) {
val1 = Integer.parseInt(value1.getText().toString());
}
if (!"".equals(value2.getText().toString())) {
val2 = Integer.parseInt(value2.getText().toString());
}
answer.setText(String.valueOf(val1 * val2));
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!"".equals(value1.getText().toString())) {
val1 = Integer.parseInt(value1.getText().toString());
}
if (!"".equals(value2.getText().toString())) {
val2 = Integer.parseInt(value2.getText().toString());
}
answer.setText(String.valueOf(val1 - val2));
}
});
divide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (!"".equals(value1.getText().toString())) {
val1 = Integer.parseInt(value1.getText().toString());
}
if (!"".equals(value2.getText().toString())) {
val2 = Integer.parseInt(value2.getText().toString());
}
answer.setText(String.valueOf(val1 / val2));
}
});
}
}
and u have not specified height and weight in xml.
try this xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/numbs"
android:gravity="center" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="top|center"
android:background="#000000"
android:text="Calculator"
android:textColor="#E11608"
android:textSize="35sp" />
<EditText
android:id="#+id/value1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:layout_marginBottom="80dp"
android:background="#FFFFFF"
android:ems="10"
android:hint="Type in your next value"
android:inputType="number" />
<EditText
android:id="#+id/value2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:layout_marginBottom="148dp"
android:background="#FFFFFF"
android:ems="10"
android:hint="Type in your first value"
android:inputType="number" />
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|left"
android:onClick="onClick"
android:text="+" />
<Button
android:id="#+id/minus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="40dp"
android:onClick="onClick"
android:text="-" />
<Button
android:id="#+id/divide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="40dp"
android:onClick="onClick"
android:text="÷" />
<Button
android:id="#+id/multiply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|right"
android:onClick="onClick"
android:text="×" />
<TextView
android:id="#+id/answer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_gravity="bottom|center"
android:layout_marginBottom="40dp"
android:background="#FFFFFF"
android:text="Your answer should display here"
android:textColor="#E11608"
android:textSize="10sp" />
</FrameLayout>

Categories

Resources