Multiple Checkboxes to Run Different Methods - java

Here is my .java:
package com.example.clarkrubberfoam;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
public class PriceEstimator extends ActionBarActivity implements OnCheckedChangeListener {
double total = 0;
double md_foam25 = 0.31, md_foam50 = 0.63, md_foam75 = 0.81, md_foam100 = 1.01, md_foam125 = 1.25, md_foam150 = 1.34;
double hd_foam25 = 0.34, hd_foam50 = 0.66, hd_foam75 = 0.91, hd_foam100 = 1.19, hd_foam125 = 1.48, hd_foam150 = 1.53;
double ye_foam25 = 0.59, ye_foam50 = 0.94, ye_foam75 = 1.41, ye_foam100 = 1.67, ye_foam125 = 2.09, ye_foam150 = 2.34;
double oe_foam25 = 0.70, oe_foam50 = 1.37, oe_foam75 = 1.69, oe_foam100 = 2.20, oe_foam125 = 2.64, oe_foam150 = 3.16;
CheckBox chkMD = (CheckBox) findViewById(R.id.checkBox1);
CheckBox chkHD = (CheckBox) findViewById(R.id.checkBox2);
CheckBox chkYE = (CheckBox) findViewById(R.id.checkBox3);
CheckBox chkOE = (CheckBox) findViewById(R.id.checkBox4);
/* Called when first opening the app */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_price_estimator);
//Attach listeners to the checkboxes
chkMD.setOnCheckedChangeListener(this);
chkHD.setOnCheckedChangeListener(this);
chkYE.setOnCheckedChangeListener(this);
chkOE.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (buttonView == chkMD) {
if(isChecked) {
mediumDensityPrice();
} else {
total = total + 0;
}
}
if (buttonView == chkHD){
if(isChecked) {
highDensityPrice();
} else {
total = total + 0;
}
}
if (buttonView == chkYE) {
if(isChecked) {
yellowEnduroPrice();
} else {
total = total + 0;
}
}
if (buttonView == chkOE) {
if(isChecked) {
orangeEnduroPrice();
} else {
total = total + 0;
}
}
}
public void mediumDensityPrice() {
Toast.makeText(getBaseContext(), "Medium Density Selected", Toast.LENGTH_LONG).show();
}
public void highDensityPrice() {
Toast.makeText(getBaseContext(), "High Density Selected", Toast.LENGTH_LONG).show();
}
public void yellowEnduroPrice() {
Toast.makeText(getBaseContext(), "Yellow Enduro Selected", Toast.LENGTH_LONG).show();;
}
public void orangeEnduroPrice() {
Toast.makeText(getBaseContext(), "Orange Enduro Selected", Toast.LENGTH_LONG).show();;
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_price_estimator,
container, false);
return rootView;
}
}
Here is my .xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.clarkrubberfoam.PriceEstimator$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:text="#string/price_estimator"
android:textAppearance="?android:attr/textAppearanceLarge" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:text="#string/medium_density" />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/checkBox1"
android:layout_below="#+id/checkBox1"
android:text="#string/high_density" />
<CheckBox
android:id="#+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkBox1"
android:layout_alignBottom="#+id/checkBox1"
android:layout_marginLeft="27dp"
android:layout_toRightOf="#+id/checkBox1"
android:text="#string/enduro_yellow" />
<CheckBox
android:id="#+id/checkBox4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/checkBox3"
android:layout_below="#+id/checkBox3"
android:text="#string/enduro_orange" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/checkBox2"
android:layout_below="#+id/checkBox2"
android:layout_marginTop="10dp"
android:text="#string/enter_width" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/numberPicker1"
android:layout_below="#+id/numberPicker1"
android:layout_marginTop="30dp"
android:onClick="totalPrice"
android:text="#string/calculate_me" />
<NumberPicker
android:id="#+id/numberPicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView2"
android:layout_marginTop="16dp" />
<NumberPicker
android:id="#+id/numberPicker2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/numberPicker1"
android:layout_centerHorizontal="true" />
<NumberPicker
android:id="#+id/numberPicker3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView4"
android:layout_alignTop="#+id/numberPicker2" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/numberPicker1"
android:layout_alignRight="#+id/numberPicker2"
android:text="#string/enter_length" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/numberPicker1"
android:layout_alignParentRight="true"
android:text="#string/enter_thickness" />
My problem is that when I run the program, it crashes immediately. I'm not sure what's going wrong. I am currently trying to adapt another multiple checkbox program to work for my needs: 'http://pulse7.net/android/android-check-box-example/'.
Essentially I have four grades of foam, and multiple thicknesses, so each grade, if checked in the checkbox, will need to lead to a different method. Currently, the Toast.makeText parts are just a placeholder for what will go there eventually once this part gets figured out :)
Cheers!

