Getting the string of a selected RadioButton in Android - android

Recently I decided to develop an app in Android. I have used this forum and other tools online to teach myself how to develop a simple app that asks the user for their name and answer few questions. My aim to allow the user to send the answers to any email of their choice. So far I have been able to achieve this:
From: ********#gmail.com
To: ********#gmail.com
Subject: Survey result for John Doe
Name: John Doe
Question 1: true
End of Survey.
My aim is to include in the email not the state of question 1 (i.e. "True") but instead I want to show the answer of their question. For Example, Question 1: B. 26-35.
I have searched online for the past couple of days but I have been having issues to find some help as I'm still new to programming. The closest thing I came across was this SO Question but it is not what I'm looking for. Any help or guidance would be highly appreciated.
MainActivity.java
package com.example.android.sampleupdrs;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
{
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView1);
}
public void emailResult (View view)
{
EditText nameField = (EditText) findViewById(R.id.name_field);
String name = nameField.getText().toString();
RadioGroup radioQ1 = (RadioGroup) findViewById(R.id.radio_Q1);
final RadioButton checkedRadioQ1 = (RadioButton) radioQ1.findViewById(radioQ1.getCheckedRadioButtonId());
boolean isCheckedRadioQ1 = checkedRadioQ1.isChecked();
radioQ1.setOnCheckedChangeListener (new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged (RadioGroup group, int checkedQ1Id)
{
RadioButton checkedRadioButton = (RadioButton)group.findViewById(checkedQ1Id);
boolean isCheckedRadioQ1 = checkedRadioQ1.isChecked();
if (isCheckedRadioQ1)
{
tv.setText("Checked: " +checkedRadioButton.getText());
}
}
});
String resultsEmail = createEmailSummary(name, isCheckedRadioQ1);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_SUBJECT, "Survery result for " + name);
intent.putExtra(Intent.EXTRA_TEXT, resultsEmail);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
private String createEmailSummary (String name, boolean isCheckedRadioQ1) {
String resultsEmail = "Name: " + name;
resultsEmail += "\nQuestion 1 " + isCheckedRadioQ1;
resultsEmail += "\nEnd of Survey";
return resultsEmail;
}
}
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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin">
<EditText
android:id="#+id/name_field"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="Name"
android:inputType="textCapWords"/>
<TextView
android:text="#string/q1string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/textView1"/>
<RadioGroup
android:id="#+id/radio_Q1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/q1b0_url"
android:text="#string/q1b0string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_alignParentStart="true"
android:layout_marginBottom="15dp" />
<RadioButton
android:id="#+id/q1b1_url"
android:text="#string/q1b1string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/q1b0_url"
android:layout_alignParentStart="true"
android:layout_marginBottom="15dp"
android:gravity="top" />
<RadioButton
android:id="#+id/q1b2_url"
android:text="#string/q1b2string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/q1b1_url"
android:layout_alignParentStart="true"
android:layout_marginBottom="15dp"
android:gravity="top" />
<RadioButton
android:id="#+id/q1b3_url"
android:text="#string/q1b3string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/q1b2_url"
android:layout_alignParentStart="true"
android:layout_marginBottom="15dp"
android:gravity="top" />
<RadioButton
android:id="#+id/q1b4_url"
android:text="#string/q1b4string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/q1b3_url"
android:layout_marginBottom="30dp"
android:gravity="start" />
</RadioGroup>
<TextView
android:text="#string/q2string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/textView2"/>
<RadioGroup
<Button
android:text="Next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/nextQ1"
android:onClick="emailResult"
android:layout_weight="1"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_gravity="right" />
</LinearLayout>
</ScrollView>
strings.xml
<resources>
<string name="app_name">Survey</string>
<string name="q1string">1. Select age group</string>
<string name="q1b0string">A. 18-25</string>
<string name="q1b1string">B. 26-35</string>
<string name="q1b2string">C. 36-45</string>
<string name="q1b3string">D. 46-59</string>
<string name="q1b4string">E. 60+</string>
</resources>

