I am new to Android and programming and having a bit of difficulties with my code. I tried to research this but couldn't find out what was wrong, would appreciate the help. I am basically trying to multiply two values but every time I run my emulator and click on the button (calculate) it crashes:
Java Code:
package com.example.cantcook;
import java.math.BigDecimal;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Calculator extends Activity {
EditText costofmeal, amountofpeople;
TextView costperperson;
Button Calculate;
BigDecimal costNum, percentNum;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
costofmeal = (EditText) findViewById(R.id.editText1);
amountofpeople = (EditText) findViewById(R.id.editText2);
Calculate = (Button) findViewById(R.id.button1);
costperperson = (TextView) findViewById(R.id.textView2);
//costperperson.setText("£0.00");
Calculate.setOnClickListener(new View.OnClickListener()
{
public void onClick (View v)
{
costNum = new BigDecimal(costofmeal.getText().toString());
percentNum = new BigDecimal(amountofpeople.getText().toString());
costperperson.setText(costNum.multiply(percentNum).toString());
}
});
}
XML code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
tools:context=".Calculator" >
<TextView
android:id="#+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="25dp"
android:text="£"
android:textAlignment="center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="112dp"
android:text=" Total spent on Shopping"
android:textAlignment="center"
android:textSize="18dp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text=" Amount of People"
android:textAlignment="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="18dp"
android:textStyle="bold" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView2"
android:layout_alignParentRight="true"
android:layout_marginBottom="25dp"
android:onClick="Btncalculate"
android:text="Calculate" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView3"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="numberSigned" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="17dp"
android:ems="10"
android:inputType="numberDecimal"
android:text="£" />
</RelativeLayout>
In your xml layout you have android:onClick="Btncalculate" in button1. What this does is when a click happens Android tries to look for Btncalculate method in your activity. And I'm assuming you don't have it there, since you're using an OnClickListener for button1(which, in my opinion, is better then using android:onClick).
Remove android:onClick="Btncalculate" from the xml file and it should work(unless there are other errors, in which case it would be great to see the stack trace).
Update
From your stacktrace:
java.lang.NumberFormatException: £5
Looks like you're code is trying to put "£5" into BigDecimal, which is not allowed, since it is not a number. To fix this you can either set android:inputType to a number in your editText1 and remove android:text="£", or use a separate method to filter out the £ sign from input.
Related
When I'm trying to transfer data between activities, I can't get my message and the app keeps crashing,
It show me 'app keeps stopping'
Code in MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
Intent outIntent;
EditText edtPhone;
EditText edtMessage;
Button btnNext;
String tempText="";
public static final String PHONE = "PHONE";
public static final String MESSAGE = "MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnNext = (Button) findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View V) {
outIntent = new Intent(MainActivity.this, ActivityTwo.class);
edtPhone = (EditText) findViewById(R.id.edtPhone);
edtMessage = (EditText) findViewById(R.id.edtMessage);
tempText = edtPhone.getText().toString();
outIntent.putExtra(PHONE,tempText);
tempText = edtMessage.getText().toString();
outIntent.putExtra(MESSAGE,tempText);
startActivity(outIntent);
}
});
}
public void closeMethod(View view) {
finish();
}
}
ActivityTwo.java
package com.example.fir;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;
public class ActivityTwo extends AppCompatActivity {
Intent incomingIntent;
TextView txtPhone;
TextView txtMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
incomingIntent = getIntent();
txtPhone = (TextView) findViewById(R.id.txtPhone);
txtMessage = (TextView) findViewById(R.id.txtMessage);
txtPhone.setText(incomingIntent.getStringExtra(MainActivity.PHONE));
txtMessage.setText(incomingIntent.getStringExtra(MainActivity.MESSAGE));
}
}
Activitymain.xml
<?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=".MainActivity" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="32dp"
android:text="Phone" />
<EditText
android:id="#+id/editTextPhone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginTop="60dp"
android:ems="10"
android:hint="Phone"
android:inputType="phone"
android:minHeight="48dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="124dp"
android:text="Message" />
<EditText
android:id="#+id/editTextTextPersonName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_centerHorizontal="true"
android:layout_marginStart="0dp"
android:layout_marginTop="156dp"
android:layout_marginEnd="3dp"
android:ems="10"
android:hint="Message"
android:inputType=""
android:minHeight="48dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="224dp"
android:orientation="horizontal">
<Button
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Next" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="closeMethod"
android:text="CLose" />
</LinearLayout>
</RelativeLayout>
Activitytwo.xml
////
<?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=".MainActivity" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="32dp"
android:text="Phone" />
<EditText
android:id="#+id/editTextPhone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginTop="60dp"
android:ems="10"
android:hint="Phone"
android:inputType="phone"
android:minHeight="48dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="124dp"
android:text="Message" />
<EditText
android:id="#+id/editTextTextPersonName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_centerHorizontal="true"
android:layout_marginStart="0dp"
android:layout_marginTop="156dp"
android:layout_marginEnd="3dp"
android:ems="10"
android:hint="Message"
android:inputType=""
android:minHeight="48dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="224dp"
android:orientation="horizontal">
<Button
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Next" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="closeMethod"
android:text="CLose" />
</LinearLayout>
</RelativeLayout>
The issue is when I don't put any value into the firstEditText or secondEditText or both of them and click on any button then the app crashes and a pop up shows "myapp keeps stopping".
I cannot get the text and am unsure of why the app keeps crashing.
you have defined your Edit texts in the first activity with id's named
edtPhone
edtMessage
but there was no edtPhone or edtMessage in your xml.
this issue also repeats in your second activity
you have defined txtPhone and txtMessage
but again there are no such ids in your second activity XML.
keep in mind that these might not be the whole problem as you didn't post any log for the errors. but if there were anything else, ask and we'll help you
I am creating an Faq page using TextViews, So the textviews become visible and hide automatically when clicked, but this was overlapping the upcoming question so I researched and found marginlayoutparams solution but this code won't reset back when clicked again.
Initial state:
After I click Fare Charges:
After I click on it again:
The code:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class faq extends AppCompatActivity {
TextView mfaq,mAns,mfaq2,mAns2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faq);
mfaq=findViewById(R.id.faq1);
mAns=findViewById(R.id.ans);
mfaq2=findViewById(R.id.faq2);
mAns2=findViewById(R.id.ans2);
mfaq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mAns.getVisibility()== View.VISIBLE){
ViewGroup.MarginLayoutParams marginParams = (ViewGroup.MarginLayoutParams) mfaq2.getLayoutParams();
marginParams.setMargins(marginParams.leftMargin,
-400, //setting it back to 0 this part isnt working
marginParams.rightMargin,
marginParams.bottomMargin);
mAns.setVisibility(View.GONE);
}
else
mAns.setVisibility(View.VISIBLE);
ViewGroup.MarginLayoutParams marginParams = (ViewGroup.MarginLayoutParams) mfaq2.getLayoutParams();
marginParams.setMargins(marginParams.leftMargin,
400, //only changing top margin
marginParams.rightMargin,
marginParams.bottomMargin);
}
});
mfaq2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mAns2.getVisibility()== View.VISIBLE){
mAns2.setVisibility(View.GONE);
}
else
mAns2.setVisibility(View.VISIBLE);
}
});
}
}
I don't know how to set it back to initial state like first image. Please help. Note- I am a beginner so please explain me so I can learn and understand.
Can you print the xml ? try with "wrap_content" in parent layout
You can use Cardview to encapsulate your Faq element :
https://developer.android.com/guide/topics/ui/layout/cardview
Then change the visibility of the component that you want to hide as gone and set a listner to change the visibility if the textView (or your cardView ) is clicked
Textview label = (TextView ) myPosts.findViewById(R.id.cancel);
cancelButton.setOnClickListener(view->{
if(newPostCard.getVisibility() == View.VISIBLE){
TransitionManager.beginDelayedTransition(cardView,
new AutoTransition());
newPostCard.setVisibility(View.GONE);
newPostButton.setVisibility(View.VISIBLE);
}
else{
TransitionManager.beginDelayedTransition(cardView,
new AutoTransition());
newPostCard.setVisibility(View.VISIBLE);
newPostButton.setVisibility(View.GONE);
}
});
The way I got around to this problem was to add a linear layout to the questions and answer fields. here is the xml code:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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="#android:color/holo_orange_dark"
tools:context=".faq">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="300dp"
tools:context=".faq">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="#string/Welcome"
android:textColor="#000000"
android:textColorHighlight="#000000"
android:textColorHint="#000000"
android:textSize="36sp"
app:fontFamily="#font/racing_sans_one"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/frequentlyaskedquestions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="#string/faqs"
android:textColor="#FFFFFF"
android:textColorHighlight="#FFFFFF"
android:textColorHint="#FFFFFF"
android:textColorLink="#FFFFFF"
android:textSize="18sp"
app:fontFamily="#font/racing_sans_one"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
<TextView
android:id="#+id/clickonthem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/clickonthem"
android:textColor="#FFFFFF"
android:textColorHighlight="#FFFFFF"
android:textColorHint="#FFFFFF"
android:textColorLink="#FFFFFF"
android:textSize="18sp"
app:fontFamily="#font/racing_sans_one"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/frequentlyaskedquestions" />
<LinearLayout
android:layout_width="409dp"
android:layout_height="294dp"
android:layout_marginTop="28dp"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/clickonthem">
<TextView
android:id="#+id/faq1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:clickable="true"
android:focusable="true"
android:text="#string/q1"
android:textColor="#000000"
android:textColorHighlight="#000000"
android:textColorHint="#000000"
android:textSize="18sp"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/ans"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="5dp"
android:layout_marginRight="20dp"
android:text="#string/a1"
android:textColor="#000000"
android:textColorHighlight="#000000"
android:textColorHint="#000000"
android:textColorLink="#000000"
android:textSize="18sp"
android:textStyle="bold|italic"
android:visibility="gone" />
<TextView
android:id="#+id/faq2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:clickable="true"
android:focusable="true"
android:text="#string/q2"
android:textColor="#000000"
android:textColorHighlight="#000000"
android:textColorHint="#000000"
android:textSize="18sp"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/ans2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="5dp"
android:layout_marginRight="20dp"
android:text="#string/a2"
android:textColor="#000000"
android:textColorHighlight="#000000"
android:textColorHint="#000000"
android:textColorLink="#000000"
android:textSize="18sp"
android:textStyle="bold|italic"
android:visibility="gone" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
The app is supposed to call one screen from another and use the other screen's layout components. Whenever I try to call a component, such as ImageButton, it says that member id is unknown, I told my teacher and he says that it shouldn't happen. I have tried renaming the components and even made a new project.
How can I fix it?
the error is in R.id
package com.movil.ejemploventanas;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
public class DatosPersonales extends Activity {
EditText vEdtNom,vEdtEdad;
ImageButton vBtnOrigen,vBtnSantuario;
Intent intnEnvio;
Bundle bndContenedorEnvio;
String strNom;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.datospersonales);
vEdtNom=(EditText)findViewById(R.id.edtNom);
vEdtEdad=(EditText)findViewById(R.id.edtEdad);
vBtnOrigen=(ImageButton)findViewById(R.id.btnOrigen);
vBtnSantuario=(ImageButton)findViewById(R.id.btnSantuario);
intnEnvio=new Intent(DatosPersonales.this,Caracteristicas.class);
bndContenedorEnvio=new Bundle();
vBtnOrigen.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
strNom=vEdtNom.getText().toString();
bndContenedorEnvio.putString("nom",strNom);
bndContenedorEnvio.putString("edad", vEdtEdad.getText().toString());
bndContenedorEnvio.putString("opc","1");
intnEnvio.putExtras(bndContenedorEnvio);
startActivity(intnEnvio);
}
});
vBtnSantuario.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
strNom=vEdtNom.getText().toString();
bndContenedorEnvio.putString("nom",strNom);
bndContenedorEnvio.putString("edad",vEdtEdad.getText().toString());
bndContenedorEnvio.putString("opc","2");
intnEnvio.putExtras(bndContenedorEnvio);
startActivity(intnEnvio);
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/txtLetrero"
style="style/titulo"
android:layout_centerHorizontal="true"
android:text="#string/letMariposa"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/txtLetrero"
android:id="#+id/linearlayout1"
android:layout_centerHorizontal="true"
android:layout_marginTop="66dp">
<TextView
android:id="#+id/txtNom"
style="style/letreros"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="string/nom"/>
<EditText
android:id="#+id/edtNom"
style="style/datos"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:inputType="textPersonName"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout1"
android:id="#+id/linearlayout2"
android:layout_centerHorizontal="true">
<TextView
android:id="#+id/txtEdad"
style="style/letreros"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="#string/edad"
android:textAlignment="gravity"/>
<EditText
android:id="#+id/edtEdad"
style="style/datos"
android:layout_width="220dp"
android:ems="10"
android:layout_height="wrap_content"
android:inputType="number"/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/origen"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_below="#+id/linearLayout2"
android:layout_marginLeft="30dp"
android:layout_marginTop="200dp"
android:id="#+id/textView4"
style="style/letreros"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_below="#id/textView4"
android:layout_marginLeft="80dp"
android:id="#+id/btnOrigen"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sant"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_below="#+id/btnOrigen"
android:layout_marginLeft="120dp"
android:id="#+id/textView5"
style="style/letreros"/>
<ImageButton
android:id="#+id/btnSantuario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView5"
android:layout_marginLeft="180dp"/>
</RelativeLayout>
The simple app with just one activity is creating problems with finding the layout's TextView and showing the same as null. Kindly debug the same why the app is crashing on clicking the submit button. I tried many solutions in Stack Overflow and many solutions say that the view might be located outside the activity specified, but here the only one activity is there. So research didn't help me, and now I'm left with the fellow developers who could predict the fault I could have committed.
MainActivity.java
package me.thirumurugan.quiz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button submit;
TextView result;
RadioButton answer_a;
EditText answer_b;
CheckBox answer_c1, answer_c2, answer_c3, answer_c4;
EditText answer_d;
int correct = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
answer_a = (RadioButton) findViewById(R.id.answer_a);
answer_b = (EditText) findViewById(R.id.answer_b);
answer_c1 = (CheckBox) findViewById(R.id.answer_c1);
answer_c2 = (CheckBox) findViewById(R.id.answer_c2);
answer_c3 = (CheckBox) findViewById(R.id.answer_c3);
answer_c4 = (CheckBox) findViewById(R.id.answer_c4);
answer_d = (EditText) findViewById(R.id.answer_d);
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
correct = 0;
if (answer_a.isChecked()){
correct++;
}
if (answer_b.getText().toString().equals("2020")){
correct++;
}
if (answer_c1.isChecked()&&answer_c2.isChecked()&&answer_c3.isChecked()&&!answer_c4.isChecked()){
correct++;
}
if (answer_d.getText().toString().toLowerCase().equals("arun jaitley")){
correct++;
}
result.setText("The Score is " + correct + " on 4!");
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context="me.thirumurugan.quiz.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/welcome_messege"
android:textAlignment="center"
android:id="#+id/result"
android:padding="#dimen/padding"
android:textStyle="bold"
android:textSize="16sp"
android:background="#color/colorAccent"
android:textColor="#FFF"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/padding"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/padding"
android:text="#string/question_1"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/answer_a"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_1_a" />
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_1_b" />
</RadioGroup>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/padding"
android:layout_marginTop="#dimen/padding"
android:text="#string/question_2"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<EditText
android:id="#+id/answer_b"
android:hint="#string/answer_hint"
android:textColorHint="#color/colorAccent"
android:layout_width="match_parent"
android:textSize="14sp"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimary"
tools:targetApi="lollipop" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/padding"
android:layout_marginTop="#dimen/padding"
android:text="#string/question_3"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<CheckBox
android:id="#+id/answer_c1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_3_a" />
<CheckBox
android:id="#+id/answer_c2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_3_b" />
<CheckBox
android:id="#+id/answer_c3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_3_c" />
<CheckBox
android:id="#+id/answer_c4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_3_d" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/padding"
android:layout_marginTop="#dimen/padding"
android:text="#string/question_4"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<EditText
android:id="#+id/answer_d"
android:hint="#string/answer_hint"
android:textSize="14sp"
android:textColorHint="#color/colorAccent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimary"
tools:targetApi="lollipop" />
<Button
android:id="#+id/submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimary"
android:text="#string/submit"
android:textColor="#FFFFFF"
android:textStyle="bold"
tools:targetApi="lollipop" />
</LinearLayout>
</ScrollView>
</LinearLayout>
The error message was the following in the trace:
08-10 21:58:06.301 20947-20947/me.thirumurugan.quiz E/AndroidRuntime:
FATAL EXCEPTION: main Process: me.thirumurugan.quiz, PID: 20947
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null
object reference at
me.thirumurugan.quiz.MainActivity$1.onClick(MainActivity.java:52) at
android.view.View.performClick(View.java:5637) at
android.view.View$PerformClick.run(View.java:22429) at
android.os.Handler.handleCallback(Handler.java:751) at
android.os.Handler.dispatchMessage(Handler.java:95) at
android.os.Looper.loop(Looper.java:154) at
android.app.ActivityThread.main(ActivityThread.java:6119) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
You are in need of a clean and rebuild. There is nothing wrong with your code. Multiple users have copied the code and used it to success in their applications, including myself:
Text is missing because I do not have your dimens or strings files.
You do not have a scope issue, as others have suggested. Your member variables should be accessible by any anonymous inner class you create.
There are otherwise missing lines from your shared code. In which case, the community can not resolve your problem as nobody will be capable of replicating it.
I am new to android. I am trying to make simple unit converter. The layout contains EditText for input, two spinners (to and from), an ImageButton and EditText to display answer.
I want to add values to spinners and when these values are selected i want to perform action.
My xml code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".BitsBytes" >
<Spinner
android:id="#+id/SpinnerFrom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_alignRight="#+id/inputvalue"
android:layout_below="#+id/textView2"
android:entries="#array/bitsbytesfrom"
android:prompt="#string/from_prompt" />
<Spinner
android:id="#+id/SpinnerTo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView3"
android:layout_alignRight="#+id/SpinnerFrom"
android:layout_below="#+id/textView3"
android:entries="#array/bitsbytesto"
android:prompt="#string/to_prompt" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/SpinnerFrom"
android:layout_below="#+id/SpinnerFrom"
android:layout_marginTop="16dp"
android:text="To:"
android:textColor="#000000"
android:textSize="20dp" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="Value: "
android:textSize="20dp" />
<EditText
android:id="#+id/inputvalue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView6"
android:layout_alignBottom="#+id/textView6"
android:layout_toRightOf="#+id/textView6"
android:ems="10"
android:hint="Enter value"
android:inputType="numberDecimal" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView6"
android:layout_below="#+id/inputvalue"
android:layout_marginTop="16dp"
android:text="From:"
android:textColor="#000000"
android:textSize="20sp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:text="Bits/Bytes Conversion"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25dp" />
<ImageButton
android:id="#+id/convertButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/SpinnerTo"
android:layout_centerHorizontal="true"
android:background="#00000000"
android:src="#drawable/btnconvert"
android:clickable="true"/>
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/answer"
android:layout_centerHorizontal="true"
android:text="Answer"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/answer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="28dp"
android:ems="10"
android:inputType="numberDecimal" />
</RelativeLayout>
My java code:
package com.easy.convert;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
public class BitsBytes extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bitsbytes);
ImageButton ib = (ImageButton) findViewById(R.id.convertButton);
ib.setOnClickListener(new View.OnClickListener() {
EditText etValue = (EditText) findViewById(R.id.inputvalue);
Spinner spBitsBytesFrom = (Spinner) findViewById(R.id.SpinnerFrom);
Spinner spBitsBytesTo = (Spinner) findViewById(R.id.SpinnerTo);
String txtFromSpinner = spBitsBytesFrom.getSelectedItem().toString();
String txtToSpinner = spBitsBytesTo.getSelectedItem().toString();
TextView Answer = (TextView) findViewById(R.id.answer);
public void onClick(View v)
{
if (txtFromSpinner.equals("Bits") && txtToSpinner.equals("Bytes"))
{
Double value = Double.parseDouble(etValue.getText().toString());
Double answer = (double) 0;
answer = value/8;
String stringAnswer = Double.toString(answer);
Answer.setText(stringAnswer);
}
}
});
}
}
I am filling the spinners using string array. I am not able to figure out whats wrong in my code because there is no error in logcat.
Change this,
(txtFromSpinner.equals("Bits") && txtToSpinner.equals("Bytes"))
to
if((txtFromSpinner.getSelectedItem().toString().equals("Bits")) && (txtToSpinner.getSelectedItem().toString().equals("Bytes")))
this will get the text from the item selected in the spinner.