You must findViewById() in onCreate() method after setContentView() call.
public class MainActivity extends Activity {
CheckBox chkMD;
CheckBox chkHD;
CheckBox chkYE;
CheckBox chkOE;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_price_estimator);
chkMD = (CheckBox) findViewById(R.id.checkBox1);
chkHD = (CheckBox) findViewById(R.id.checkBox2);
chkYE = (CheckBox) findViewById(R.id.checkBox3);
chkOE = (CheckBox) findViewById(R.id.checkBox4);
// Attach listeners to the checkboxes
chkMD.setOnCheckedChangeListener(this);
chkHD.setOnCheckedChangeListener(this);
chkYE.setOnCheckedChangeListener(this);
chkOE.setOnCheckedChangeListener(this);
}
}

Related

TextView in SliderView text shown and text value bug [the n'th TextView is returning its initialized value after changing (n+2)'th textView]

i have a textView in SliderView like this
activitity_slider.xml
<androidx.viewpager.widget.ViewPager
android:id="#+id/slideViewPager"
android:layout_width="match_parent"
slide_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_gravity="center"
android:background="#color/white">
<LinearLayout
android:id="#+id/HareketEkranı"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_marginBottom="10dp"
android:orientation="vertical"
>
<androidx.cardview.widget.CardView
android:id="#+id/hareket"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
app:cardBackgroundColor="#color/white"
app:cardCornerRadius="10dp">
<ImageView
android:id="#+id/HareketResmi"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:contentDescription="Hareket"/>
//android:src="#drawable/ic_armcircle"
<com.jjoe64.graphview.GraphView
android:id="#+id/haraketdatasi"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="left"
android:text="Hareket"
android:layout_weight="1"
android:textColor="#color/darkTextColor"
android:textSize="24sp" />
<TextView
android:id="#+id/HareketAdi"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:textAlignment="gravity"
android:gravity="right"
android:text="Armcircle"
android:textColor="#color/red"
android:layout_weight="1"
android:textSize="24sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/TekrarYazisiSlide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="Tekrar"
android:layout_weight="1"
android:textColor="#color/darkTextColor"
android:textSize="24sp" />
<TextView
android:id="#+id/TekrarSayisiSlide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:text="TekrarSayisi"
android:textAlignment="gravity"
android:gravity="right"
android:layout_weight="1"
android:textColor="#color/red"
android:textSize="24sp" />
<TextView
android:id="#+id/kesme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:text="/"
android:layout_weight="1"
android:textColor="#color/black"
android:textSize="24sp" />
<TextView
android:id="#+id/TekrarhedefiSlide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:text="25"
android:layout_weight="1"
android:textColor="#color/black"
android:textSize="24sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</RelativeLayout>
UPDATE !
SliderAdapter.java
package gymholix.assistx;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
public class SliderAdapter extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
public SliderAdapter(Context context){
this.context = context;
}
//Arrays
public int[] slide_images = {
R.drawable.ic_armcircle,
R.drawable.ic_ropejump,
R.drawable.ic_jumpingjack,
R.drawable.ic_burpee,
R.drawable.ic_squat
};
public String[] slide_headings = {
"ArmCircle",
"RopeJump",
"JumpingJack",
"Burpee",
"Squat"
};
/*public String[] tekrar_sayisi = {
"0",
"0",
"0",
"0",
"0"*/
public int[] tekrar_sayisi = {
1,
2,
3,
4,
5
};
#Override
public int getCount() {
return slide_headings.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (RelativeLayout) object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view =layoutInflater.inflate(R.layout.slide_layout, container, false);
ImageView slideImageView = (ImageView) view.findViewById(R.id.HareketResmi);
TextView slideHeading = (TextView) view.findViewById(R.id.HareketAdi);
TextView slideTekraSayisi = (TextView) view.findViewById(R.id.TekrarSayisiSlide);
slideImageView.setImageResource((slide_images[position]));
slideHeading.setText(slide_headings[position]);
slideTekraSayisi.setText(String.valueOf(tekrar_sayisi[position]));
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
}
}
Slider.Java
package gymholix.assistx;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Slider extends AppCompatActivity {
private LinearLayout mDotLayout;
private String asd;
private int asdf;
TextView DenemeSayiCek;
int position;
View view;
int count;
View viewFix;
Context context;
//Sensors---------------------------------------------------------------------------------------
private Accelerometer accelerometer;
private Gyroscope gyroscope;
public double[] acc={3.00,2.00,1.00};
public double[] gyr={3.00,2.00,1.00};
//Sensors---------------------------------------------------------------------------------------
//Main------------------------------------------------------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Antreman antreman = new Antreman();
context = this;
setContentView(R.layout.activity_slider);
ViewPager AktifHareket = findViewById(R.id.slideViewPager);
mDotLayout = findViewById(R.id.dotsLayout);
SliderAdapter sliderAdapter = new SliderAdapter(this);
AktifHareket.setAdapter((sliderAdapter));
addDotsIndicator();
//Saydir Buton------------------------------------------------------------------------------
TextView Deneme = findViewById(R.id.deneme);
TextView Deneme4 = findViewById(R.id.deneme4);
TextView Deneme3 = findViewById(R.id.deneme3);
TextView Deneme2 = findViewById(R.id.deneme2);
Button Saydir = findViewById(R.id.SaydirSlide);
Button Saydir2 = findViewById(R.id.Saydir2Slide);
Saydir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
position = AktifHareket.getCurrentItem();
view = AktifHareket.getChildAt(position);
count = AktifHareket.indexOfChild(view);
viewFix = AktifHareket.getChildAt(count);
DenemeSayiCek = viewFix.findViewById(R.id.TekrarSayisiSlide);
asd = DenemeSayiCek.getText().toString();
asdf = Integer.parseInt(asd);
asdf++;
DenemeSayiCek.setText(String.valueOf(asdf));
Deneme.setText(String.valueOf(asd));
Deneme2.setText(String.valueOf(position));
Deneme3.setText(String.valueOf(asdf));
Deneme4.setText(String.valueOf(SliderAdapter.POSITION_NONE));
}
});
//Saydir Buton------------------------------------------------------------------------------
//ImageButton-------------------------------------------------------------------------------
ImageView logoImage = findViewById(R.id.logo);
logoImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
antreman.AntremanSayfasi(context);
}
});
antreman.AntremanSayfasi(context);//Açılışta Sayfayı açsın diye
//ImageButton-------------------------------------------------------------------------------
//Sensors-----------------------------------------------------------------------------------
accelerometer = new Accelerometer(this);
gyroscope = new Gyroscope(this);
accelerometer.setListner(new Accelerometer.Listner() {
#Override
public void onTranslation(float ax, float ay, float az) {
setAccValue(ax, ay, az);
Antreman.GetSensorValues.OnAccelerometerChangeValues = acc;
}
});
gyroscope.setListner(new Gyroscope.Listner() {
#Override
public void onRotation(float gx, float gy, float gz) {
setGyroValue(gx, gy, gz);
Antreman.GetSensorValues.OnGyroscopeChangeValues = gyr;
//OnSensorChangeValues.add(1, String.valueOf(gyr) );
}
});
/* Saydir2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});*/
//Sensors-----------------------------------------------------------------------------------
}
//Sensors---------------------------------------------------------------------------------------
protected void onResume(){
super.onResume();
accelerometer.register();
gyroscope.register();
}
protected void onPouse(){
super.onPause();
accelerometer.unregister();
gyroscope.unregister();
}
//Sensors---------------------------------------------------------------------------------------
//SensorsValueGetAndSet-------------------------------------------------------------------------
public double[] setAccValue(float ac, float bc, float cc){
this.acc[0] = ac;
this.acc[1] = bc;
this.acc[2] = cc;
return acc;
}
public double[] setGyroValue(float qq, float wq, float eq){
this.gyr[0] = qq;
this.gyr[1] = wq;
this.gyr[2] = eq;
return gyr;
}
public void getAccValue(float ac, float bc, float cc){
ac = (float) acc[0];
bc = (float) acc[1];
cc = (float) acc[2];
}
public void getGyroValue(float qq, float wq, float eq){
qq = (float) gyr[0];
wq = (float) gyr[1];
eq = (float) gyr[2];
}
//SensorsValueGetAndSet-------------------------------------------------------------------------
public void addDotsIndicator(){
TextView[] mDots = new TextView[3];
for(int i = 0; i < mDots.length; i++){
mDots[i] = new TextView(this);
mDots[i].setText(Html.fromHtml("•"));
mDots[i].setTextSize(35);
mDots[i].setTextColor(getResources().getColor(R.color.colorPrimaryDark));
mDotLayout.addView(mDots[i]);
}
}
//----------------------------------------------------------------------------------------------
}
the weird thing about this code is; while running the button changes the text value correctly in the first pager, and the seckond one but when it comes the third one while it changes the value it resets the first pagers shown value but the getText() method inherits the correct value but the text is frozen and it cant be changed any more, after that the other page's values cant be changed either, but the getText() method still works fine and gets the correct value.
any idea will speed up my debuging process thanx anyway...
adding this snipped solved the problem, it is a must to define borders to the pager
#Override
protected void onCreate(Bundle savedInstanceState) {
...
int size = sliderAdapter.slide_headings.length;
AktifHareket.setOffscreenPageLimit(size);

How do I create a fragment template(class with variables and methods, layout) for multiple fragments with the same content?

On the main screen I have 7 buttons (days) and a fragment.
For every day of the week I wanted to generate a fragment with some EditTexts and a ListView, but creating 7 fragments with the same layout and almost the same class content seems too repetitive.
I only did it for Monday and Tuesday.
The only difference between MondayFragment and TuesdayFragment is that in TuesdayFragment I renamed the variable mondayTV to tuesdayTV and in layout I changed the ids of the submit button and the ListView. Also the key for Bundle is different. I don't think it's worth posting it since it's so similar to MondayFragment.
I want to know if it's possible to create a fragment template and use it to generate a fragment for every button of the activity given this code I wrote. There is still a lot to work on when it comes to functionality but I can't get this idea out of my head.
MainActivity.java
package com.example.dietmanagement;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public Button monday, tuesday, wednesday, thursday, friday, saturday, sunday;
final MondayFragment mondayFragment = new MondayFragment();
final TuesdayFragment tuesdayFragment = new TuesdayFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Intent i = getIntent();
String current_user = i.getStringExtra("current_user");
TextView current_user_txtview = findViewById(R.id.current_user);
current_user_txtview.setText("Welcome, " + current_user);*/
monday = (Button)findViewById(R.id.monday_btn);
tuesday = (Button)findViewById(R.id.tuesday_btn);
wednesday = (Button)findViewById(R.id.wednesday_btn);
thursday = (Button)findViewById(R.id.thursday_btn);
friday = (Button)findViewById(R.id.friday_btn);
saturday = (Button)findViewById(R.id.saturday_btn);
sunday = (Button)findViewById(R.id.sunday_btn);
monday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFragment(mondayFragment);
getDay(mondayFragment, "monday", (String) monday.getContentDescription());
}
});
tuesday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFragment(tuesdayFragment);
getDay(tuesdayFragment, "tuesday", (String) tuesday.getContentDescription());
}
});
}
private void openFragment(final Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.daysfragment, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
public void getDay(final Fragment fragment, String key, String value)
{
Bundle bnd = new Bundle();
bnd.putString(key, value);
fragment.setArguments(bnd);
}
}
Activity_main.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"
android:background="#color/background_green"
tools:context=".MainActivity">
<Button
android:id="#+id/tuesday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:contentDescription="#string/tuesday_context"
android:text="#string/tuesday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.194"
app:layout_constraintStart_toEndOf="#+id/monday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.017" />
<TextView
android:id="#+id/main_title"
android:layout_width="147dp"
android:layout_height="93dp"
android:fontFamily="sans-serif-medium"
android:text="#string/welcome_label"
android:textColor="#FFFFFF"
android:textSize="70sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.414"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.049" />
<Button
android:id="#+id/monday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:contentDescription="#string/monday_context"
android:text="#string/monday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.16"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.017" />
<Button
android:id="#+id/thursday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/thursday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.018"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.172" />
<Button
android:id="#+id/sunday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/sunday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.786"
app:layout_constraintStart_toEndOf="#+id/saturday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.172" />
<Button
android:id="#+id/saturday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/saturday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.225"
app:layout_constraintStart_toEndOf="#+id/friday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.172" />
<Button
android:id="#+id/friday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/friday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.137"
app:layout_constraintStart_toEndOf="#+id/thursday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.172" />
<Button
android:id="#+id/wednesday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/wednesday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.369"
app:layout_constraintStart_toEndOf="#+id/tuesday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.017" />
<ImageView
android:id="#+id/logo"
android:layout_width="52dp"
android:layout_height="58dp"
android:layout_marginStart="8dp"
android:layout_marginTop="52dp"
android:contentDescription="#string/app_name"
app:layout_constraintStart_toEndOf="#+id/main_title"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_logo" />
<TextView
android:id="#+id/current_user"
android:layout_width="362dp"
android:layout_height="27dp"
android:text="#string/current_user"
android:textAlignment="viewEnd"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/main_title"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.938"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.318" />
<FrameLayout
android:id="#+id/daysfragment"
android:layout_width="match_parent"
android:layout_height="460dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MondayFragment.java
package com.example.dietmanagement;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MondayFragment extends Fragment {
public TextView mondayTV;
public ArrayList<String> hour_food;
public ArrayAdapter<String> listViewAdapter;
public ListView listView;
public EditText input_meal;
public EditText input_time;
public Button submit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_monday, container, false);
mondayTV = (TextView) v.findViewById(R.id.day);
Bundle bndMon = getArguments();
String day = bndMon.getString("monday");
mondayTV.setText(day);
hour_food = new ArrayList<String>();
listViewAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, hour_food);
listView = (ListView)v.findViewById(R.id.monday_list_item);
listView.setAdapter(listViewAdapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
hour_food.remove(position);
Toast.makeText(getActivity(), "Meal Removed", Toast.LENGTH_SHORT).show();
listViewAdapter.notifyDataSetChanged();
return true;
}
});
input_meal = v.findViewById(R.id.input_meal);
input_time = v.findViewById(R.id.input_time);
submit = (Button) v.findViewById(R.id.submit_food_btn);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(TextUtils.isEmpty(input_time.getText())) {
Toast.makeText(getActivity(), "Empty time input", Toast.LENGTH_SHORT).show();
} else if(TextUtils.isEmpty(input_meal.getText())){
Toast.makeText(getActivity(), "Empty meal input", Toast.LENGTH_SHORT).show();
}
else
{
hour_food.add(String.format("%s - %s", input_meal.getText().toString(), input_time.getText().toString()));
listViewAdapter.notifyDataSetChanged();
input_meal.setText("");
input_time.setText("");
}
}
});
return v;
}
}
fragment_monday.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_green"
tools:context=".MondayFragment">
<TextView
android:id="#+id/day"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="#string/day" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/input_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autofillHints="#string/time"
android:hint="#string/time"
android:inputType="time" />
<EditText
android:id="#+id/input_meal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints="#string/meal"
android:hint="#string/meal"
android:inputType="textAutoCorrect|textCapSentences" />
</LinearLayout>
<Button
android:id="#+id/submit_food_btn_monday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit"
android:background="#color/white"
android:textColor="#color/background_green"
android:layout_gravity="end"
android:layout_marginTop="10dp"/>
<ListView
android:id="#+id/monday_list_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
strings.xml
Create DayFragment and layout only for one day. Pass extra information for Fragment and handle situations for different days with that extra information (in your case it looks like only String from bundle is different).
fragment_day.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_green">
<TextView
android:id="#+id/day"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="#string/day" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/input_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autofillHints="#string/time"
android:hint="#string/time"
android:inputType="time" />
<EditText
android:id="#+id/input_meal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints="#string/meal"
android:hint="#string/meal"
android:inputType="textAutoCorrect|textCapSentences" />
</LinearLayout>
<Button
android:id="#+id/submit_food_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit"
android:background="#color/white"
android:textColor="#color/background_green"
android:layout_gravity="end"
android:layout_marginTop="10dp"/>
<ListView
android:id="#+id/list_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
DayFragment.java
public class DayFragment extends Fragment {
private TextView dayTV;
private ArrayList<String> hour_food;
private ArrayAdapter<String> listViewAdapter;
private ListView listView;
private EditText input_meal;
private EditText input_time;
private Button submit;
private String text;
public DayFragment(String text) {
this.text = text;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_day, container, false);
dayTV = v.findViewById(R.id.day);
dayTV.setText(text);
hour_food = new ArrayList<>();
listViewAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, hour_food);
listView = v.findViewById(R.id.list_item);
listView.setAdapter(listViewAdapter);
listView.setOnItemLongClickListener((parent, view, position, id) -> {
hour_food.remove(position);
Toast.makeText(getActivity(), "Meal Removed", Toast.LENGTH_SHORT).show();
listViewAdapter.notifyDataSetChanged();
return true;
});
input_meal = v.findViewById(R.id.input_meal);
input_time = v.findViewById(R.id.input_time);
submit = v.findViewById(R.id.submit_food_btn);
submit.setOnClickListener(v1 -> {
if (TextUtils.isEmpty(input_time.getText())) {
Toast.makeText(getActivity(), "Empty time input", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(input_meal.getText())) {
Toast.makeText(getActivity(), "Empty meal input", Toast.LENGTH_SHORT).show();
} else {
hour_food.add(String.format("%s - %s", input_meal.getText().toString(), input_time.getText().toString()));
listViewAdapter.notifyDataSetChanged();
input_meal.setText("");
input_time.setText("");
}
});
return v;
}
}
Use constructor for passing information.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button monday = findViewById(R.id.monday_btn),
tuesday = findViewById(R.id.tuesday_btn),
wednesday = findViewById(R.id.wednesday_btn),
thursday = findViewById(R.id.thursday_btn),
friday = findViewById(R.id.friday_btn),
saturday = findViewById(R.id.saturday_btn),
sunday = findViewById(R.id.sunday_btn);
openFragment(monday);
openFragment(tuesday);
openFragment(wednesday);
openFragment(thursday);
openFragment(friday);
openFragment(saturday);
openFragment(sunday);
}
private void openFragment(Button btn) {
btn.setOnClickListener(v -> {
String contentDescription = btn.getContentDescription().toString();
getSupportFragmentManager().beginTransaction()
.replace(R.id.daysfragment, new DayFragment(contentDescription))
.addToBackStack(null)
.commit();
});
}
}
In MainActivity openFragment() method takes a Button parameter and with that Button and sets onClickListener to that Button. When you click any Button it gets content description from that Button and passing it to Fragment and opens that Fragment with that content description.

