I wrote the XML for a Quiz App.
There will be (10) questions, some RadioGroup and some CheckBox, but the type of questions will not be in any order. So the 1st is radiogroup, the 2nd checkbox, the 3rd, 4th, and 5th radiogroup, the 6th and 7th checkbox, etc.
The RadioGroup obviously has only one correct answer, and the CheckBox have two or three correct answers.
I want to create a "CHECK QUIZ" button, which displays a message at the top of the scrolling quiz giving the number correct, and also displaying a large red "X" in red at the front of each wrong answer.
I am not sure where to start for the Java code in my MainActivity java file.
MainActivity.java
package com.example.android.quiztest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.EditText;
import android.widget.TextView;
/**
* package com.example.android.quiztest;
* This app displays a radio button and checkbox quiz, and then grades the quiz, * displaying the score and identifying the incorrect answers.
**/
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.example.android.quiztest.R.layout.activity_main);
}
}
activity_main.xml
<ScrollView 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"
tools:context="com.example.android.quiztest.MainActivity"
android:fillViewport="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="#dimen/dimension_1"
android:orientation="vertical">
<EditText
android:id="#+id/name_text_view_STUDENT"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/text_person_name"
android:inputType="textPersonName" />
<TextView
android:id="#+id/label_text_view_DIRECTIONS"
style="#style/HeaderTextStyle"
android:textSize="20sp"
android:layout_marginTop="#dimen/dimension_1"
android:text="#string/text_directions" />
<TextView
android:id="#+id/label_text_view_1"
style="#style/HeaderTextStyle"
android:layout_marginTop="#dimen/dimension_1"
android:text="#string/text_1" />
<RadioGroup
android:id="#+id/radioGroup_1"
style="#style/HeaderTextStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/radioButton_1a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimension_1"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:text="#string/text_1a"
android:textSize="#dimen/text_size_1" />
<RadioButton
android:id="#+id/radioButton_1b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimension_1"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:text="#string/text_1b"
android:textSize="#dimen/text_size_1" />
<RadioButton
android:id="#+id/radioButton_1c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimension_1"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:text="#string/text_1c"
android:textSize="#dimen/text_size_1" />
</RadioGroup>
<View
android:layout_width="fill_parent"
android:layout_height="2dp"
android:layout_marginTop="25dp"
android:background="#c0c0c0" />
<TextView
android:id="#+id/label_text_view_2"
style="#style/HeaderTextStyle"
android:layout_marginTop="#dimen/dimension_1"
android:text="#string/text_2" />
<CheckBox
android:id="#+id/checkBox_2a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:text="#string/text_2a"
android:textSize="#dimen/text_size_1" />
<CheckBox
android:id="#+id/checkBox_2b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimension_1"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:text="#string/text_2b"
android:textSize="#dimen/text_size_1" />
<CheckBox
android:id="#+id/checkBox_2c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimension_1"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:text="#string/text_2c"
android:textSize="#dimen/text_size_1" />
</LinearLayout>
</ScrollView>
strings.xml
<resources>
<string name="text_button_1">check answers</string>
<string name="app_name">Quiz Test</string>
<string name="text_person_name">Type student name here.</string>
<string name="text_directions">Select ALL correct answers:</string>
<string name="text_1">1) probability distribution</string>
<string name="text_1a">1a) A smooth curve indicating the frequency distribution for a discontinuous random variable.</string>
<string name="text_1b">1b) A discontinuous dot diagram showing the frequency distribution for a random variable.</string>
<string name="text_1c">1c) A smooth curve indicating the frequency distribution for a continuous random variable.</string>
<string name="text_2">2) normal distribution</string>
<string name="text_2a">2a) A smooth double-peak bell-shaped curve symmetrical about the mean.</string>
<string name="text_2b">2b) A smooth single-peak curve </string>
<string name="text_2c">3c) A bell-shaped curve symmetrical about the mean. </string>
</resources>
I updated the XML to provide the ability to mark a red X in front of the wrong answers:
file: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:fillViewport="false"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="#dimen/dimension_1"
android:orientation="vertical">
<EditText
android:id="#+id/name_textView_STUDENT"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/text_person_name"
android:inputType="textPersonName" />
<TextView
android:id="#+id/textView_directions"
style="#style/HeaderTextStyle"
android:layout_marginTop="#dimen/dimension_1"
android:text="#string/text_directions"
android:textSize="20sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/dimension_1"
android:orientation="horizontal">
<TextView
android:id="#+id/incorrect_question_1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/dimension_1"
android:gravity="center"
android:text="X"
android:textColor="#ff0000"
android:textSize="30dp"
android:visibility="gone" />
<TextView
android:id="#+id/textView_1"
style="#style/HeaderTextStyle"
android:layout_marginTop="#dimen/dimension_1"
android:text="#string/text_1" />
</LinearLayout>
<RadioGroup
android:id="#+id/radioGroup_1"
style="#style/HeaderTextStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/radioButton_1a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimension_1"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:textSize="#dimen/text_size_1"
android:text="#string/text_1a"
android:onClick="onClick_1a"/>
<RadioButton
android:id="#+id/radioButton_1b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimension_1"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:text="#string/text_1b"
android:textSize="#dimen/text_size_1"
android:onClick="onClick_2a"/>/>
<RadioButton
android:id="#+id/radioButton_1c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimension_1"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:text="#string/text_1c"
android:textSize="#dimen/text_size_1"
android:onClick="onClick_3a"/>
</RadioGroup>
And developed the Java grading logic for the radio groups and checkboxes:
file: MainActivity.java
package com.example.android.quiztest2;
/**
* *Below added my unique package name "com.example.android.justjava4"
*/
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;
/**
* package com.example.android.justjava4;
* This app displays an order form to order coffee, and displays the information.
* quantity is a global variable
**/
public class MainActivity extends AppCompatActivity {
private RadioButton radioButton_1a, radioButton_1b, radioButton_1c, radioButton_4a, radioButton_4b, radioButton_4c,
radioButton_5a, radioButton_5b, radioButton_5c, radioButton_6a, RadioButton_6b, radioButton_6c,
radioButton_7a, radioButton_7b, radioButton_7c, radioButton_9a, radioButton_9b, radioButton_9c;
private CheckBox checkBox_2a, checkBox_2b, checkBox_2c, checkBox_3a, checkBox_3b, checkBox_3c, checkBox_8a, checkBox_8b, checkBox_8c;
int grade = 0;
public void Score(int grade) {
if (radioButton_1c.isChecked()) grade++;
if (radioButton_4c.isChecked()) grade++;
if (radioButton_5c.isChecked()) grade++;
if (radioButton_6c.isChecked()) grade++;
if (radioButton_7c.isChecked()) grade++;
if (radioButton_9c.isChecked()) grade++;
if (checkBox_2a.isChecked() && !checkBox_2b.isChecked() && checkBox_2c.isChecked()) grade++;
if (checkBox_3a.isChecked() && checkBox_3b.isChecked() && checkBox_3c.isChecked()) grade++;
if (checkBox_8a.isChecked() && !checkBox_8b.isChecked() && checkBox_8c.isChecked()) grade++;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.example.android.quiztest2.R.layout.activity_main);
final Context currentContext = this;
Button button_grade_quiz = (Button)
findViewById(R.id.button_grade_quiz);
button_grade_quiz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean answerCorrect1 = false;
TextView incorrectQuestionOne = (TextView) findViewById(R.id.incorrect_question_1);
if (!answerCorrect1) {
incorrectQuestionOne.setVisibility(View.VISIBLE);
} else {
incorrectQuestionOne.setVisibility(View.GONE);
}
}
});
}
}
Not sure how to connect the grading function to the other java methods.
Simple Answer: Add a button to your xml, and assign it an id. For example, the xml would most likely look something like this:
<Button
android:id="#+id/quiz_complete_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Finish Quiz"
android:textSize="#dimen/text_size_1"
android:layout_gravity="center"/>
Then, in your MainActivity AFTER setContentView is called, you will find your button view by its id, and set an onClickListener to it. My sample code below includes a rough test that will show a Toast message when the button is clicked so that you can see the button is hooked up correctly to the listener.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Context currentContext = this;
Button quizAnsweredButton = (Button) findViewById(R.id.quiz_complete_button);
quizAnsweredButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
Toast.makeText(currentContext, "TESTING", Toast.LENGTH_LONG).show();
}
});
}
(Note - to clarify, the bold above is to indicate that you can only reference views once they are shown - which is what is done by setContentView above. If you try to call findViewById before setContentView, you will receive a crash.)
Here is where it gets more complicated.
Without writing the whole of the solution, what I would do in order to reach your goal is to add the entirety of what you would like the quiz to look like, if the user submits the quiz with all answers wrong, in xml. I have created the xml for question 1. (I've added a horizontal LinearLayout in order to preserve the rest of your xml, but for the complexity of your view, I would recommend using a RelativeLayout)
As you can see, the visibility of the incorrect label is set to "gone". This means the view will not be seen, but also will not take up space with the parent view. "invisible" would hide the view, but its space would still be filled.
Now, when the test is submitted, we will show the incorrect answer label. In your complete solution, of course, you will evaluate whether the answer is correct or not.
XML for question one label:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/question_1_incorrect_label"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textColor="#color/red"
android:gravity="center"
android:visibility="gone"/>
<TextView
android:id="#+id/label_text_view_1"
style="#style/HeaderTextStyle"
android:layout_marginTop="#dimen/dimension_1"
android:text="#string/text_1" />
</LinearLayout>
Updated MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Context currentContext = this;
Button quizAnsweredButton = (Button) findViewById(R.id.quiz_complete_button);
quizAnsweredButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean answer1Correct = false;
//TODO: Evaluate the actual value of answer1Correct boolean.
TextView questionOneIncorrectLabel = (TextView)findViewById(R.id.question_1_incorrect_label);
if (!answer1Correct) {
questionOneIncorrectLabel.setVisibility(View.VISIBLE);
}
else {
questionOneIncorrectLabel.setVisibility(View.GONE);
}
}
});
}
Note - in colors.xml, added:
<color name="red">#FF0000</color
The rest should just be some legwork to get it working, as well as the code within MainActivity to analyze whether or not each answer is correct.
Finally, a hint to simplify your correct answer message. You can create a string constant with a placeholder for a value to be added later. For example:
<string name="text_quiz_complete_answers">You answered %d question(s) correctly.</string>
When pulling this string value from the strings.xml file, you reference it like this:
String.format(getString(R.string.text_quiz_complete_answers), 5)
With 5 just being a placeholder. Instead there should be the numerical value you calculated.
For more info on formatting strings like this, I would reference this post: Are parameters in strings.xml possible?
Related
I'm still new to the Android and I want to add a CardView to the activity each time a button is clicked. The CardView has text on it and a background image. I already have the XML file that can add this, but because I want to be able to add more than one, I can't use <include.>. The first image is when the button is clicked once and the second is when the button is clicked 3 times. I already have the onClick for the TextView that says "Click To Add Block" and the XML for the CardView, but I can't make it so that you can add them and change the text in the TextView in each and every one of them. I also can't seem to find a way to programmatically add an onClick listener to the programmatically created CardView. Later down the line, I would also like to be able to delete the CardView from a click of a button too.
Here is the CardView XML file (Before it was inside a Relative Layout)
<androidx.cardview.widget.CardView
android:id="#+id/cardviewClassesBlock1"
android:layout_width="330dp"
android:layout_height="75dp"
android:layout_marginTop="90dp"
android:layout_centerHorizontal="true"
app:cardCornerRadius="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_launcher_background">
<TextView
android:id="#+id/textviewClassesBlock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="3dp"
android:textSize="22sp"
android:fontFamily="#font/amiko_semibold"
android:textColor="#color/white"
android:text="Block A"/>
<ImageView
android:layout_width="60dp"
android:layout_height="6dp"
android:layout_marginStart="10dp"
android:layout_below="#+id/textviewClassesBlock1"
android:background="#drawable/rounded_corner_edittext" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="5dp"
android:textColor="#color/white"
android:text="P - 0 | T - 0 | A - 0"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
I have created a sample project for You.
First You have to create a layout for Your CardView. In res/layout create card_base.xml. In this layout add:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardviewClassesBlock1"
android:layout_width="wrap_content"
android:layout_height="75dp"
android:layout_centerHorizontal="true"
app:cardCornerRadius="10dp"
android:layout_margin="10dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_launcher_background"
>
<TextView
android:id="#+id/textviewClassesBlock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="3dp"
android:text="Block A"
android:textSize="22sp"
/>
<ImageView
android:layout_width="60dp"
android:layout_height="6dp"
android:layout_below="#+id/textviewClassesBlock1"
android:layout_marginStart="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="5dp"
android:text="P - 0 | T - 0 | A - 0"
/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
This is basically Your CardView with small changes.
Next, in Your activity_main.xml add this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
>
<Button
android:id="#+id/butAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add New Card"
/>
<Button
android:id="#+id/butDoSth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Do something"
/>
<androidx.appcompat.widget.LinearLayoutCompat
android:id="#+id/cards"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<include
android:id="#+id/includedLayoutFirst"
layout="#layout/card_base"
/>
</androidx.appcompat.widget.LinearLayoutCompat>
</androidx.appcompat.widget.LinearLayoutCompat>
This is a starter (very simple) look of Your app. It has one button and one CardView which is already inserted.
Now in Your MainActivity.java paste this:
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.cardview.widget.CardView;
public class MainActivity extends AppCompatActivity
{
private int starter = 66; //ASCII code for `B`
LinearLayoutCompat cards;
Button buttonAdd;
Button buttonDoSth;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cards = findViewById(R.id.cards);
buttonAdd = findViewById(R.id.butAdd);
buttonDoSth = findViewById(R.id.butDoSth);
buttonAdd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
CardView newCard = new CardView(MainActivity.this);
getLayoutInflater().inflate(R.layout.card_base, newCard);
TextView t = newCard.findViewById(R.id.textviewClassesBlock1);
String current = Character.toString((char) starter++);
t.setText("Block " + current);
newCard.setTag(current); //
cards.addView(newCard);
}
});
buttonDoSth.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
findBlockAndDoSomething("B");
}
});
}
private void findBlockAndDoSomething(String name)
{
Log.d("MyTAG", "CLICK");
for (int i = 0; i < cards.getChildCount(); i++)
{
CardView selected = (CardView) cards.getChildAt(i);
if (selected.getTag() != null && selected.getTag().toString().equals(name))
{
// do something. E.g change block name
TextView textViewClassesBlock1 = selected.findViewById(R.id.textviewClassesBlock1);
textViewClassesBlock1.setText("Block XXX");
return;
}
}
}
}
Result (starter code and with adding new CardView):
I know this question has been asked several times, and with different solutions, but I have tried all I could find here, and none worked. As the title suggest, in Android Studio, my EditText widget's field isn't showing any type of text, even what it has by default (like the hint and default text). The text is there if I print it out , but not displaying. It is for a simple login page.
This is the xml file :
<?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">
<TextView
android:text="Name : "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="30dp"
android:layout_marginTop="40dp"
android:id="#+id/atcoNameTag" />
<TextView
android:text="Password : "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/atcoNameTag"
android:layout_marginTop="30dp"
android:id="#+id/passTag"
android:layout_alignStart="#+id/atcoNameTag"/>
<TextView
android:text="Role : "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:id="#+id/roleNameTag"
android:layout_below="#+id/passTag"
android:layout_alignStart="#+id/atcoNameTag"/>
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10"
android:layout_above="#+id/passTag"
android:layout_centerHorizontal="true"
android:id="#+id/insertName"
android:layout_alignTop="#+id/atcoNameTag"
android:layout_toEndOf="#+id/atcoNameTag"
android:layout_alignStart="#+id/insertPass"
android:hint="username"
android:cursorVisible="true"/>
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:layout_alignBottom="#+id/passTag"
android:layout_toEndOf="#+id/passTag"
android:id="#+id/insertPass"
android:layout_alignTop="#+id/passTag"
android:hint="password"
android:cursorVisible="true"/>
<Spinner
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:layout_alignTop="#+id/roleNameTag"
android:layout_toEndOf="#+id/roleNameTag"
android:layout_alignStart="#+id/insertPass"/>
<Button
android:text="Login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/loginButton"
android:onClick="onClick"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="35dp" />
</RelativeLayout>
And this is the java file :
package mecals.mecalsapp;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_page);
Button nameBtn = (Button) findViewById(R.id.loginButton);
nameBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText nameEntry = (EditText) findViewById(R.id.insertName);
nameEntry.setTextColor(Color.BLACK);
String name = nameEntry.getText().toString();
//TODO username checking, username not showing , need devC Team's work
if (name.length() > 0) {
Toast toastYes = Toast.makeText(getApplicationContext(), "Hi there, " + name + "!", Toast.LENGTH_SHORT);
toastYes.show();
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(intent);
} else {
Toast toastNo = Toast.makeText(getApplicationContext(), "Please insert name !", Toast.LENGTH_SHORT);
toastNo.show();
}
EditText passwordEntry = (EditText) findViewById(R.id.insertPass);
passwordEntry.setTextColor(Color.BLACK);
String pass = passwordEntry.getText().toString();
//TODO password checking , need devC Team's work
}
});
}
}
And these are the solutions I have tried , to no avail :
Difference between content_main.xml and activity_main.xml?
Android edittext typed text not showing
Android EditText typed value not showing
Text not displayed in Android editText when changing android:hint to android:text
EditText in Android doesn't show text when typing while using the on-screen keyboard
Edit Text hints not appearing on later version SDK
edittext not showing the typed text in android
In short, I have
-set the text colour to Black , with nameEntry.setTextColor(Color.BLACK);
-I have added android:windowSoftInputMode="adjustPan" in the manifest
-I have NOT used something like android:gravity , just android:layout
-the cursor is set to visible
-I even checked the height of the widget
-I checked the size of the text with android:ems to be 10
-and the input type is set to text for the first field and textPassword for the second
Help !
PS : before anyone asks , my Android Studio version is 2.2.3 , and the API I am using is min 21.
The problem is that the height of the EditText field is much to small to display the text. This is present because both the top and the bottom of the EditText field are set according to the TextView left of the EditText. But since the height of the TextView is smaller than the normal height of the EditText you force it to be very narrow (and so there is not enough space for the Text). If you remove this line
android:layout_alignTop="#+id/atcoNameTag"
you can see that the text gets displayed normally.
There are actually several ways to fix this:
you could increase the text size of the TextViews
you could add enough padding on top and on the bottom of the TextViews
you could decrease the text size of the EditText
you could decouple the height of the EditText from the TextView
It is probably a good idea to go with the last solution and put the Textview and EditText fields that belong together into a separate LinearLayout and remove the align calls like this:
<?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">
<LinearLayout
android:id="#+id/first"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginStart="30dp"
android:layout_marginTop="40dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:weightSum="100"
>
<TextView
android:layout_weight="30"
android:text="Name : "
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/atcoNameTag" />
<EditText
android:layout_weight="60"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="text"
android:id="#+id/insertName"
android:hint="username"
android:cursorVisible="true"/>
</LinearLayout>
<LinearLayout
android:id="#+id/second"
android:layout_below="#+id/first"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginStart="30dp"
android:weightSum="100"
>
<TextView
android:layout_weight="30"
android:text="Password : "
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/passTag"/>
<EditText
android:layout_weight="60"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:id="#+id/insertPass"
android:hint="password"
android:cursorVisible="true"/>
</LinearLayout>
<LinearLayout
android:layout_below="#+id/second"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginStart="30dp"
android:weightSum="100"
android:layout_marginTop="10dp"
>
<TextView
android:layout_weight="30"
android:text="Role : "
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/roleNameTag"/>
<Spinner
android:layout_weight="60"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/spinner"/>
</LinearLayout>
<Button
android:text="Login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/loginButton"
android:onClick="onClick"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="35dp" />
</RelativeLayout>
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)
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).
okay, i cannot post images yet :/
Basically, i have an application with three edittext fields, three check boxes, a calculation button and a text field to output the answer. i want the program to scan to see which value is missing, so that from this it know which calculation it should do. Another method would be for the user to check one of the checkbox's and then the program would only run the calculation for the corresponding checkbox.
for instance, if the user inputs Q = 10, T = 2, and checks the checkbox for I, the program would then do the math and display I = 20 ?
this make much sense yet
i spose in psuedo code it would look like
" if checkbox one is checked and values for Q and T have been entered, then calculate value for I and display in answers field" however i will be adding some error checks and validation methods in there.
if you need the xml file and java file then please ask, im just looking for a method at the moment as to how i could do it, i wouldnt expect you all to waste your free time writing a whole program for me.
cheers guys and girls
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background1"
android:gravity="fill"
android:orientation="vertical"
android:textColor="#ffffff"
tools:context=".CurrentPage" >
<!--
The primary full-screen view. This can be replaced with whatever view
is needed to present your content, e.g. VideoView, SurfaceView,
TextureView, etc.
-->
<!--
This FrameLayout insets its children based on system windows using
android:fitsSystemWindows.
-->
<TextView
android:id="#+id/Current_hint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:layout_marginTop="33dp"
android:text="Welcome to the Current Calculation page."Hint - Use the check boxes to find the values that are missing "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ffffff"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/Equation_letter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/current_calculate"
android:layout_marginTop="37dp"
android:layout_toLeftOf="#+id/current_calculate"
android:text=" HELLO "
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/Distances_answer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/Equation_letter"
android:layout_alignBottom="#+id/Equation_letter"
android:layout_alignLeft="#+id/current_calculate"
android:layout_alignParentRight="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff" />
<TextView
android:id="#+id/t"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Q"
android:layout_alignRight="#+id/Q"
android:layout_below="#+id/Q"
android:layout_marginTop="36dp"
android:gravity="right|top"
android:text="t ="
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff"
tools:ignore="HardcodedText" />
<CheckBox
android:id="#+id/custom3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/t"
android:layout_alignLeft="#+id/custom2"
android:background="#drawable/check_box_new"
android:button="#drawable/check_box_new" />
<CheckBox
android:id="#+id/custom1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/number_input_3"
android:layout_alignLeft="#+id/custom3"
android:background="#drawable/check_box_new"
android:button="#drawable/check_box_new" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Current_hint"
android:layout_alignRight="#+id/Current_hint"
android:layout_below="#+id/Equation_letter"
android:layout_marginTop="25dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/CurrentmainHelp"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1.31"
android:text="HELP! This equation can be used to calculate the current of an object in amps. The correct equation to discover amps is I=Q/t. Where I = current, Q = charge flowing past a point in the circuit, and t = time taken for the charge to flow. Please note, Q is measure in coulombs and t is measured in seconds, with I being measured in amperes.
Still need more help? "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="18sp"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/Yes_Please"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="36dp"
android:layout_weight="1.31"
android:onClick="CurrentHelp"
android:text="Yes Please"
android:textColor="#ffffff" />
</LinearLayout>
</ScrollView>
<Button
android:id="#+id/current_calculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/Calculate_Current"
android:textColor="#ffffff"
/>
<EditText
android:id="#+id/number_input_2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_above="#+id/t"
android:layout_alignLeft="#+id/number_input_1"
android:layout_alignRight="#+id/number_input_1"
android:ems="10"
android:focusable="true"
android:inputType="numberDecimal"
android:textColor="#ffffff" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/number_input_3"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/t"
android:layout_alignLeft="#+id/number_input_2"
android:layout_alignRight="#+id/number_input_2"
android:ems="10"
android:focusable="true"
android:inputType="numberDecimal"
android:textColor="#ffffff" />
<CheckBox
android:id="#+id/custom2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/number_input_1"
android:layout_marginLeft="45dp"
android:layout_toRightOf="#+id/number_input_1"
android:background="#drawable/check_box_new"
android:button="#drawable/check_box_new" />
<EditText
android:id="#+id/number_input_1"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_above="#+id/Q"
android:layout_alignRight="#+id/current_calculate"
android:ems="10"
android:focusable="false"
android:inputType="numberDecimal"
android:singleLine="true"
android:textColor="#ffffff" />
<TextView
android:id="#+id/Q"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Equation_letter"
android:layout_below="#+id/I"
android:layout_marginTop="36dp"
android:gravity="right|top"
android:text="Q ="
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/I"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Q"
android:layout_alignRight="#+id/Q"
android:layout_below="#+id/Current_hint"
android:layout_marginTop="65dp"
android:gravity="right|top"
android:text="I ="
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff"
tools:ignore="HardcodedText" />
okay, that was the xml, and this is the java so far
package com.kieran.whetherfieldphysicscalculator;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
// i=q/t this will be the first calculation on the list
public class Current extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current);
// Show the Up button in the action bar.
setupActionBar();
Button calc1 = (Button)findViewById(R.id.current_calculate);
calc1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText Charge1 = (EditText)findViewById(R.id.number_input_2);
EditText Time1 = (EditText)findViewById(R.id.number_input_3);
TextView Distances_answer = (TextView)findViewById(R.id.Distances_answer);
double charge = Double.parseDouble(Charge1.getText().toString());
double time = Double.parseDouble(Time1.getText().toString());
//Time is a class in Java
Distances_answer.setText("" +charge*time);
}
});
}
public void CurrentHelp(View view) {
// Do something in response to button
Intent intent = new Intent(this, CurrentHelp.class);
startActivity(intent);
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am asking if there is an easier way to formate the program to find the values, rather than have to code each individual segment?
cheers
In your case I guess that you want the user to check only one checkbox and only answer corresponding to that checkbox should be displayed to the user.
so for that you would need to set OnClickListener on checkbox so that the corresponding operation is selected.
Read here on how to set listener on checkbox and use it. Paticularly look for the addListenerOnChkIos() method as it has the code you want.
Also set another OnClickListener on the calculate button and in that check which checkbox is checked depending on which you will perform the operation and update the textview.