I'm creating a simple quiz according to this tutorial, but the app crashes with the button "Next answer" which is related to a checked radio button.
Main code:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class Display extends Activity {
TextView tv;
Button btnNext;
RadioGroup rg;
RadioButton rb1, rb2,rb3;
String questions[]={"Capital of Portugal?", "Capital of Spain?", "Capital of France?"};
String answers[]={"Lisbn","Madrid","Paris"};
String options[]={"Zuriq", "London","Lisbon","Manchester","Buenos Aires","Madrid", "NY", "Paris","Moscow"};
int flag=0;
public static int marks,correct,wrong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dispaly);
tv=(TextView) findViewById(R.id.tvque);
btnNext=(Button) findViewById(R.id.btnNext);
rb1= (RadioButton) findViewById(R.id.radioButton);
rb2= (RadioButton) findViewById(R.id.radioButton2);
rb3= (RadioButton) findViewById(R.id.radioButton3);
tv.setText(questions[flag]);
rb1.setText(options[flag*3]);
rb2.setText(options[(flag*3)+1]);
rb3.setText(options[(flag*3)+2]);
Toast.makeText(this, "Negative Marks: " + MainActivity.tbflag, 1000).show();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//The error comes from the line bellow, i believe:
RadioButton user_answer= (RadioButton)findViewById(rg.getCheckedRadioButtonId());
String answerText=user_answer.getText().toString();
if(answerText.equalsIgnoreCase(answers[flag])){
correct++;
}else{
wrong++;
flag++;
if(flag<questions.length){
tv.setText(questions[flag]);
rb1.setText(options[flag*3]);
rb2.setText(options[(flag*3)+1]);
rb3.setText(options[(flag*3)+2]);
}
else
{
if(MainActivity.tbflag)
{
marks=correct-wrong;
}
else
{
marks=correct;
}
Intent in =new Intent(getApplicationContext(), ResultActivity.class);
startActivity(in);
}
}
}
});
}
}
Log message:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.RadioGroup.getCheckedRadioButtonId()' on a null object reference
I don't understand this error, why isn't the method being called? Can someone help?
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.vtorferreira.anew.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvque"
tools:text="Questions" />
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/group">
<RadioButton
android:text="RadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="32dp"
android:id="#+id/radioButton" />
<RadioButton
android:text="RadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/radioButton2" />
<RadioButton
android:text="RadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioButton3"
android:layout_below="#+id/radioButton2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RadioGroup>
<Button
android:text="Next Question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="60dp"
android:layout_marginStart="60dp"
android:layout_marginBottom="125dp"
android:id="#+id/btnNext" />
</RelativeLayout>
The reason you are getting the first NullPointerException is because you must inflate rg before it is used.
The second NullPointerException is possibly due to the fact that you are pressing the "Next" button with no radio button selected. To prevent this, you can add a null check inside the OnClickListener or select one of the radio buttons by default. To select a radio button by default, add the following to your XML:
<RadioGroup
...
android:checkedButton="#+id/some-radio-button-id">
...
</RadioGroup>
Alternatively, you can set the default checked RadioButton in your Activity:
rg.check(R.id.radioButton)
Related
So i am making a quiz with two activities and a class with questions, answers and right answers in collections, one main activity with the question to answer, 4 options (RadioGroup with RadioButtons) and a button submit, when this last is clicked, i want to get the Radio Button value to another activity which shows a sentence whether if you are right or wrong and a button to continue the next question (in MainActivity). I know how to get the RadioButton text in the old way, but not with binding initialized.
This is the activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout 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"\>`
<data />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/campofutbol" />
<LinearLayout
android:id="#+id/linear1"
android:layout_width="match_parent"
android:layout_height="320dp"
android:orientation="vertical">
<TextView
android:id="#+id/txtQuestionNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="185dp"
android:layout_marginTop="130dp"
android:fontFamily="sans-serif-medium"
android:text="#string/contador_pregunta_1"
android:textColor="#color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/txtQuestion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:paddingStart="60dp"
android:paddingEnd="50dp"
android:text="#string/Question_1"
android:textAlignment="inherit"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="420dp"
android:layout_alignParentBottom="true"
android:orientation="vertical">
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="290dp">
<RadioButton
android:id="#+id/rButtonA"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_marginStart="60dp"
android:layout_marginTop="70dp"
android:layout_marginEnd="30dp"
android:paddingEnd="40dp"
android:text="#string/Opcion_1_a" />
<RadioButton
android:id="#+id/rButtonB"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_marginStart="60dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="30dp"
android:paddingEnd="40dp"
android:text="#string/Opcion_1_b" />
<RadioButton
android:id="#+id/rButtonC"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_marginStart="60dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="30dp"
android:paddingEnd="40dp"
android:text="#string/Opcion_1_c" />
<RadioButton
android:id="#+id/rButtonD"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_marginStart="60dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="30dp"
android:paddingEnd="40dp"
android:text="#string/Opcion_1_d" />
</RadioGroup>
<Button
android:id="#+id/btnSubmit"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginStart="150dp"
android:layout_marginTop="40dp"
android:text="#string/submit"
android:theme="#color/blue_clue" />
</LinearLayout>
</RelativeLayout>
and this is the MainActivity.Java i have right now.
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
import dam.pmdm.a05_quizzes.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView txtQuestionNumber;
TextView txtQuestion;
RadioGroup rg;
RadioButton optA;
RadioButton optB;
RadioButton optC;
RadioButton optD;
Button btnSubmit;
int score = 0;
int totalQuestion = QuestionsAnswers.questions.length;
int currentQuestion = 0;
ActivityMainBinding binding;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
txtQuestionNumber = binding.txtQuestionNumber;
txtQuestion = binding.txtQuestion;
rg = (RadioGroup) binding.radioGroup; ...
}
This is what i want to change to binding "way".
public class MainActivity extends AppCompatActivity implements View.OnClickListener {...
rg = (RadioGroup) binding.radioGroup;
final String value = ((RadioButton) findViewById(rg.getCheckedRadioButtonId()))
`.getText().toString();`
...}
The rest of the code from MainActivity.java if someone wants to optimize it. I was testing if i could display the radio button value in a Toast and now can't even see the screen (as you can see i'm learning).
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
Toast.makeText(getBaseContext(), value, Toast.LENGTH_SHORT).show();
}
});
optA = binding.rButtonA;
optB = binding.rButtonB;
optC = binding.rButtonC;
optD = binding.rButtonD;
btnSubmit = binding.btnSubmit;
optA.setOnClickListener(this);
optB.setOnClickListener(this);
optC.setOnClickListener(this);
optD.setOnClickListener(this);
btnSubmit.setOnClickListener(this);
txtQuestionNumber.setText(currentQuestion + 1 + " / " + totalQuestion);
}
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="#+id/away"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:text="#string/away"
android:gravity="center"
android:textSize="20sp"/>
<TextView
android:id="#+id/score"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="50dp"
android:layout_marginTop="50dp"
android:gravity="center"
android:text="#string/_0"
android:textSize="20sp" />
<Button
android:id="#+id/one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="50dp"
android:onClick="score1"
android:text="#string/score" />
<TextView
android:id="#+id/home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="50dp"
android:layout_marginTop="50dp"
android:text="#string/home"
android:textSize="20sp"
android:gravity="center"/>
<TextView
android:id="#+id/score2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginBottom="50dp"
android:text="#string/_0"
android:textSize="20sp" />
<Button
android:id="#+id/two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="score2"
android:text="#string/score" />
<Button
android:id="#+id/reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/reset"
android:layout_gravity="center"
android:layout_marginTop="50dp"
android:textColor="#ff1100"/>
</LinearLayout>
I searched it on multiple websites but I still can't the answer. I also tried using the__setText("")it
didn't work as well as the the if() method. I have also tried the intent method also doesn't seem to
work, and many other codes , please help me because I am stuck at this bit , I know that it is simple but
I just can't find it. Thank you
The following codes will set the TextView score to blank when Button one is clicked
First approach
To use the android:onClick="score1" in your XML
Add this to your activity
TextView mTvScore1 = (TextView) findViewById(R.id.score)
public void score1(View v) {
mTvScore1.setText("");
}
Second approach
Button mBtn = (Button) findViewById(R.id.one)
TextView mTvScore1 = (TextView) findViewById(R.id.score)
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTvScore1.setText("");
}
});
Activity code
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView mTvScore1 = (TextView) findViewById(R.id.score);
Button mBtn = (Button) findViewById(R.id.one);
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
score1(v);
}
});
}
public void score1(View v) {
mTvScore1.setText("");
}
}
I want to get the username from edit text and display it in the second Activity in TextView id-textView2. When I press enter after writing the name and click start button it goes to the second activity but the text is not being displayed . I tried executing other actions like startActivity() inside onEditorAction method it works after i press enter, but this code is not working
String name = nameText.getText().toString();
Intent p1 = new Intent(MainActivity.this, qPage1.class);
p1.putExtra("user_name",name);
Is it because i declared two times intent, inside onEditorAction() and inside starQuizz method in Activity A. i did this because of scope issues.
Activity A
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.view.KeyEvent;
import android.widget.TextView.OnEditorActionListener;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText nameText = findViewById(R.id.nameText);
nameText.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView nameText, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND || event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
String name = nameText.getText().toString();
Intent p1 = new Intent(MainActivity.this, qPage1.class);
p1.putExtra("user_name",name);
handled = true;
}
return handled;
}
});
}
//OnClick of a Start button
public void startQuizz(View view){
Intent p1 = new Intent(this, qPage1.class);
startActivity(p1);
}
}
Activity A xml layout
<?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"
android:background="#drawable/beautifulcolorgradientsbackgrounds091eternalconstance"
tools:context=".MainActivity">
<EditText
android:id="#+id/nameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="181dp"
android:width="300dp"
android:hint="#string/name_input"
android:inputType="text"
android:imeOptions="actionSend"
android:imeActionId="10"/>
<Button
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="182dp"
android:onClick="startQuizz"
android:text="START" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="45dp"
android:fontFamily="#font/changa_one"
android:text="Are you up for the challenge?"
android:textAlignment="center"
android:textAllCaps="false"
android:textSize="30sp" />
</RelativeLayout>
Activity 2
package com.guesstasif.guesswhat;
import android.content.Intent;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.view.View;
import android.widget.TextView;
public class qPage1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q_page1);
final ProgressBar p1progress = findViewById(R.id.pg1progressBar);
Runnable r = new Runnable() {
#Override
public void run() {
int progressStatus = 0;
while (progressStatus<200){
p1progress.incrementProgressBy(1);
android.os.SystemClock.sleep(50);
progressStatus++;
}
RadioButton q1radiobutton3 = findViewById(R.id.q1radioButton3);
RadioButton q2radiobutton1 = findViewById(R.id.q2radioButton1);
Intent p2 = new Intent(qPage1.this, qPage2.class);
//name==============================================================
String name = getIntent().getStringExtra("user_name");
TextView textView2= findViewById(R.id.textView2);
textView2.setText(name);
//==================================================================
if(q1radiobutton3.isChecked() && q2radiobutton1.isChecked())
{
p2.putExtra("intVariableName", 2);
}
else if (q1radiobutton3.isChecked() || q2radiobutton1.isChecked())
{
p2.putExtra("intVariableName", 1);
}
startActivity(p2);
}
};
Thread progressThread =new Thread(r);
progressThread.start();
}
}
Activity 2 xml layout
<?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=".qPage1">
<TextView
android:id="#+id/q1textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Q1.What is the name of the 7th planet of ou Solar system?"
android:textAlignment="center"
android:textSize="24sp" />
<RadioGroup
android:id="#+id/q1radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/q1textView"
android:layout_centerHorizontal="true"
android:orientation="horizontal">
<RadioButton
android:id="#+id/q1radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Jupiter" />
<RadioButton
android:id="#+id/q1radioButton2"
android:layout_width="84dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Saturn" />
<RadioButton
android:id="#+id/q1radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Uranus" />
<RadioButton
android:id="#+id/q1radioButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Neptune" />
</RadioGroup>
//second Question//
<TextView
android:id="#+id/q2textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="173dp"
android:text="Q2.What is the name of the largest tree in the world?"
android:textAlignment="center"
android:textSize="24sp" />
<RadioGroup
android:id="#+id/q2radioGroup"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_alignParentStart="true"
android:layout_below="#+id/q2textView">
<RadioButton
android:id="#+id/q2radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="General Sherman" />
<RadioButton
android:id="#+id/q2radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Sequoia sempervirens" />
<RadioButton
android:id="#+id/q2radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Centurion" />
<RadioButton
android:id="#+id/q2radioButton4"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_weight="1"
android:text="Coast redwood" />
</RadioGroup>
<ProgressBar
android:id="#+id/pg1progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="33dp"
android:max="200" />
<TextView
android:id="#+id/scoreView"
android:layout_width="170dp"
android:layout_height="41dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="89dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="137dp"
android:textAlignment="center" />
</RelativeLayout>
The reason is you start a new Intent in here:
public void startQuizz(View view){
Intent p1 = new Intent(this, qPage1.class);
startActivity(p1);
}
Which does not pass the string and just starts a new Intent-Activity.
Also here:
Intent p1 = new Intent(MainActivity.this, qPage1.class);
p1.putExtra("user_name",name);
You missed to start Intent so:
Intent p1 = new Intent(MainActivity.this, qPage1.class);
p1.putExtra("user_name",name);
startActivity(p1);
And in the quiz method, start another Intent:
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
And finally, in the second Activity:
Bundle bundle = getIntent().getExtras();
String name = bundle.getString("user_name");
Also, you were using Thread instead of runOnUIThread(); and that might cause some UI effects.
Look at the startQuizz method - seems like you are not setting the name as an extra to the intent!
You should use a single function that starts the next activity both in the editor action and the button click listener.
It seems you are setting text of a TextView in a background thread.
The UI cannot be altered in a background thread.
Try wrapping the setText() part in runOnUiThread().
Check this out: How do we use runOnUiThread in Android?
I'll answer the most obvious question here. It seems there's a lot of code work being done, here also.
EditText edittext = (EditText) findViewById(R.id.something);
You must, and I cannot stress this enough, as of Level 30, still, you have to cast it as an EditText. In fact, you have to with everything, essentially. Java doesn't like structural propagating without being handed the stalk, not the beans (seeds). So, please one last thing:
String string = edittext.getText().toString()
That works every time in this combination!
I am trying to make an application on Android Studio with the help of a tutorial. I managed to get the User Interface right and I think that I have assigned the correct buttons too. I am unable to get where I am going wrong with my code. I am new to Java and so I am unable to pinpoint the error I have committed. I am posting below the code from the files I was asked to edit in the tutorial.
package com.example.to_dolistapplication.app;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
import android.graphics.Color;
public class MainActivity extends Activity implements OnClickListener {
Button btn1;
Button btn2;
Button btn3;
TextView textTitle;
EditText scoreText;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.button);
btn2 = (Button)findViewById(R.id.button2);
btn3 = (Button)findViewById(R.id.button3);
scoreText = (EditText)findViewById(R.id.textView);
textTitle = (TextView)findViewById(R.id.editText);
//---set on click listeners on the buttons-----
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
// change font size of the text
textTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
}
#Override
public void onClick(View v) {
if (v == btn1){
counter++;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.CYAN);
}
if (v == btn2){
counter--;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.GREEN);
}
if (v == btn3){
counter = 0;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.RED);
}
}
}
Above is the File from MainActivity.java
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.to_dolistapplication.app.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+1"
android:id="#+id/button"
android:onClick="#string/intro"
android:layout_below="#+id/editText"
android:layout_toRightOf="#+id/textView"
android:layout_marginTop="79dp"
android:layout_alignRight="#+id/editText"
android:layout_alignEnd="#+id/editText" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-1"
android:id="#+id/button2"
android:layout_centerVertical="true"
android:layout_alignLeft="#+id/button"
android:layout_alignStart="#+id/button"
android:layout_alignRight="#+id/editText"
android:layout_alignEnd="#+id/editText" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
android:id="#+id/button3"
android:layout_below="#+id/button2"
android:layout_marginTop="64dp"
android:layout_alignRight="#+id/button2"
android:layout_alignEnd="#+id/button2"
android:layout_alignLeft="#+id/button2"
android:layout_alignStart="#+id/button2" />
<TextClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textClock"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_toRightOf="#+id/textView2"
android:layout_alignBottom="#+id/textView2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/editText"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="29dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Score"
android:id="#+id/textView"
android:layout_alignBottom="#+id/editText"
android:layout_toLeftOf="#+id/editText" />
This is from the file activity_main.xml.
The app, when run on emulator, displays Unfortunately Counter App has stopped.
what might be the reason for the app not working? Please help.
**EditText** scoreText = (EditText)findViewById(R.id.textView);
**TextView** textTitle = (TextView)findViewById(R.id.editText);
you missmathed with types: android:id="#+id/editText" is EditText, but in Activity you wrote his id to TextView.
And you missmathed with types: android:id="#+id/textView" is TextView, but but in Activity you wrote his id as EditText.
You've mismatched id's in onCreate() method.
Use the debug mode or just look at your console output
I am working on an android Temperature converter app(which does not work). At first I saw this message on LogCat
the application may be doing too much work on its main thread
I then removed the code that was never used.
Now, this is the error:
java.lang.RuntimeException: Unable to start activity
Code: Main_Activity.java
package com.example.tempconverter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editCelsius = (EditText) findViewById(R.id.editCelsius);
final EditText editFahrenheit = (EditText) findViewById(R.id.editFahrenheit);
Button buttonConvert =(Button)findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
double celsius = Double.valueOf(editCelsius.getText().toString());
double fahrenheit = (celsius * 9)/5 +32;
editFahrenheit.setText(String.valueOf(fahrenheit));
}
});
}
}
The code in fragment_main.xml
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.tempconverter.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textCelsius"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="55dp"
android:text="Celsius"
android:textAppearance="?android:attr/textAppearanceMedium"
tools:ignore="hardcodedtext" />
<EditText
android:id="#+id/editCelsius"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textCelsius"
android:layout_marginLeft="52dp"
android:layout_toRightOf="#+id/textCelsius"
android:ems="7"
android:inputType="number" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textFahrenheit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editCelsius"
android:layout_marginTop="31dp"
android:text="Fahrenheit"
android:textAppearance="?android:attr/textAppearanceMedium"
tools:ignore="hardcodedtext" />
<Button
android:id="#+id/buttonConvert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editFahrenheit"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:text="Convert"
tools:ignore="hardcodedtext" />
<EditText
android:id="#+id/editFahrenheit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/editCelsius"
android:layout_alignTop="#+id/textFahrenheit"
android:ems="7"
android:inputType="number" />
</RelativeLayout>
this is a part of the LogCat now ...
https://drive.google.com/file/d/0Bxd5Rg3QFBfbdkZULWxNUTVrV2M/edit?usp=sharing
Apparently, you are inflating the wrong view. You've got a RuntimeException, and you should have a NullPointerException, because the setContentView try to set (and methods findViewById try to find views inside) the wrong layout as:
setContentView(R.layout.activity_main);
whereas all your EditTexts, TextViews and Buttons are in fragment_main.xml.
Try to set the content view as follow:
setContentView(R.layout.fragment_main);
or, rename fragment_main.xml to activity_main.xml.
Update from comments:
These kinds of errors "Couldn't load memtrack module' occur with some devices with emulator. To avoid this, always test with multiple devices (real or not).