how to use edittext inside the radiogroup in android?

**I have used four radio buttons for adding and subtraction the amount in the wallet. whenever i open the app it crashes .Whenever i open the app it crashes i don't what is error please someone help me. i am new to android. In this app i have used four radio buttons for add the amount and subtracting the amount. **
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/form"
tools:context="com.sivaneshsg.wallet.MainActivity">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Amount"
android:textSize="25sp"
android:textStyle="italic"
android:textColor="#android:color/black"
android:paddingTop="5dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"/>
<EditText
android:id="#+id/inputamount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Amount in Rs."
android:paddingTop="5dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:inputType="number"
android:ems="10"
/>
<RadioGroup
android:id="#+id/rgroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Income"
android:textStyle="italic"
android:textSize="20sp"
android:textColor="#android:color/black"
android:paddingBottom="10dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="#+id/cash1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cash"
android:textSize="15dp"
android:paddingRight="10dp"
android:textColor="#android:color/black"
/>
<RadioButton
android:id="#+id/card1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Card"
android:textColor="#android:color/black"
/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Expense"
android:textSize="20dp"
android:textStyle="italic"
android:textColor="#android:color/black"
android:paddingBottom="10dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="#+id/cash2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cash"
android:textColor="#android:color/black"
android:textSize="15sp"
android:paddingRight="10dp"
/>
<RadioButton
android:id="#+id/card2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Card"
android:textSize="15sp"
android:textColor="#android:color/black"
/>
</LinearLayout>
</RadioGroup>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK"
/>
<TextView
android:id="#+id/amountcard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:text="Amount in Card : RS. 0"
android:textSize="25sp"
android:padding="10dp"/>
<TextView
android:id="#+id/amountcash"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Amount in Cash : Rs. 0"
android:textSize="25sp"
android:textColor="#android:color/black"
android:padding="10dp"/>
<TextView
android:id="#+id/amountwallet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Total Amount in Wallet : RS. 0"
android:textSize="23sp"
android:textColor="#android:color/black"
android:textStyle="bold"
android:padding="10dp"/>
</LinearLayout>
package com.sivaneshsg.wallet;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
public class MainActivity extends AppCompatActivity {
int cashamount = 0;
int cardamount = 0;
int totalamount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText et = (EditText) findViewById(R.id.inputamount);
final int amount = Integer.parseInt(et.getText().toString());
RadioGroup rg = (RadioGroup) findViewById(R.id.rgroup);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.card1) {
cardamount = cardamount + amount;
} else if (checkedId == R.id.cash1) {
cashamount = cashamount + amount;
} else if (checkedId == R.id.cash2) {
cashamount = cashamount - amount;
} else if (checkedId == R.id.card2) {
cardamount = cardamount - amount;
}
}
});
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView cash = (TextView) findViewById(R.id.amountcash);
TextView card = (TextView) findViewById(R.id.amountcard);
TextView wallet = (TextView) findViewById(R.id.amountwallet);
cash.setText("Amount in Cash : RS. " + cashamount);
card.setText("Amount in Card : RS. " + cardamount);
totalamount = cashamount + cashamount;
wallet.setText("Total Amount in Wallet : RS. " + totalamount);
}
});
}
}
**Whenever i open the app it crashes i don't what is error please someone help me. i am new to android. In this app i have used four radio buttons for add the amount and subtracting the amount. **
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
public class teste extends AppCompatActivity {
int cashamount = 0;
int cardamount = 0;
int totalamount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.iuiu);
EditText et = (EditText) findViewById(R.id.inputamount);
final String amount = (et.getText().toString());
RadioGroup rg = (RadioGroup) findViewById(R.id.rgroup);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.card1) {
cardamount = Integer.parseInt(cardamount + amount);
} else if (checkedId == R.id.cash1) {
cashamount = Integer.parseInt(cashamount + amount);
} else if (checkedId == R.id.cash2) {
cashamount -= Integer.parseInt(amount);
} else if (checkedId == R.id.card2) {
cardamount -= Integer.parseInt(amount);
}
}
});
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView cash = (TextView) findViewById(R.id.amountcash);
TextView card = (TextView) findViewById(R.id.amountcard);
TextView wallet = (TextView) findViewById(R.id.amountwallet);
cash.setText("Amount in Cash : RS. " + cashamount);
card.setText("Amount in Card : RS. " + cardamount);
totalamount = cashamount + cashamount;
wallet.setText("Total Amount in Wallet : RS. " + totalamount);
}
});
}
}
try the above code your problem was here
final int amount = Integer.parseInt(et.getText().toString());