In MainActivity class,
you can get the text of the Radio button in this way:
boolean isCheckedRadioQ1 = checkedRadioQ1.isChecked();
text = "";
if (isCheckedRadioQ1) {
text = checkedRadioQ1.getText().toString();
tv.setText("Checked: " +checkedRadioButton.getText());
}
In method createEmailSummary do
resultsEmail += "\nQuestion 1 " + text;
instead of
resultsEmail += "\nQuestion 1 " + isCheckedRadioQ1
You'll have to send text as a parameter to createEmailSummary instead of isCheckedRadioQ1

If I understand correctly, what you need is checkedRadioButton.getText().toString() and not the boolean isCheckedRadioQ1.

Related

Android Initial Login Screen then use fragments to swipe between screens once login is successful

I am trying to create an Android app, then has an initial login screen that detects if a user is Admin or User. Once logged in, the user (depending on their role) will see different tabs to swipe between. I have a basic app that starts with a login activity and the login to decipher the users roles (using static values for now). First part is ok. Now when I try to use Fragments after the login screen, I'm getting stuck.
I have a LoginActivity that has an onClikcListener on a button after user enters credentials. Depending on whether the user is Amin or General Users, it will just to a new activity either activity_vote_admin or activity_vote_user. At this point I am stuck. Any ideas if what I am trying to do is valid. Or is there a better way to do this. At the moment I am getting this error.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.confidencevotefragmentrebuild/com.example.confidencevotefragmentrebuild.activity_vote_admin}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference.
LoginActivity (this is my main activity)
...
package com.example.confidencevotefragmentrebuild;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
private static EditText username;
private static EditText password;
public static TextView attempts;
private static Button submit_button;
int attempt_counter = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton();
}
public void loginButton() {
username = (EditText) findViewById(R.id.editText);
password = (EditText) findViewById(R.id.editText2);
attempts = (TextView) findViewById(R.id.textView_Attempts);
//Reference button view
final Button submit_button = findViewById(R.id.submit_button);
// perform click event on button
submit_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (username.getText().toString().equals("admin") &&
password.getText().toString().equals("pass")) {
Toast.makeText(LoginActivity.this, "Welcome " + username.getText(),
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginActivity.this, activity_vote_admin.class);
startActivity(intent);
} else if (username.getText().toString().equals("user") &&
password.getText().toString().equals("pass")) {
Toast.makeText(LoginActivity.this, "Welcome " + username.getText(),
Toast.LENGTH_SHORT).show();
Intent intentUser = new Intent(LoginActivity.this, activity_vote_user.class);
startActivity(intentUser);
} else {
Toast.makeText(LoginActivity.this, "User or Password incorrect",
Toast.LENGTH_SHORT).show();
attempt_counter--;
attempts.setText(Integer.toString(attempt_counter));
if (attempt_counter == 0) {
Toast.makeText(LoginActivity.this, "Too many failed attempts, please close app and try again",
Toast.LENGTH_SHORT).show();
submit_button.setEnabled(false);
}
}
}
}
);
}
}
...
Activity_vote_admin
...
package com.example.confidencevotefragmentrebuild;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
public class activity_vote_admin extends AppCompatActivity {
/**
* Field for selecting the number of confidence votes
*/
RatingBar mResults;
private RatingBar rBar;
Button mBtn;
/**
* Spinner field to enter the project name
*/
private Spinner mProjectSpinner;
/**
* Projects. The possible values are:
* stored locally - Needs to get values from a database. TODO
*/
int mProject = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vote_main_admin);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown on each page
AdminFragmentPagerAdapter adapter = new AdminFragmentPagerAdapter(getSupportFragmentManager());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
// initiate a rating bar
rBar = findViewById(R.id.rating_bar);
//float vote = rBar.getRating();
// Find all relevant views for user input
mResults = findViewById(R.id.rating_bar);
mProjectSpinner = findViewById(R.id.spinner_project);
// Run getRating method to get rating number from a rating bar
//getRating();
// Initiate button
mBtn = findViewById(R.id.voteButton);
// perform click event on button
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get values and then displayed in a toast
//String totalStars = "Total Stars:: " + RatingBar.getNumStars();
float vote = rBar.getRating();
String rating = "Rating : " + vote;
Toast.makeText(getApplicationContext(), rating + "\n", Toast.LENGTH_LONG).show();
}
});
projectSpinner();
}
// Setup the dropdown spinner that allows the user to select the role.
private void projectSpinner() {
// Create adapter for spinner. The list options are from the String array it will use
// the spinner will use the default layout
ArrayAdapter projectSpinnerAdapter = ArrayAdapter.createFromResource(this,
R.array.projects, android.R.layout.simple_spinner_item);
// Specify dropdown layout style - simple list view with 1 item per line
projectSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
// Apply the adapter to the project spinner
mProjectSpinner.setAdapter(projectSpinnerAdapter);
// Set the integer mSelected to the constant values
mProjectSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if(mProjectSpinner.getSelectedItem() == "This is Hint Text");
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.nextGEMS1_5))) {
mProject = 0 ;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_6))) {
mProject = 1;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_7))) {
mProject = 2;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_8))) {
mProject = 3;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_9))) {
mProject = 4;
return;
}
else mProject = 0;
}
}
// Because AdapterView is an abstract class, onNothingSelected must be defined
#Override
public void onNothingSelected(AdapterView<?> parent) {
mProject = 0; // User
}
});
}
}
...
activity_vote_main_admin.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:layout_height="match_parent"
android:orientation="vertical">
<androidx.viewpager.widget.ViewPager
android:name="com.example.confidencevotefragmentrebuild.testFragment1"
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
...
activity_login.xml
...
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".LoginActivity"
tools:showIn="#layout/activity_login">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#5fb0c9"
android:orientation="vertical"
android:scrollbarAlwaysDrawVerticalTrack="true">
<TextView
android:id="#+id/login_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:gravity="center_horizontal"
android:text="LOGIN"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="500dp"
android:background="#ffffff"
android:elevation="4dp"
android:orientation="vertical"
android:padding="20dp"
android:layout_below="#+id/login_title"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="80dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="450dp"
android:orientation="vertical"
android:paddingTop="30dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp">
<EditText
android:id="#+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:drawableLeft="#drawable/usericon"
android:hint="User Name"
android:inputType="textEmailAddress"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/editText2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:drawableLeft="#drawable/lock"
android:hint="Password"
android:inputType="textPassword"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:paddingTop="5dp"
android:text="Forgot Password?" />
<Button
android:id="#+id/submit_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="22dp"
android:background="#drawable/action_buttom"
android:text="Sign in"
android:textAllCaps="false"
android:textColor="#fff"
android:textSize="18sp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="20dp"
android:orientation="horizontal"
android:paddingTop="1dp">
<TextView
android:id="#+id/attempts_text"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:layout_gravity="center_horizontal"
android:paddingTop="1dp"
android:text="Number of attempts remaining: " />
<TextView
android:id="#+id/textView_Attempts"
android:layout_width="match_parent"
android:layout_height="25dp"
android:layout_gravity="center_horizontal"
android:paddingTop="1dp"
android:text="5" />
</LinearLayout>
<TextView
android:id="#+id/lnkRegister"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:gravity="center"
android:paddingTop="30dp"
android:text="Register here"
android:textColor="#5fb0c9"
android:textSize="16sp" />
</LinearLayout>
</RelativeLayout>
<ImageButton
android:id="#+id/conferencevote_logo"
android:layout_width="210dp"
android:layout_height="180dp"
android:layout_below="#+id/login_title"
android:layout_centerHorizontal="true"
android:layout_marginTop="2dp"
android:elevation="4dp"
android:background="#drawable/rounded_button"
android:src="#drawable/confvotenew"
/>
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
...
AdminFragemntyPagerAdapter
...
package com.example.confidencevotefragmentrebuild;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class AdminFragmentPagerAdapter extends FragmentPagerAdapter {
public AdminFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new testFragment1();
} else if (position == 1) {
return new testFragment2();
} else {
return new testFragment2();
}
}
#Override
public int getCount() {
return 3;
}
}
...
aactivity_vote_user.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#5fb0c9"
android:orientation="vertical"
android:scrollbarAlwaysDrawVerticalTrack="true">
<TextView
android:id="#+id/vote_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:gravity="center_horizontal"
android:text="USER VOTE"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="500dp"
android:background="#ffffff"
android:elevation="4dp"
android:orientation="vertical"
android:padding="20dp"
android:layout_below="#+id/vote_title"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="80dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="450dp"
android:orientation="vertical"
android:paddingTop="70dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<Spinner
android:id="#+id/spinner_project"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:hint="#string/spinner_hint"
android:maxLines="1"
android:singleLine="true"
android:backgroundTint="#color/attCobalt"
android:popupBackground="#color/myBlue"
android:dropDownSelector="#color/attBlue"
/>
</com.google.android.material.textfield.TextInputLayout
>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<RatingBar
android:id="#+id/rating_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stepSize="1.0"
android:layout_marginTop="40dp"
android:theme="#style/rating_bar"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingTop="5dp"
android:text="Vote and Submit" />
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/voteButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="22dp"
android:background="#drawable/action_buttom"
android:text="Submit"
android:textAllCaps="false"
android:textColor="#fff"
android:textSize="18sp" />
/>
</LinearLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
<ImageButton
android:id="#+id/conferencevote_logo"
android:layout_width="210dp"
android:layout_height="180dp"
android:layout_below="#+id/login_title"
android:layout_centerHorizontal="true"
android:layout_marginTop="55dp"
android:elevation="4dp"
android:background="#drawable/rounded_button"
android:src="#drawable/confvotenew"
/>
</RelativeLayout>
...
My fragments are as follows.
...
package com.example.confidencevotefragmentrebuild;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
public class testFragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_vote_user, container, false);
}
}
...
There are two reason for this issue :
You didn't declare any button on "activity_vote_main_admin.xml", thats why your view not binding with activity and giving null pointer exception.
May be you declare the button on fragment xml and trying to bind it with activity.

