I am trying to build a calculator for android, i am trying to multiply two numbers.
If i give number 1 and leave number 2 open, i want to get zero as an answer.
I first thought it could be the problem of not having a value for the double.
So i tried: if (Double.isNaN(number1)) { number1=0; }
But it did not work.
How do i make this happen?
R.layout.main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- 1 -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="number:" />
<EditText
android:id="#+id/number1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="0"
android:inputType="number"
android:layout_marginLeft="20dp" />
</LinearLayout>
<!-- 2 -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="number:" />
<EditText
android:id="#+id/number2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="0"
android:inputType="number"
android:layout_marginLeft="20dp" />
</LinearLayout>
<!-- multiply -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="multiply:" />
<TextView
android:id="#+id/multiplydisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginLeft="20dp" />
</LinearLayout>
<Button
android:id="#+id/btncalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"/>
<Button
android:id="#+id/btnreset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset" />
</LinearLayout>
TipcalcActivity.java
package com.tip.calc;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;
public class TipcalcActivity extends Activity {
private EditText number1;
private EditText number2;
private TextView multiplydisplay;
private Button btncalculate;
private Button btnreset;
private double number1calc = 0;
private double number2calc = 0;
private double multiply = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls() {
number1 = (EditText)findViewById(R.id.number1);
number2 = (EditText)findViewById(R.id.number2);
multiplydisplay = (TextView)findViewById(R.id.multiplydisplay);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() { public void
onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() { public void
onClick (View v){ reset(); }});
}
private void calculate() {
number1calc=Double.parseDouble(number1.getText().toString());
number2calc=Double.parseDouble(number2.getText().toString());
multiply=(number1calc*number2calc);
multiplydisplay.setText(Double.toString(multiply));
}
private void reset() {
multiplydisplay.setText("");
number1.setText("");
number2.setText("");
}
}
you should just check that the content of the textfield of the value is different than "". If not, just assign the value 0.
In calculate :
private void calculate() {
number1calc=(number1.getText().toString() != "" ) ? Double.parseDouble(number1.getText().toString()) : 0;
number2calc=(number2.getText().toString() != "" ) ? Double.parseDouble(number2.getText().toString()) : 0;
multiply=(number1calc*number2calc);
multiplydisplay.setText(Double.toString(multiply));
}
if(numberOne.getText().toString().trim().length() < 1 || numberTwo.getText().toString().length() < 1){
multiplyDisplay.setText("0");
}
else{
//default handling
}
If the edittext is left blank, this is obviously not a number(NaN). Doing any operation with NaN in Java will cause the result of this operation to be NaN.
Related
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.
I'm trying to figure out why my app crashes when my AddThreeToTeamA button crashes my application upon clicking. I have addded my XML and my Java code.
I am following a tutorial however it obviously does not crash and I have tried several different solutions.
Any hint will be appreciated.
package com.themovingmonkey.courtcounter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int score = 0;
int scoreTeamA;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void addThreeForTeamA() {
scoreTeamA = score + 3;
displayForTeamA(scoreTeamA);
}
public void addTwoForTeamA() {
scoreTeamA = score + 2;
displayForTeamA(scoreTeamA);
}
public void addOneForTeamA() {
scoreTeamA = score + 1;
displayForTeamA(scoreTeamA);
}
public void displayForTeamA(int score) {
TextView scoreView = (TextView) findViewById(R.id.Team_A_Score);
scoreView.setText(String.valueOf(scoreTeamA));
}
}
////////////////////////////////////////////////////////////////
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text= "Team A"
android:padding="4dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="0"
android:padding="4dp"
android:id="#+id/Team_A_Score"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="3 Points"
android:layout_margin="8dp"
android:onClick="addThreeForTeamA"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="2 Points"
android:layout_margin="8dp"
android:onClick="addTwoForTeamA"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="1 Point"
android:layout_margin="8dp"
android:onClick="addOneForTeamA"
/>
</LinearLayout>
All methods defined using the android:onClick="someMethod" attribute. Then they have to be public and should pass a View as the only parameter, Change your methods to:
public void someMethod(View view){
//Everything else!
}
Your methods do not pass a View as the only parameter at all currently!
I'm having a set of 9 radio Buttons(a group of 3 each),user has to select 3 (1 of each group)
on right selection a increment in score while on wrong selection decrement in score,but problem is that if all 3 correct ans are selected score is coming right else not ,also it is not responding to re selecting of another radio button of the group.On submit button i have written the code, I am new in development so kindly guide
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
case R.id.qa:cb.setChecked(false);
cc.setChecked(false);
cd.setChecked(false);
s[0] = false;
break;
case R.id.qb:
ca.setChecked(false);
cc.setChecked(false);
cd.setChecked(false);
s[0] = false;
break;
case R.id.qc:
cb.setChecked(false);
ca.setChecked(false);
cd.setChecked(false);
s[0] = true;
break;
}
public void onClick(View v) {
score = 0;
for (int i = 0; i < 3; i++) {
if (s[i] == true)
score++;
else
score--;
}
where s is boolean s[] = new boolean[];
I am new in development so not able to sort out problem
The code sample below will add the radiobuttons dynamically to a group so that you can arrange the buttons in any way you like using any layouts.
Layout : main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="1" >
<RadioButton
android:id="#+id/rbtn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:text="A" />
<RadioButton
android:id="#+id/rbtn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:text="B" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="1" >
<RadioButton
android:id="#+id/rbtn3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:text="C" />
<RadioButton
android:id="#+id/rbtn4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:text="D" />
</LinearLayout>
</LinearLayout>
Code : MainActivity.xml
public class MainActivity extends Activity {
private static final String GROUP_A = "GroupA";
private static final String GROUP_B = "GroupB";
private List<RadioButton> radioButtons;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RadioButton rbtn1 = (RadioButton) findViewById(R.id.rbtn1);
RadioButton rbtn2 = (RadioButton) findViewById(R.id.rbtn2);
RadioButton rbtn3 = (RadioButton) findViewById(R.id.rbtn3);
RadioButton rbtn4 = (RadioButton) findViewById(R.id.rbtn4);
addRadioButtonToGroup(rbtn1, GROUP_A);
addRadioButtonToGroup(rbtn2, GROUP_A);
addRadioButtonToGroup(rbtn3, GROUP_A);
addRadioButtonToGroup(rbtn4, GROUP_B);
}
private void addRadioButtonToGroup(RadioButton rbtn, String group) {
rbtn.setTag(group);
if (radioButtons == null) {
radioButtons = new ArrayList<RadioButton>();
}
radioButtons.add(rbtn);
rbtn.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
for (int i = 0; i < radioButtons.size(); i++) {
RadioButton radioButton = radioButtons.get(i);
if (radioButton
.getTag()
.toString()
.equalsIgnoreCase(
buttonView.getTag().toString())) {
if (!radioButton.equals(buttonView)) {
radioButton.setChecked(false);
}
}
}
}
}
});
}
}
Here..First 3 radio buttons will belong to the group A and other to Group B, which makes sure one radio button in a group can be checked at a time. We also dont need the RadioGroup and this code gives the control to arrange Radio Buttons in anyway you like.
Use RadioGroup instead of checking and un checking the RadioButtons manually.
If You put 3 radio buttons in a radio group, you will be able to check a radio button at one time, RadioGroup will manage it.
Check the sample below : On Submit button click it will calculate the score.
layout : main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="First Question" />
<RadioGroup
android:id="#+id/rg1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/rbtn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="A" />
<RadioButton
android:id="#+id/rbtn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="B" />
<RadioButton
android:id="#+id/rbtn3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="C" />
</RadioGroup>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Second Question" />
<RadioGroup
android:id="#+id/rg2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/rbtn4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="P" />
<RadioButton
android:id="#+id/rbtn5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Q" />
<RadioButton
android:id="#+id/rbtn6"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="R" />
</RadioGroup>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Third Question" />
<RadioGroup
android:id="#+id/rg3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/rbtn7"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="X" />
<RadioButton
android:id="#+id/rbtn8"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Y" />
<RadioButton
android:id="#+id/rbtn9"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Z" />
</RadioGroup>
<Button
android:id="#+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>
</ScrollView>
Activity :
package com.example.demo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends Activity {
private RadioGroup rg1;
private RadioGroup rg2;
private RadioGroup rg3;
private OnClickListener btnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
int answerCount = 0;
if (rg1.getCheckedRadioButtonId() == R.id.rbtn1)
answerCount++;
if (rg2.getCheckedRadioButtonId() == R.id.rbtn5)
answerCount++;
if (rg3.getCheckedRadioButtonId() == R.id.rbtn9)
answerCount++;
Toast.makeText(MainActivity.this, String.valueOf(answerCount),
Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rg1 = (RadioGroup) findViewById(R.id.rg1);
rg2 = (RadioGroup) findViewById(R.id.rg2);
rg3 = (RadioGroup) findViewById(R.id.rg3);
Button btnSumbit = (Button) findViewById(R.id.btnSubmit);
btnSumbit.setOnClickListener(btnClickListener);
}
}
I have a problem concerning setting a listener that would execute different action based on the clicked button.
The compiler doesn't detect any error on the syntax, but the problem is that when I simulate my app on the emulator, it pops up the window asking for "Force Close".
Here is my Java file :
package tp.imc.namespace;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class IMCCalculatorActivity extends Activity {
EditText poids,taille;
Button boutton1,boutton2;
TextView text1;
Boolean k=true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
poids=(EditText) findViewById(R.id.poids);
taille=(EditText) findViewById(R.id.taille);
boutton1 =(Button) findViewById(R.id.boutton1);
text1=(TextView) findViewById(R.id.text1);
boutton1.setOnClickListener(clicker);
boutton2.setOnClickListener(clicker);
}
// declare a OnClickListener that will execute different actions
// depending on the view that was clicked
View.OnClickListener clicker = new View.OnClickListener(){
public void onClick (View v){
if( v == boutton1 )
{
String a,b;
Double r;
a=poids.getText().toString();
b=taille.getText().toString();
Double zero=Double.parseDouble(b);
a=poids.getText().toString();
b=taille.getText().toString();
if (zero==0)
{
text1.setText("Erreur ! Division par 0.");
}
else {
r=(Double.parseDouble(a))/(Double.parseDouble(b)*Double.parseDouble(b));
if (r<16.5) text1.setText("Famine.");
else if (r>16.5 && r<18.5) text1.setText("Maigreur.");
else if (r>=18.5 && r<25) text1.setText("Coplulence nomrale.");
else if (r>=25 && r<30) text1.setText("Surpoids.");
else if (r>=30 && r<35) text1.setText("Obésité modérée.");
else if (r>=35 && r<40) text1.setText("Obésité sévère.");
else if (r>=40) text1.setText("Obésité morbide ou massive.");
}
}
else if( v == boutton2 )
{
poids.setText("");
taille.setText("");
text1.setText("");
}
}
};
}
And here is my XML file :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/poids"
android:textColor="#FF0000"
android:gravity="center"
/>
<EditText
android:id="#+id/poids"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/poids"
android:lines="1"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/taille"
android:textColor="#FF0000"
android:gravity="center"
/>
<EditText
android:id="#+id/taille"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/taille"
android:lines="1"
/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/metre"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/centimetre"
/>
</RadioGroup>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/mega"
android:checked="false"
/>
<Button
android:id="#+id/boutton1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/compute" />
<Button
android:id="#+id/boutton2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/raz" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/resultat"
/>
<TextView
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/text"
/>
</LinearLayout>
You don't define boutton2, it is null. Add this:
boutton2 = (Button) findViewById(R.id.boutton2);
boutton2.setOnClickListener(clicker);
Since boutton1 and boutton2 don't have common code between them you could simply create two different listeners.
Lastly, this line doesn't look right.
if( v == boutton1 )
You are trying to compare a View to a Button which may not work. Try this:
if( v.getId() == boutton1.getId() )
I searched net to find the answer for my following problem. But no answer found. I myself tried several ways, but I am still a novice at Android. What I found on net related to scrolling is official documentation and examples of scrolling on http://developer.android.com, Mr. Senthilkumar's How to scroll the screen, Kakka47's ScrollView only part of the screen, darrinps A scroll view with only part of the screen scrolling, etc.
This is very common requirement as is clear from above titles. I have following screen layout as shown in figure.
The screen from top to column titles is stable. The table records, below column titles needs to scroll. I have AbsoluteLayout (I know it is deprecated but that is the only one I can use for by specific need), inside it a scrollview and inside scrollview a TableLayout.
User clicks "Add" button to add the orders received. One order in one row. As rows increase, they go beyond visible area. Therefore, I want it to scroll so user can access it. But this part is not scrolling. I have given the listing of my code. Please tell me what to do.
Code:
package com.BookOrders;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsoluteLayout;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
//import android.widget.TableRow.LayoutParams;
#SuppressWarnings("deprecation")
public class BookOrders extends Activity implements ScrollViewListener{
/** Called when the activity is first created. */
private TextView BookingDateDisplay;
private Button ChangeDate, AddRec, DeleteRec, SaveAll;
private CheckBox SelectedAll, SelectedRec;
private ObservableScrollView CustomScroller = null;
private ObservableScrollView CustomScrolled = null;
private int ChangedYear;
private int ChangedMonth;
private int ChangedDay;
public Context CurrentContext, UsedContext;
static final int DATE_DIALOG_ID = 0;
int IdGenerator = 100000;
int Number_of_Records = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
#SuppressWarnings("deprecation")
final AbsoluteLayout main = (AbsoluteLayout)findViewById(R.id.widget0);
CurrentContext = main.getContext();
//final ScrollView ScrollControl = (ScrollView)findViewById(R.id.scroller);
//final AbsoluteLayout LayerControl = (AbsoluteLayout)findViewById(R.id.FinalLayer);
// UsedContext = LayerControl.getContext();
// capture our View elements
CustomScroller = (ObservableScrollView) findViewById(R.id.scrollContainer);
BookingDateDisplay = (TextView) findViewById(R.id.BookedDate);
ChangeDate = (Button) findViewById(R.id.pickDate);
AddRec = (Button) findViewById(R.id.AddRecord);
DeleteRec = (Button) findViewById(R.id.DeleteRecord);
SaveAll = (Button) findViewById(R.id.SaveRecord);
SelectedAll = (CheckBox) findViewById(R.id.SelectAll);
// add a click listener to the button
ChangeDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
AddRec.setOnClickListener(new View.OnClickListener() {
public void onClick(View AddRecView) {
IdGenerator = IdGenerator+10;
UsedContext = AddRecView.getContext();
TableRow Tr = new TableRow(UsedContext);
for (int controls=0; controls<6; controls++) {
if (controls==0){
CheckBox RecordCheck = new CheckBox(UsedContext);
RecordCheck.setId(IdGenerator+controls);
RecordCheck.setTag("CheckBoxTag");
RecordCheck.setHeight(20);
RecordCheck.setWidth(25);
Tr.addView(RecordCheck);
}
if ((0 < controls ) && (controls<5)){
Spinner Record = new Spinner(UsedContext);
Record.setId(IdGenerator+controls);
//Record.setMinimumHeight(20);
//Record.setMinimumWidth(90);
Tr.addView(Record);
}
if (controls==5){
EditText OrderQuantity = new EditText(UsedContext);
OrderQuantity.setId(IdGenerator+controls);
//OrderQuantity.setHeight(20);
//OrderQuantity.setWidth(90);
Tr.addView(OrderQuantity);
}
}
TableLayout Orders = (TableLayout)findViewById(R.id.OrderData);
Orders.addView(Tr);
// Scrolls to line before last - why?
final ScrollView ScrollAttempt = (ScrollView) findViewById(R.id.scrollContainer);
ScrollAttempt.post(new Runnable() {
public void run() {
ScrollAttempt.fullScroll(View.FOCUS_DOWN);
}
});
Number_of_Records = Number_of_Records + 1;
}
});
// updates the date in the TextView
private void updateDisplay() {
BookingDateDisplay.setText(
new StringBuilder()
.append(ChangedDay).append("-")
.append(ChangedMonth + 1).append("-") // Month is 0 based so add 1
.append(ChangedYear).append(" "));
}
// the call back received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener DateSetListener =
new DatePickerDialog.OnDateSetListener(){
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
ChangedYear = year;
ChangedMonth = monthOfYear;
ChangedDay = dayOfMonth;
updateDisplay();
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, DateSetListener, ChangedYear, ChangedMonth, ChangedDay);
}
return null;
}
public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
if(scrollView == CustomScroller) {
CustomScrolled.scrollTo(x, y);
} else if(scrollView == CustomScrolled) {
CustomScroller.scrollTo(x, y);
}
}
}
My main.xml:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/widget0"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<!-- <ImageButton android:text="Date" android:layout_height="20px" android:layout_width="32px" android:id="#+id/BDate" android:layout_x="274dip" android:layout_y="51dip"></ImageButton> -->
<TextView
android:id="#+id/Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="81dip"
android:layout_y="10dip"
android:background="#0ff0ff"
android:gravity="center"
android:text="Order Booking"
android:textColor="#330000"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" >
</TextView>
<TextView
android:id="#+id/BDate_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="277dip"
android:layout_y="52dip"
android:gravity="right"
android:text="Booked on:"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/BookedDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="350dip"
android:layout_y="52dip"
android:text=""
android:textSize="12sp" >
</TextView>
<Button
android:id="#+id/pickDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="400dip"
android:layout_y="15dip"
android:text="Change Date"
android:textSize="10sp" >
</Button>
<View
android:layout_width="wrap_content"
android:layout_height="36dp"
android:layout_y="68dp"
android:background="#drawable/gradient" >
</View>
<Button
android:id="#+id/AddRecord"
android:layout_width="120dp"
android:layout_height="34dp"
android:layout_x="10dip"
android:layout_y="71dip"
android:text="Add"
android:textSize="10sp" >
</Button>
<Button
android:id="#+id/DeleteRecord"
android:layout_width="120dp"
android:layout_height="34dp"
android:layout_x="140dp"
android:layout_y="71dp"
android:text="Delete"
android:textSize="10sp" >
</Button>
<Button
android:id="#+id/ClearRecord"
android:layout_width="120dp"
android:layout_height="34dp"
android:layout_x="270dp"
android:layout_y="71dp"
android:text="Clear"
android:textSize="10sp" >
</Button>
<Button
android:id="#+id/SaveRecord"
android:layout_width="120dp"
android:layout_height="34dp"
android:layout_x="400dp"
android:layout_y="71dp"
android:text="Save"
android:textSize="10sp" >
</Button>
<View
android:layout_width="wrap_content"
android:layout_height="1dp"
android:layout_y="110dp"
android:background="#drawable/gradient" >
</View>
<CheckBox
android:id="#+id/SelectAll"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_x="10dip"
android:layout_y="115dip"
android:text="Select All"
android:textSize="10sp" >
</CheckBox>
<TextView
android:id="#+id/Company"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="95dip"
android:layout_y="115dip"
android:background="#666666"
android:text="Company"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/Product"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="200dip"
android:layout_y="115dip"
android:background="#666666"
android:text="Product"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/Code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="300dip"
android:layout_y="115dip"
android:background="#666666"
android:text="Code"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/Model"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="380dp"
android:layout_y="115dp"
android:background="#666666"
android:text="Model"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/Quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="470dp"
android:layout_y="115dp"
android:background="#666666"
android:text="Quantity"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<View
android:id="#+id/view1"
android:layout_width="wrap_content"
android:layout_height="1dp"
android:layout_x="0dip"
android:layout_y="134dip"
android:background="#drawable/gradient" >
</View>
<com.BookOrders.ObservableScrollView
android:id="#+id/scrollContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_x="1dp"
android:layout_y="140dp"
android:clickable="true"
android:fadeScrollbars="false"
android:fillViewport="true" >
<TableLayout
android:id="#+id/OrderData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stretchColumns="0,1,2,3,4" />
</com.BookOrders.ObservableScrollView>
</AbsoluteLayout>
Have you tried a ScrollView? You can find more about ScrollView here
Here is an example of how to use ScrollView:
<ScrollView
android:id="#+id/coupons_details_scroll_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<!--You can nest any other views here, and they will be scrollable, but take care of views that have their own scrolling capabilities like ListView -->
</ScrollView>
Good luck with it :)
I worked out the solution for this. For those who would like to know can first go through the following link
http://blog.stylingandroid.com/archives/447
I used this logic. However, I create rows dynamically when user clicks "Add" button. The only problem is, if you use spinner you won't be able to set its height zero.
Nitin