Crash on creating a list size >1 to pass into list view (Index out of bounds)

Im trying to create a dice rolling tool as part of a larger application. However if i try to roll more than 1 dice in my dice roll function the application crashes. Howver as im new to Java i cant seem to find the cause of the index out of bounds error.
DiceActvity.Java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import java.util.ArrayList;
import java.util.List;
public class DiceActivity extends AppCompatActivity
{
ListView LVDiceList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dice);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Radio button
final RadioButton rbGreater = (RadioButton) findViewById(R.id.greaterThanRadioB);
final RadioButton rbLess = (RadioButton) findViewById(R.id.lessThanRadioB);
//Edit boxes
final EditText txtDiceType = (EditText) findViewById(R.id.diceTypeEdTxt);
final EditText txtNumberDice = (EditText) findViewById(R.id.numDiceEdTxt);
final EditText txtFilterNum = (EditText) findViewById(R.id.filterNumEdTxt);
//Buttons
Button btnRoll = (Button) findViewById(R.id.rollButton);
Button btnDiscard = (Button) findViewById(R.id.discardButton);
//Display Array
final List<Integer> diceList = new ArrayList<Integer>(10);
//Array Adapter
final ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item, diceList);
//Set adapter
LVDiceList = (ListView) findViewById(R.id.diceResultListV);
LVDiceList.setAdapter(adapter);
//Roll the dice
btnRoll.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Hide soft keyboard
Utils.hideKeyboard(DiceActivity.this);
//Validation of fields
//If both fields >0
if (Integer.valueOf(txtDiceType.getText().toString()) > 0 && Integer.valueOf(txtNumberDice.getText().toString()) > 0)
{
int number = Integer.valueOf(txtNumberDice.getText().toString());
int sides = Integer.valueOf(txtDiceType.getText().toString());
//Populate array
for (int i=0;i <number; i++)
{
diceList.add(i, rollDice(sides,number).get(i));
}
//Update the list view
adapter.notifyDataSetChanged();
}
return;
}
});
//Clear the list of results
btnDiscard.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
diceList.clear();
adapter.notifyDataSetChanged();
}
});
//Radio Button Validation
rbGreater.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(rbGreater.isChecked() == true)
{
rbLess.setChecked(false);
}
}
});
rbLess.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(rbLess.isChecked() == true)
{
rbGreater.setChecked(false);
};
}
});
}
//Returns a list of rolled dice results
private List<Integer> rollDice(int chance, int amount)
{
final List<Integer> rollArray = new ArrayList<Integer>(amount);
int result;
//Gives a random number between 1 and X,Y number of times
{
//BASE Equation||Min + (int)(Math.random() * ((Max - Min) + 1))
//1 = minimum roll
result = 1 + (int) (Math.random() * ((chance - 1) + 1));
rollArray.add(result);
}
return rollArray;
}
}
content_dice.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="garethgriffiths.tabletopcompanion.DiceActivity"
tools:showIn="#layout/activity_dice">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/textView_NumDice"
android:id="#+id/numDiceTextV"
android:layout_alignBottom="#+id/numDiceEdTxt"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:textSize="25dp"
android:textStyle="bold"
android:textAlignment="gravity"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="4"
android:id="#+id/numDiceEdTxt"
android:maxLength="3"
android:text="#string/edText_NumDice"
android:gravity="right"
android:selectAllOnFocus="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/numDiceTextV"
android:layout_toEndOf="#+id/numDiceTextV"
android:numeric="integer"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/textView_DiceType"
android:id="#+id/diceTypeTextV"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/numDiceTextV"
android:layout_alignBottom="#+id/diceTypeEdTxt"
android:layout_toLeftOf="#+id/diceTypeEdTxt"
android:layout_toStartOf="#+id/diceTypeEdTxt"
android:textSize="25dp"
android:textStyle="bold"
android:textAlignment="gravity"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="4"
android:id="#+id/diceTypeEdTxt"
android:maxLength="2"
android:text="#string/edText_DiceType"
android:layout_below="#+id/numDiceEdTxt"
android:layout_alignLeft="#+id/numDiceEdTxt"
android:layout_alignStart="#+id/numDiceEdTxt"
android:gravity="right"
android:selectAllOnFocus="true"
android:numeric="integer"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radioB_LessThan"
android:id="#+id/lessThanRadioB"
android:layout_above="#+id/discardButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="36dp"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radioB_GreaterThan"
android:id="#+id/greaterThanRadioB"
android:layout_alignTop="#+id/lessThanRadioB"
android:layout_toRightOf="#+id/lessThanRadioB"
android:layout_toEndOf="#+id/lessThanRadioB"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="4"
android:maxLength="3"
android:id="#+id/filterNumEdTxt"
android:layout_alignTop="#+id/greaterThanRadioB"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:text="#string/edText_NumFilter"
android:gravity="center"
android:selectAllOnFocus="true"
android:numeric="integer"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_Discard"
android:id="#+id/discardButton"
android:layout_alignTop="#+id/rollButton"
android:layout_toLeftOf="#+id/rollButton"
android:layout_toStartOf="#+id/rollButton"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_Roll"
android:id="#+id/rollButton"
android:layout_marginTop="108dp"
android:layout_below="#+id/diceTypeTextV"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/diceResultListV"
android:scrollIndicators="right"
android:visibility="visible"
android:layout_below="#+id/discardButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
Heres a small Class used to hide softkeyboard thats called in DiceActivity
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
/**
* http://stackoverflow.com/questions/1109022/close-hide-the-android-soft-keyboard
* Used to close soft keyboard
*/
public class Utils
{
public static void hideKeyboard(Activity activity)
{
// Check if no view has focus:
View view = activity.getCurrentFocus();
if (view != null)
{
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
Your method private List<Integer> rollDice(int chance, int amount) returns a list of Integer. And according to your comment inside the method it should have multiple numbers in it.
But this method always returns only one number.
Now you invoke this method here:
for (int i=0;i <number; i++)
{
diceList.add(i, rollDice(sides,number).get(i));
}
You are invoking this method in a loop. Storing the results in a NEW list.
You get an exception because in the second loop get(i) is 1 and there is only 1 entry in this list on index 0.
To correct this is should read: .get(0)
Also this kind of implementation is very messy. Please take a paper and a pencil to figure it out.

Moving TextView Box made my android app crash

I have had this problem crop up a few times and I can't figure out why it should happen. What happened was after moving some stuff around my TextView box ended up on top of an EditText box, which is no good. So I went and moved the TextView box to the bottom of the screen. When I did that, the app would crash when I tried to access the piggybank. However, if I move the TextView box up to the top again, it works fine.. I really don't get it. Anyways, this is the error that I got
06-22 09:06:41.928: E/AndroidRuntime(10958): java.lang.RuntimeException: Unable to
start activity ComponentInfo{net.finalexam/net.finalexam.Piggy}:
java.lang.ClassCastException: android.widget.RadioButton
This is piggy xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/piggy" >
<EditText
android:id="#+id/txtQuarters"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="27dp"
android:ems="10"
android:hint="Number of quarters"
android:inputType="number" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/txtDimes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtQuarters"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Number of dimes"
android:inputType="number" />
<EditText
android:id="#+id/txtNickles"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtDimes"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Number of nickles"
android:inputType="number" />
<EditText
android:id="#+id/txtPennies"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtNickles"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Number of pennies"
android:inputType="number" />
<EditText
android:id="#+id/txtDollars"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtPennies"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Number of Dollars"
android:inputType="number" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtDollars"
android:layout_centerHorizontal="true" >
<RadioButton
android:id="#+id/radAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Add" />
<RadioButton
android:id="#+id/radSubtract"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subtract" />
</RadioGroup>
<Button
android:id="#+id/btnCalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioGroup1"
android:layout_centerHorizontal="true"
android:text="Calculate" />
<TextView
android:id="#+id/txtResults"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnCalculate"
android:layout_centerHorizontal="true"
android:layout_marginTop="27dp"
android:textSize="40sp" android:textStyle="bold" android:textColor="#000000"/>
</RelativeLayout>
This is the Piggy Java file
package net.finalexam;
import java.text.DecimalFormat;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class Piggy extends Activity
{
double quartersValue = .25;
double dimesValue = .10;
double nicklesValue = .05;
double penniesValue = .01;
double dollarsValue = 1;
double quartersMoney;
double dollarsMoney;
double dimesMoney;
double nicklesMoney;
double penniesMoney;
double totalMoney;
double newTotalMoney;
double oldTotalMoney = 0;
int numberOfQuarters;
int numberOfDimes;
int numberOfNickles;
int numberOfPennies;
int numberOfDollars;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.piggybank);
final EditText quarters = (EditText) findViewById(R.id.txtQuarters);
final EditText dimes = (EditText) findViewById(R.id.txtDimes);
final EditText nickles = (EditText) findViewById(R.id.txtNickles);
final EditText pennies = (EditText) findViewById(R.id.txtPennies);
final EditText dollars = (EditText) findViewById(R.id.txtDollars);
Button calculate = (Button) findViewById(R.id.btnCalculate);
final TextView results = ((TextView) findViewById(R.id.txtResults));
final RadioButton add = (RadioButton) findViewById(R.id.radAdd);
final RadioButton subtract = (RadioButton) findViewById(R.id.radSubtract);
calculate.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if (quarters.getText().toString().equals(""))
{
numberOfQuarters = 0;
}
else
{
numberOfQuarters = Integer.parseInt(quarters.getText().toString());
}
if (dimes.getText().toString().equals(""))
{
numberOfDimes = 0;
}
else
{
numberOfDimes = Integer.parseInt(dimes.getText().toString());
}
if (nickles.getText().toString().equals(""))
{
numberOfNickles = 0;
}
else
{
numberOfNickles = Integer.parseInt(nickles.getText().toString());
}
if (pennies.getText().toString().equals(""))
{
numberOfPennies = 0;
}
else
{
numberOfPennies = Integer.parseInt(pennies.getText().toString());
}
if (dollars.getText().toString().equals(""))
{
numberOfDollars = 0;
}
else
{
numberOfDollars = Integer.parseInt(dollars.getText().toString());
}
quartersMoney = numberOfQuarters * quartersValue;
dimesMoney = numberOfDimes * dimesValue;
nicklesMoney = numberOfNickles * nicklesValue;
penniesMoney = numberOfPennies * penniesValue;
dollarsMoney = numberOfDollars;
totalMoney = quartersMoney + dimesMoney + nicklesMoney + penniesMoney + dollarsMoney;
DecimalFormat currency = new DecimalFormat("$###,###.##");
if (add.isChecked())
{
if (totalMoney > 0)
{
newTotalMoney = oldTotalMoney + totalMoney;
oldTotalMoney = newTotalMoney;
results.setText(currency.format(newTotalMoney));
}
else
{
Toast.makeText(Piggy.this, "You need to do more chores!!", Toast.LENGTH_LONG).show();
}
}
if (subtract.isChecked())
{
newTotalMoney = oldTotalMoney - totalMoney;
}
if (newTotalMoney > 0)
{
oldTotalMoney = newTotalMoney;
results.setText(currency.format(newTotalMoney));
}
else
{
Toast.makeText(Piggy.this, "Save more money kido!!", Toast.LENGTH_LONG).show();
};
}
});
}
}
I have searched for an answer but they all seem to be slightly different situations. Any ideas? Thanks. And like I said, this works fine if the TextView box is overlapping the quarters EditText box.
Edit 1 Here is the screen before the piggy bank
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"
>
<ImageView
android:id="#+id/ic_launcher_money"
android:layout_width="100px"
android:layout_height="100px"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="2px"
android:src="#drawable/ic_launcher_money"></ImageView>
<TextView
android:id="#+id/bankses"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/bankses"
android:textSize="25sp">
</TextView>
</LinearLayout>
Main.java
package net.finalexam;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Main extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
String[] banks ={"Piggy Bank","Adult Bank"};
setListAdapter(new ArrayAdapter<String>(this,R.layout.main, R.id.bankses, banks));
}
protected void onListItemClick(ListView l, View v, int position, long id){
switch(position){
case 0:
startActivity(new Intent(Main.this,Piggy.class));
break;
case 1:
startActivity(new Intent(Main.this,Adultbank.class));
break;
}
}
}
Try cleaning your project on Eclipse. It often fixes that kind of problems.

Categories