Can't make calculations using a mix of TextView and EditText

I'm currently making a very simple math game. In this math game I want the player to solve easy equations. It looks like this: 9 * __ = 45, the player then fill in the correct number to solve the equation and then presses a Correct-button. If correct scores are added to the player.
The empty space is an EditText and the others are TextViews. Because I use a mix of TextView & EditText I need somehow to make a convertion for the program to be able to read and calculate. I've been reading like crazy and tried all kinds of different methods without success. How should I do to get around this?
This is how my data looks like:
activity_play.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_play"
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.android.laboration2.PlayActivity">
<TextView
android:id="#+id/textPlayMultiply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textPlayNumber1"
android:layout_centerHorizontal="true"
android:text="#string/multiply"
android:textAlignment="textStart"
android:layout_gravity = "start"
android:textColor="#android:color/black"
android:textSize="40sp" />
<TextView
android:id="#+id/textPlayNumber1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/textPlayScore"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/textPlayScore"
android:layout_marginTop="48dp"
android:text="#string/number_1"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp" />
<TextView
android:id="#+id/textPlayEqual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/equal"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp"
android:layout_below="#+id/editTextPlayNumber2"
android:layout_alignLeft="#+id/textPlayMultiply"
android:layout_alignStart="#+id/textPlayMultiply" />
<TextView
android:id="#+id/textPlayResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="29dp"
android:text="#string/result_number3"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp"
android:layout_below="#+id/textPlayEqual"
android:layout_alignLeft="#+id/textPlayEqual"
android:layout_alignStart="#+id/textPlayEqual" />
<TextView
android:id="#+id/textPlayScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="31dp"
android:layout_toStartOf="#+id/answerButton"
android:text="#string/score_0"
android:textAlignment="textStart"
android:layout_gravity="start"
android:textColor="#android:color/black"
android:textSize="24sp"
android:layout_toLeftOf="#+id/answerButton" />
<Button
android:id="#+id/answerButton"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginTop="36dp"
android:background="#android:color/holo_orange_dark"
android:text="#string/button_result"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="18sp"
android:textStyle="bold"
android:layout_below="#+id/textPlayResult"
android:layout_centerHorizontal="true" />
<EditText
android:id="#+id/editTextPlayNumber2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textPlayMultiply"
android:layout_alignBottom="#+id/textPlayMultiply"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_toEndOf="#+id/answerButton"
android:layout_toRightOf="#+id/answerButton"
android:hint=" "
android:inputType="number"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp" />
<TextView
android:id="#+id/textPlayLevel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textPlayScore"
android:layout_alignBottom="#+id/textPlayScore"
android:layout_toEndOf="#+id/answerButton"
android:layout_toRightOf="#+id/answerButton"
android:text="#string/level_0"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="24sp" />
</RelativeLayout>
.
PlayActivity.java
package com.example.android.laboration2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class PlayActivity extends AppCompatActivity implements View.OnClickListener {
TextView textPlayNumber1;
EditText editTextPlayNumber2;
TextView textPlayResult;
TextView textPlayScore;
TextView textPlayLevel;
Button answerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
textPlayNumber1 = (TextView) findViewById(R.id.textPlayNumber1);
editTextPlayNumber2 = (EditText) findViewById(R.id.editTextPlayNumber2);
textPlayResult = (TextView) findViewById(R.id.textPlayResult);
textPlayScore = (TextView) findViewById(R.id.textPlayScore);
textPlayLevel = (TextView) findViewById(R.id.textPlayLevel);
answerButton = (Button) findViewById(R.id.answerButton);
answerButton.setOnClickListener(this);
}//onCreate ends here
#Override
public void onClick(View v) {
}//onClick ends here
}//PlayActivity ends here
You can do
int playNumberValue = Integer.getInteger(textPlayNumber1.getText().toString());
int userInputValue = Integer.getInteger(editTextPlayNumber2.getText().toString());
int result = Integer.getInteger(textPlayResult.getText().toString());
if(result == userInputValue+playNumberValue)
//win game
Your TextView and EditText all have String type values. You have to parse those value to Integer then calculate and show the result.
Here is the action onClick answer button-
int score = 0;
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.answerButton:
int playNum1 = Integer.parseInt(textPlayNumber1.getText().toString());
int playNum2 = Integer.parseInt(editTextPlayNumber2.getText().toString());
int playResult = Integer.parseInt(textPlayResult.getText().toString());
if(playNum1*playNum2 == playResult){
score++;
textPlayScore.setText(""+score);
}
break;
}
}
Hope this helps.

