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.
Related
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 have a custom dialog in which I include another layout. In this layout there are 3 buttons and a TextView none of these is null. If I click the buttons they work correctly. But the TextView doesn't show any text. The text should appears when I click another button. That's how it should works
Custom dialog layout:
<LinearLayout
............
.....
<androidx.cardview.widget.CardView
android:id="#+id/result_card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="2dp"
card_view:cardMaxElevation="2dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="8dp"
android:visibility="gone"
app:cardCornerRadius="8dp">
<include android:id="#+id/result_layout" layout="#layout/result_block" />
</androidx.cardview.widget.CardView>
....
....
</LinearLayout>
The result_block layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:background="#color/colorPrimary"
android:orientation="vertical">
<TextView
android:id="#+id/result_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17dp"
android:text=""
android:textColor="#color/colorWhite"
android:fontFamily="sans-serif-medium"
android:padding="8dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:orientation="horizontal">
<ImageButton
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_copy_24px_outlined"
android:layout_marginEnd="16dp"
android:tint="#color/colorWhite"
android:background="?attr/selectableItemBackgroundBorderless"
/>
<ImageButton
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:tint="#color/colorWhite"
android:src="#drawable/ic_share_24px_outlined"
android:background="?attr/selectableItemBackgroundBorderless"
/>
<ImageButton
android:id="#+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tint="#color/colorWhite"
android:src="#drawable/ic_volume_up_24px_outlined"
android:background="?attr/selectableItemBackgroundBorderless"
/>
</LinearLayout>
</LinearLayout>
And now the dialog
private void showDiag() {
final View dialogView = View.inflate(getActivity(), R.layout.custom_dialog_layout,null);
final View resultLayout = View.inflate(getActivity(), R.layout.result_block,null);
final Dialog dialog = new Dialog(getActivity(), R.style.MyAlertDialogStyle);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(dialogView);
final TextView resultTxt = resultLayout.findViewById(R.id.result_txt);
final ImageButton btn1 = resultLayout.findViewById(R.id.btn1);
final CardView resultCardView = dialog.findViewById(R.id.result_card_view);
final TextInputEditText editText = dialog.findViewById(R.id.text_edit);
final ImageButton clearText = dialog.findViewById(R.id.clear_text);
MaterialButton resultConfirm = dialog.findViewById(R.id.result_confirm);
ImageButton btn2 = dialogView.findViewById(R.id.copy_btn);
ImageButton btn3 = dialogView.findViewById(R.id.share_btn);
resultConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!editText.getText().toString().equals("")) {
String theWord = editText.getText().toString();
String result = Utils.getSecondWord(theWord);
// result it shows me the correct string with no errors or something else
resultTxt.setText(result); // doesn't work. Not set the text
insertWord(theWord, result);
resultCardView.setVisibility(View.VISIBLE);
resultCardView.setVisibility(View.VISIBLE);
} else {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
}
}
});
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "result: " + resultTxt.getText().toString());
}
});
// Share btn
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "result: " + resultTxt.getText().toString());
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "result: " + resultTxt.getText().toString());
}
});
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Utils.revealShow(dialogView, true, null, resultConfirm);
}
});
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
if (i == KeyEvent.KEYCODE_BACK){
Utils.revealShow(dialogView, false, dialog, resultConfirm);
return true;
}
return false;
}
});
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.show();
}
Everything inside the dialog works correctly but the TextView not. Even if I try to write something else like resultTxt.setText("Hello there"); the text not appears. Any suggestions?
Please you remove the android:text=""in TextView because textview is get default text is empty or you write anything in TextView like android:text="abc"
I am making a quiz app. I want the exit page to be displayed when the next button is pressed after last question has been answered. I have a activity_questions.xml and a activity_exit.xml. The xml for activity_questions.xml is :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.example.android.crystal.questions">
<TextView
android:id="#+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="29dp"
android:fontFamily="sans-serif-thin"
android:padding="10dp"
android:text=""
android:textColor="#440027"
android:textSize="30dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:id="#+id/edit2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/text3"
android:layout_margin="30dp"
android:background="#9775AA"
android:hint="Answer"
android:inputType="text"
android:padding="10dp"
android:textSize="20dip" />
<LinearLayout
android:id="#+id/ll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/edit2"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="#+id/answer"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:layout_weight="1"
android:onClick="onAnswerClick"
android:padding="2dp"
android:text="Okay" />
<Button
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:layout_weight="1"
android:onClick="onHintClick"
android:padding="2dp"
android:text="Hint" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingBottom="5dp"
android:orientation="vertical"
android:layout_marginTop="26dp"
android:layout_below="#+id/ll"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<ImageView
android:id="#+id/tickcross"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_below="#+id/ll"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:src="#drawable/wierdtick" />
<TextView
android:id="#+id/correctornot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tickcross"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="Correct!"
android:textColor="#440027"
android:textSize="30dp" />
<Button
android:id="#+id/nextbutton"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Next"
android:onClick="onNextClick"
/>
</LinearLayout>
</RelativeLayout>
And the java is:
package com.example.android.crystal;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class questions extends AppCompatActivity {
Random r = new Random();
private boolean done;
private int QuestionNo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
findViewById(R.id.tickcross).setVisibility(View.INVISIBLE);
findViewById(R.id.correctornot).setVisibility(View.INVISIBLE);
findViewById(R.id.nextbutton).setVisibility(View.INVISIBLE);
String[] questions = getResources().getStringArray(R.array.Questions);
TextView t = (TextView) findViewById(R.id.text3);
t.setText(questions[QuestionNo]);
}
public void onFinishClick(View view){
Intent intent = new Intent(this, exit.class);
startActivity(intent);
}
public static void hideKeyboardFrom(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
public void answersubmitted() {
findViewById(R.id.tickcross).setVisibility(View.VISIBLE);
TranslateAnimation animation = new TranslateAnimation(0, 0, 2000, 0);
animation.setDuration(1000);
animation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
findViewById(R.id.tickcross).startAnimation(animation);
findViewById(R.id.correctornot).setVisibility(View.VISIBLE);
findViewById(R.id.nextbutton).setVisibility(View.VISIBLE);
}
public void onHintClick(View view) {
String[] hints = getResources().getStringArray(R.array.Hints);
Toast toasty = Toast.makeText(getApplicationContext(), hints[QuestionNo], Toast.LENGTH_SHORT);
toasty.show();
}
public void onAnswerClick(View view) {
if (done == false) {
hideKeyboardFrom(this);
String answer = ((EditText) findViewById(R.id.edit2)).getText().toString();
String[] answers = getResources().getStringArray(R.array.Answers);
String correctAnswer = answers[QuestionNo];
correctAnswer = correctAnswer.toUpperCase();
answer = answer.toUpperCase();
if (answer.equals(correctAnswer)) {
TextView t = (TextView) findViewById(R.id.correctornot);
t.setText("CORRECT!");
ImageView i = (ImageView) findViewById(R.id.tickcross);
i.setImageDrawable(getDrawable(R.drawable.wierdtick));
answersubmitted();
} else {
TextView t = (TextView) findViewById(R.id.correctornot);
t.setText("Correct Answer: " + correctAnswer);
ImageView i = (ImageView) findViewById(R.id.tickcross);
i.setImageDrawable(getDrawable(R.drawable.weirdcross));
answersubmitted();
}
done = true;
}
}
public void onNextClick(View view){
if (done){
String[] questions = getResources().getStringArray(R.array.Questions);
if (QuestionNo < (questions.length - 1)) {
QuestionNo += 1;
TextView t = (TextView) findViewById(R.id.text3);
t.setText(questions[QuestionNo]);
findViewById(R.id.tickcross).setVisibility(View.INVISIBLE);
findViewById(R.id.correctornot).setVisibility(View.INVISIBLE);
findViewById(R.id.nextbutton).setVisibility(View.INVISIBLE);
EditText et = (EditText) findViewById(R.id.edit2);
et.setText("");
done = false;
}
else {
onFinishClick();
}
}
}
}
But the onFinishClick() gives an error
Thanks in advance for your help
What should i do to move to another activity when only special conditions are met
Basically, an if-statement and an Intent.
Raw code with no variables added:
if(condition(s)){
Intent i = new Intent(this, TargetActivity.class);
//Put arguments into the intent if you need them...
startActivity(i);
}
You can put it in a thread, in an onClickListener, anywhere and any way you want to execute the code.
As to the error you are receiving, I cannot help you with that until you supply the stacktrace from Logcat
You can do like this:
mNextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mQuestionCount < questionList.size()){
// set next question
} else {
// call finish
}
}
});
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);
}
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>