My Intent activity

I want to send two textview by intents. I am sending intents but I am not getting the desired result. I get two $12.99 as my output. Why doesn't it show the pizza name? Please help. I want to get my pizza name and then price in one line on my app. Here is my code:
XML
<TextView android:id="#+id/pizza1"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Mr. Meat Lover Pizza"
android:textSize="25dp"
android:textColor="#2c2349" />
<TextView android:id="#+id/price1"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:background="#drawable/rectangle"
android:text="$12.99+"
android:textColor="#2c2349"
android:layout_alignParentEnd="true"
android:paddingStart="15dp"
android:textSize="25dp" />
<Button android:id="#+id/ckeckout1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:background="#drawable/rectangle"
android:text="Add to Cart"
android:layout_marginTop="5dp"
android:layout_below="#+id/price1"
android:textColor="#2c2349"
android:backgroundTint="#ff00"
android:layout_alignParentEnd="true"
android:textSize="15dp" />
<LinearLayout android:id="#+id/layout4"
android:layout_below="#+id/layout3"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:id="#+id/textview1"
android:textSize="20dp"
android:layout_width="230dp"
android:layout_height="wrap_content" />
<TextView android:id="#+id/textview2"
android:textSize="20dp"
android:layout_width="130dp"
android:layout_height="wrap_content" />
</LinearLayout>
JAVA
TextView1 = (TextView) findViewById(R.id.pizza1);
TextView2 = (TextView) findViewById(R.id.price1);
My get intent is:
Intent intent1 = new Intent(SplPizzas.this, Cart.class);
String message1 = TextView1.getText().toString();
intent1.putExtra(Message1, message1);
String message2 = TextView2.getText().toString();
intent1.putExtra(Message2, message2);
startActivity(intent1);
break;
Activity 2
Intent intent = getIntent();
String message1 = intent.getStringExtra(SplPizzas.Message1);
String message2 = intent.getStringExtra(SplPizzas.Message2);
TextView output1 = (TextView) findViewById(R.id.textview1);
output1.setText(message1);
TextView output2 = (TextView) findViewById(R.id.textview2);
output2.setText(message2);
#ferrari The way you wrote the code is bit terrible :P
I formatted it a bit and it runs on my end.
As much I am able to guess I think you have mistakenly assigned same "String" to your SplPizzas.Message1 and SplPizzas.Message2.
Thats why you are getting same value i.e. $12.99 in both cases.
Please verify.
Here is the code:
MainActivity.java --> SplPizzas.java from your code
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public static String MESSAGE1 = "msg1";
public static String MESSAGE2 = "msg2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startNextActivity(View view){
TextView TextView1 = (TextView) findViewById(R.id.pizza1);
TextView TextView2 = (TextView) findViewById(R.id.price1);
Intent intent1 = new Intent(MainActivity.this, Main2Activity.class);
String message1 = TextView1.getText().toString();
intent1.putExtra(MESSAGE1, message1);
String message2 = TextView2.getText().toString();
intent1.putExtra(MESSAGE2, message2);
startActivity(intent1);
}
}
Main2Activity.java --> Cart.java from your code
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
String message1 = intent.getStringExtra(MainActivity.MESSAGE1);
String message2 = intent.getStringExtra(MainActivity.MESSAGE2);
TextView output1 = (TextView) findViewById(R.id.textview1);
output1.setText(message1);
TextView output2 = (TextView) findViewById(R.id.textview2);
output2.setText(message2);
}
}
activity_main.xml --> First screen of your code
<?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="in.proged.mytempapp2.MainActivity">
<TextView
android:id="#+id/pizza1"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Mr. Meat Lover Pizza"
android:textSize="25dp"
android:textColor="#2c2349"/>
<TextView
android:id="#+id/price1"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="$12.99+"
android:textColor="#2c2349"
android:layout_alignParentEnd="true"
android:paddingStart="15dp"
android:textSize="25dp"/>
<Button
android:id="#+id/ckeckout1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Add to Cart"
android:layout_marginTop="5dp"
android:layout_below="#+id/price1"
android:textColor="#2c2349"
android:backgroundTint="#ff00"
android:layout_alignParentEnd="true"
android:textSize="15dp"
android:onClick="startNextActivity"/>
</RelativeLayout>
activity_main2.xml --> Second screen of your code
<?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_main2"
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="in.proged.mytempapp2.Main2Activity">
<LinearLayout
android:id="#+id/layout4"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textview1"
android:textSize="20dp"
android:layout_width="230dp"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/textview2"
android:textSize="20dp"
android:layout_width="130dp"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>

Why text in button Register and Login so large?

This is my XML file. All text in button is large.
I used android:textAllCaps="false", but no result.In what may be a problem?
All literals are declared in the strings.xml.
Nowhere isn't even talk of the big letters. I think problem in invested LinearLayout.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/black_color"
android:gravity="center_vertical"
android:orientation="vertical"
android:weightSum="1">
<ImageView
android:id="#+id/imageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center_horizontal"
android:layout_weight="0.3"
android:src="#drawable/ico_start" />
<EditText
android:id="#+id/feeld_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:hint="#string/login"
android:phoneNumber="false" />
<EditText
android:id="#+id/feeld_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:hint="#string/password"
android:inputType="textPassword" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.6"
android:gravity="bottom"
android:padding="10dp">
<Button
android:id="#+id/button_register"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="#string/register"
android:textSize="17dp" />
<Button
android:id="#+id/button_login"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:nestedScrollingEnabled="true"
android:text="#string/login"
android:textSize="17dp" />
</LinearLayout>
</LinearLayout>
</ScrollView>
<resources>
<string name="app_name">Lesson 6. Registration Form</string>
<string name="register">Register</string>
<string name="login">Login</string>
<string name="password">Password</string>
package com.egoriku.lesson6registrationform;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private final String login = "egorikftp";
private final String password = "androidN";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView mainImage = (ImageView) findViewById(R.id.imageView);
final EditText loginText = (EditText) findViewById(R.id.feeld_login);
final EditText passwordText = (EditText) findViewById(R.id.feeld_password);
Button buttonRegister = (Button) findViewById(R.id.button_register);
Button buttonLogin = (Button) findViewById(R.id.button_login);
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (loginText.getText().length() == 0) {
loginText.setError("Введите логин");
mainImage.setImageResource(R.drawable.ico_error);
}
if (passwordText.getText().length() == 0) {
passwordText.setError("Введите пароль");
mainImage.setImageResource(R.drawable.ico_error);
} else if (loginText.getText().toString().equals(login) && passwordText.getText().toString().equals(password)) {
Toast.makeText(getApplicationContext(), "Вы успешно вошли в систему!", Toast.LENGTH_LONG).show();
loginText.setText(null);
passwordText.setText(null);
mainImage.setImageResource(R.drawable.ico_ok);
} else {
Toast.makeText(getApplicationContext(), "Логин/Пароль введен неверно!", Toast.LENGTH_SHORT).show();
mainImage.setImageResource(R.drawable.ico_error);
loginText.setText(null);
passwordText.setText(null);
}
}
});
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (loginText.getText().length() == 0) {
loginText.setError("Введите логин");
mainImage.setImageResource(R.drawable.ico_error);
}
if (passwordText.getText().length() == 0) {
passwordText.setError("Введите пароль");
mainImage.setImageResource(R.drawable.ico_error);
} else {
//login = loginText.getText().toString();
//password = passwordText.getText().toString();
Toast.makeText(getApplicationContext(), "Вы успешно зарегистрированы! ", Toast.LENGTH_LONG).show();
loginText.setText(null);
passwordText.setText(null);
mainImage.setImageResource(R.drawable.ico_ok);
}
}
});
}
}
Screen of my program. Thanks.
The simplest method is to simply add this line inside your Button tag in xml
android:textAppearance="?android:attr/textAppearanceLarge"
Adding this line will show the text of your Button as you want whether capital or small depending upon the text in
android:text=" .... "
and change text size which fits perfectly
Button's widget in Android uses this style by default:
<item name="textAppearanceButton">#android:style/TextAppearance.Widget.Button</item>
Which enable by default the textAllCaps to true. As you can see in values/styles_base_text.xml of AppCompat theme, it could refer to the same style:
<style name="Base.TextAppearance.AppCompat.Button">
<item name="android:textSize">#dimen/abc_text_size_button_material</item>
<item name="textAllCaps">true</item>
<item name="android:textColor">?android:textColorPrimary</item>
</style>
Therefore, you need to override the current theme by your own. This question has been already resolved with this solution provided by #Galya. The steps are:
Create a new style for android:textAppearanceButton
Use the style's parent from the Base theme: #style/Base.TextAppearance.AppCompat.Button
Then, set caps to false with textAllCaps.
However, this will change all text caps buttons in the project. If you only need to handle these two buttons, I'd suggest you to create two TextViews and provide an onClickListener on them.

Android Calculator - Editview cannot input decimal places

I am new to Android code development...I am developing a Android calculator apps and does not understand why the two EditTexts (first input and second input) cannot accept decimal places but can only input integers...Here attached as follows are the codes:
Thanks!
=============Main Activity===============================
package com.trial.jm4_calculator;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
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.support.v4.app.NavUtils;
public class MainActivity extends Activity {
private TextView output;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(btn1Listener);
output = (TextView) findViewById(R.id.lblOutput);
}
View.OnClickListener btn1Listener = new View.OnClickListener() {
public void onClick(View v) {
double opd1, opd2;
double result = 0.0;
EditText txtOpd1, txtOpd2;
RadioButton rdbAdd, rdbSubtract, rdbMultiply, rdbDivide;
CheckBox chkDivide;
txtOpd1 = (EditText) findViewById(R.id.txtOpd1);
txtOpd2 = (EditText) findViewById(R.id.txtOpd2);
opd1 = Double.parseDouble(txtOpd1.getText().toString());
opd2 = Double.parseDouble(txtOpd2.getText().toString());
rdbAdd = (RadioButton) findViewById(R.id.rdbAdd);
if (rdbAdd.isChecked()) {
result = opd1 + opd2;
}
rdbSubtract = (RadioButton) findViewById(R.id.rdbSubtract);
if (rdbSubtract.isChecked()) {
result = opd1 - opd2;
}
rdbMultiply = (RadioButton) findViewById(R.id.rdbMultiply);
if (rdbMultiply.isChecked()) {
result = opd1 * opd2;
}
rdbDivide = (RadioButton) findViewById(R.id.rdbDivide);
if (rdbDivide.isChecked()) {
result = opd1 / opd2;
}
output.setText("Answer = " + result);
}
};
}
====================Main.xml===================================
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="First Input: "/>
<EditText
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:inputType="number"
android:id="#+id/txtOpd1"/>
</LinearLayout>
<RadioGroup
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:id="#+id/rdgOp">
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="+ "
android:id="#+id/rdbAdd"/>
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="- "
android:id="#+id/rdbSubtract"/>
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="* "
android:id="#+id/rdbMultiply"/>
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="/ "
android:id="#+id/rdbDivide"/>
</RadioGroup>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Second Input: "/>
<EditText
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:inputType="number"
android:id="#+id/txtOpd2"/>
</LinearLayout>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Compute"
android:id="#+id/button1"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/lblOutput"/>
</LinearLayout>
If you want to use Decimal Number only on your EditText
use the xml attribute android:inputType="numberDecimal" in your EditText widget your EditText declaration will be like this:
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal" />
If you want to use Signed Decimal Number than combine the two Xml attributes android:inputType="numberDecimal" and android:inputType="numberSigned". Your EditText declaration will be like this:
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal|numberSigned" >
</EditText>
Change android:inputType from "number" to "numberDecimal". See the documentation for even more options for inputType.
inputType="number" doesnt allow floats. try changing:
android:inputType="number"
to:
android:numeric="integer|decimal"
You need to change the input type of your EditText in the XML code.
Change the inputType attribute of the EditText from
android:inputType="number"
to
android:inputType="numberDecimal"
<EditText
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:inputType="numberDecimal"
android:id="#+id/txtOpd1"/>

Categories

Resources