Trying to hide the menu item when there are no views - java

I'm trying to build an app that generates buttons dynamically per floatActionButton click. This aspect works fine. But if there are no views, there shouldn't be a delete menu item on the action bar. At the start of the app, since there are no items, there is no menu item but I need the menu item to show up once I start adding views. I tried to work it with if statements but it still did not work.
This is my code:
public class MainActivity extends AppCompatActivity {
int counter = 0;
FloatingActionButton addingSemester;
Button semesterButton;
LinearLayout semesterLayout;
GridLayout semesterGridLayout;
RelativeLayout relativeLayout;
LinearLayout.LayoutParams portraitLayoutParams = new LinearLayout.LayoutParams(
AppBarLayout.LayoutParams.MATCH_PARENT,
AppBarLayout.LayoutParams.WRAP_CONTENT);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addingSemester = (FloatingActionButton) findViewById(R.id.addActionButton);
semesterLayout = (LinearLayout) findViewById(R.id.main_layout);
semesterGridLayout = (GridLayout)findViewById(R.id.semester_grid_layout);
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
relativeLayout = (RelativeLayout)findViewById(R.id.relativeLayout);
semesterButton = new Button(MainActivity.this);
if (savedInstanceState != null) {
counter = savedInstanceState.getInt("counter");
for(int i = 0; i < counter; i++) {
addSemesterButton(i);
}
}
}
public void addSemesterButton(int id) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
double width = (size.x)/3;
semesterButton = new Button(MainActivity.this);
semesterButton.setId(id + 1);
semesterButton.setText("Semester " + (id + 1));
semesterButton.setBackgroundColor(getColor(R.color.colorPrimary));
semesterButton.setTextColor(Color.WHITE);
portraitLayoutParams.setMargins(24, 24, 24, 24);
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.setMargins(24, 24, 24, 24);
params.width = (int) width;
params.height = GridLayout.LayoutParams.WRAP_CONTENT;
semesterButton.setLayoutParams(params);
semesterGridLayout.addView(semesterButton);
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.addView(semesterButton);
semesterButton.setLayoutParams(portraitLayoutParams);
}
setOnLongClickListenerForSemesterButton();
}
public void addTextView(int id){
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
double width = (size.x);
TextView instructionsPromptTextView = new TextView(MainActivity.this);
instructionsPromptTextView.setId(id);
instructionsPromptTextView.setText(R.string.click_the_button_to_add_semesters);
instructionsPromptTextView.setTextSize((float)width);
instructionsPromptTextView.setVisibility(View.VISIBLE);
instructionsPromptTextView.setBackgroundColor(Color.BLACK);
relativeLayout.addView(instructionsPromptTextView);
if(id == 0){
instructionsPromptTextView.setVisibility(View.INVISIBLE);
}
}
public void onFloatActionButtonClick(View view) {
if (counter < 8) {
addSemesterButton(counter);
counter++;
setOnLongClickListenerForSemesterButton();
} else if (counter == 8) {
Toast.makeText(MainActivity.this, "You cannot add more than 8 semesters", Toast.LENGTH_SHORT).show();
} else if (counter == 0){
addTextView(counter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.delete);
if(counter == 0){
item.setVisible(false);
}
if(counter > 0){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main, menu);
item.setVisible(true);
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.delete) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete everything?")
.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterGridLayout.removeAllViews();
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.removeAllViews();
}
counter = 0;
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("counter", counter);
super.onSaveInstanceState(savedInstanceState);
}
private void setOnLongClickListenerForSemesterButton() {
semesterButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final Button b = (Button) v;
b.setTag(b.getText().toString());
b.setBackgroundColor(Color.RED);
b.setText("Delete");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Delete entry");
builder.setMessage("Are you sure you want to delete this entry?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterGridLayout.removeView(b);
for (int i = 0; i < semesterGridLayout.getChildCount(); i++) {
((Button) semesterGridLayout.getChildAt(i)).setText("Semester " + (i + 1));
}
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.removeView(b);
for (int i = 0; i < semesterLayout.getChildCount(); i++) {
((Button) semesterLayout.getChildAt(i)).setText("Semester " + (i + 1));
}
}
counter--;
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
b.cancelLongPress();
b.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
b.setText(b.getTag().toString());
dialog.cancel();
}
});
builder.show();
return true;
}
});
}
}
EDIT
This is the stacktrace
FATAL EXCEPTION: main
Process: myapp.onur.journeygpacalculator, PID: 22605
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.view.View$DeclaredOnClickListener.onClick(View.java:4711)
at android.view.View.performClick(View.java:5623)
at android.view.View$PerformClick.run(View.java:22433)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6247)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.view.View$DeclaredOnClickListener.onClick(View.java:4706)
at android.view.View.performClick(View.java:5623) 
at android.view.View$PerformClick.run(View.java:22433) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6247) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762) 
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.add(int, int, int, java.lang.CharSequence)' on a null object reference
at android.view.MenuInflater$MenuState.addItem(MenuInflater.java:493)
at android.view.MenuInflater.parseMenu(MenuInflater.java:190)
at android.view.MenuInflater.inflate(MenuInflater.java:111)
at android.support.v7.view.SupportMenuInflater.inflate(SupportMenuInflater.java:113)
at myapp.onur.journeygpacalculator.MainActivity.inflateMenu(MainActivity.java:182)
at myapp.onur.journeygpacalculator.MainActivity.onFloatActionButtonClick(MainActivity.java:168)

Instead of setting it invisible only in onCreateOptionsMenu set it in your action button click too like below
MenuItem item;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main, menu);
item = menu.findItem(R.id.delete);
item.setVisible(false);
return super.onCreateOptionsMenu(menu);
}
public void onFloatActionButtonClick(View view) {
if (counter < 8) {
addSemesterButton(counter);
counter++;
setOnLongClickListenerForSemesterButton();
item.setVisible(true);
} else if (counter == 8) {
Toast.makeText(MainActivity.this, "You cannot add more than 8 semesters", Toast.LENGTH_SHORT).show();
item.setVisible(true);
} else if (counter == 0){
addTextView(counter);
item.setVisible(false);
}
}

1. Update onCreateOptionsMenu() as below, to hide delete option when app starts first:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
itemDelete = menu.findItem(R.id.delete);
// Required to hide delete option when app starts first
itemDelete.setVisible(false);
return true;
}
2. Add below method to update the state of delete option.
public void updateOptionMenu() {
if (counter > 0)
item.setVisible(true);
else
item.setVisible(false);
}
3. Call updateOptionMenu() method from all places where the counter value changes like: onFloatActionButtonClick() and AlertDialog's onClick() methods.
Here is the full code:
public class MainActivity extends AppCompatActivity {
MenuItem itemDelete;
int counter = 0;
FloatingActionButton addingSemester;
Button semesterButton;
LinearLayout semesterLayout;
GridLayout semesterGridLayout;
RelativeLayout relativeLayout;
LinearLayout.LayoutParams portraitLayoutParams = new LinearLayout.LayoutParams(
AppBarLayout.LayoutParams.MATCH_PARENT,
AppBarLayout.LayoutParams.WRAP_CONTENT);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addingSemester = (FloatingActionButton) findViewById(R.id.addActionButton);
semesterLayout = (LinearLayout) findViewById(R.id.main_layout);
semesterGridLayout = (GridLayout)findViewById(R.id.semester_grid_layout);
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
relativeLayout = (RelativeLayout)findViewById(R.id.relativeLayout);
semesterButton = new Button(MainActivity.this);
if (savedInstanceState != null) {
counter = savedInstanceState.getInt("counter");
for(int i = 0; i < counter; i++) {
addSemesterButton(i);
}
}
addTextView(counter);
}
public void addSemesterButton(int id) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
double width = (size.x)/3;
semesterButton = new Button(MainActivity.this);
semesterButton.setId(id + 1);
semesterButton.setText("Semester " + (id + 1));
semesterButton.setBackgroundColor(getColor(R.color.colorPrimary));
semesterButton.setTextColor(Color.WHITE);
portraitLayoutParams.setMargins(24, 24, 24, 24);
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.setMargins(24, 24, 24, 24);
params.width = (int) width;
params.height = GridLayout.LayoutParams.WRAP_CONTENT;
semesterButton.setLayoutParams(params);
semesterGridLayout.addView(semesterButton);
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.addView(semesterButton);
semesterButton.setLayoutParams(portraitLayoutParams);
}
setOnLongClickListenerForSemesterButton();
}
public void addTextView(int id){
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
double width = (size.x);
TextView instructionsPromptTextView = new TextView(MainActivity.this);
instructionsPromptTextView.setId(id);
instructionsPromptTextView.setText(R.string.click_the_button_to_add_semesters);
instructionsPromptTextView.setTextSize((float)width);
instructionsPromptTextView.setVisibility(View.VISIBLE);
instructionsPromptTextView.setBackgroundColor(Color.BLACK);
relativeLayout.addView(instructionsPromptTextView);
/*
if(id == 0){
instructionsPromptTextView.setVisibility(View.INVISIBLE);
}*/
}
public void onFloatActionButtonClick(View view) {
if (counter < 8) {
addSemesterButton(counter);
counter++;
setOnLongClickListenerForSemesterButton();
// Required to show delete option
updateOptionMenu();
} else if (counter == 8) {
Toast.makeText(MainActivity.this, "You cannot add more than 8 semesters", Toast.LENGTH_SHORT).show();
}
// Will never be called because counter == 0 will be consumed by first if condition
/*
else if (counter == 0){
addTextView(counter); // Move it to onCreate()
}*/
}
public void updateOptionMenu() {
if (counter > 0)
item.setVisible(true);
else
item.setVisible(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
itemDelete = menu.findItem(R.id.delete);
// Required to hide delete option when app starts first
itemDelete.setVisible(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.delete) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete everything?")
.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterGridLayout.removeAllViews();
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.removeAllViews();
}
counter = 0;
updateOptionMenu(); // Required to hide option item when all views are removed
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("counter", counter);
super.onSaveInstanceState(savedInstanceState);
}
private void setOnLongClickListenerForSemesterButton() {
semesterButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final Button b = (Button) v;
b.setTag(b.getText().toString());
b.setBackgroundColor(Color.RED);
b.setText("Delete");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Delete entry");
builder.setMessage("Are you sure you want to delete this entry?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterGridLayout.removeView(b);
for (int i = 0; i < semesterGridLayout.getChildCount(); i++) {
((Button) semesterGridLayout.getChildAt(i)).setText("Semester " + (i + 1));
}
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.removeView(b);
for (int i = 0; i < semesterLayout.getChildCount(); i++) {
((Button) semesterLayout.getChildAt(i)).setText("Semester " + (i + 1));
}
}
counter--;
updateOptionMenu(); // Required to hide delete item if this button is last button to be removed
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
b.cancelLongPress();
b.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
b.setText(b.getTag().toString());
dialog.cancel();
}
});
builder.show();
return true;
}
});
}
}
Hope this will help~

Related

setOnCheckedChangeListener isn't working when used with a dynamic radioGroup

I have a radioGroup that is populated dynamically since I don't know how many elements are going to be within it (it is being populated by a database). The problem is when I use setOnCheckedChangeListener with it, it won't work at all. I tried creating a toast to see if it's even getting called, and the toast didn't even fire!
Here is a copy of the class that contains the radio group as well as the setOnCheckedChange method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_add_payment, container, false);
addPayment = v.findViewById(R.id.btn_add_payment);
totalPaymentTV = v.findViewById(R.id.tv_total_payment);
radioGroup0 = v.findViewById(R.id.rg_select_subject);
datePickerTV = v.findViewById(R.id.tv_date_picker);
radioGroup = v.findViewById(R.id.rg_add_payment);
numberPicker = v.findViewById(R.id.numberPicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(10);
hoursTeached = 0;
teacherFee = 0;
date = new String();
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
Toast.makeText(getContext(),"hello ",Toast.LENGTH_SHORT).show();
schoolViewModel.getTeacherByID(i).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
#Override
public void onChanged(Teacher teacher) {
teacherFee = teacher.getFee();
totalPaymentTV.setText(teacherFee * hoursTeached + " DA");
}
});
}
});
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int hours) {
if (!(radioGroup.getCheckedRadioButtonId() == -1)) {
schoolViewModel.getTeacherByID(radioGroup.getCheckedRadioButtonId()).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
#Override
public void onChanged(Teacher teacher) {
teacherFee = teacher.getFee();
hoursTeached = hours;
totalPaymentTV.setText(teacherFee * hours + " DA");
}
});
}
}
});
datePickerTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pickADate();
}
});
schoolViewModel = new ViewModelProvider(this).get(SchoolViewModel.class);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
schoolViewModel.getSingleTeacherWithSubjects(i).observe(getViewLifecycleOwner(), new Observer<TeacherWithSubjects>() {
#Override
public void onChanged(TeacherWithSubjects teacherWithSubjects) {
if (teacherWithSubjects.subjects.size() > 1) {
openDialog(teacherWithSubjects.subjects, radioGroup0);
} else {
subject = teacherWithSubjects.subjects.get(0);
}
}
});
}
});
schoolViewModel.getAllTeachers().observe(getViewLifecycleOwner(), new Observer<List<Teacher>>() {
#Override
public void onChanged(List<Teacher> teachers) {
addRadioButtons(teachers, radioGroup);
}
});
addPayment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(getContext(), "Choose a Teacher!!", Toast.LENGTH_SHORT).show();
return;
}
if (subject == null) {
Toast.makeText(getContext(), "Choose a Subject", Toast.LENGTH_SHORT).show();
return;
}
if (date.isEmpty()) {
Toast.makeText(getContext(), "Pick a Date", Toast.LENGTH_SHORT).show();
return;
}
if(hoursTeached == 0){
Toast.makeText(getContext(),"Choose how many hours have been teached!!",Toast.LENGTH_SHORT).show();
return;
}
SubjectTeacherCrossRef crossRef = new SubjectTeacherCrossRef(subject.getSubjectName(),radioGroup.getCheckedRadioButtonId());
int totalPayment = (hoursTeached*teacherFee);
schoolViewModel.addPayment(new Payment(crossRef,date,hoursTeached,totalPayment));
}
});
return v;
}
private void addRadioButtons(List<Teacher> teachers, RadioGroup radioGroup) {
for (Teacher i : teachers) {
//instantiate...
RadioButton radioButton = new RadioButton(getContext());
//set the values that you would otherwise hardcode in the xml...
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
params.bottomMargin = 25;
params.leftMargin = 20;
params.rightMargin = 20;
params.topMargin = 20;
radioButton.setLayoutParams(params);
//label the button...
radioButton.setBackground(new ColorDrawable(Color.TRANSPARENT));
radioButton.setMinWidth(250);
radioButton.setBackgroundResource(R.drawable.custom_checkbox);
radioButton.setElevation(16);
radioButton.setGravity(Gravity.CENTER);
radioButton.setText(i.getTeacherName());
radioButton.setPadding(50, 100, 50, 100);
radioButton.setButtonDrawable(R.drawable.custom_checkbox);
radioButton.setId(i.getTeacherId());
//add it to the group.
radioGroup.addView(radioButton);
}
}
void openDialog(List<Subject> subjects, RadioGroup radioGroup) {
dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.choose_teached_subject_dialog);
dialog.setCancelable(false);
radioGroup = dialog.findViewById(R.id.rg_select_subject);
Button confirmSubject = dialog.findViewById(R.id.btn_choose_subject);
Button cancelSubject = dialog.findViewById(R.id.btn_dont_choose_subject);
//populate the checkBox
for (int i = 0; i < subjects.size(); i++) {
RadioButton radioButton1 = new RadioButton(dialog.getContext());
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
params.bottomMargin = 25;
params.leftMargin = 20;
params.rightMargin = 20;
params.topMargin = 20;
radioButton1.setLayoutParams(params);
radioButton1.setBackground(new ColorDrawable(Color.TRANSPARENT));
radioButton1.setMinWidth(250);
radioButton1.setBackgroundResource(R.drawable.custom_checkbox);
radioButton1.setElevation(16);
radioButton1.setGravity(Gravity.CENTER);
radioButton1.setId(i);
radioButton1.setText(subjects.get(i).getSubjectName());
radioButton1.setPadding(50, 100, 50, 100);
radioButton1.setButtonDrawable(R.drawable.custom_checkbox);
//add it to the group.
radioGroup.addView(radioButton1);
}
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
dummySubject = subjects.get(i);
Toast.makeText(getContext(), dummySubject.getSubjectName(), Toast.LENGTH_SHORT).show();
}
});
confirmSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (dummySubject == null) {
Toast.makeText(getContext(), "Choose A Subject", Toast.LENGTH_SHORT).show();
} else {
subject = dummySubject;
dummySubject = null;
dialog.dismiss();
}
}
});
cancelSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dummySubject = null;
dialog.dismiss();
}
});
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setGravity(Gravity.CENTER);
dialog.show();
}
void pickADate() {
DatePickerDialog datePickerDialog = new DatePickerDialog(
getContext(), this,
Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.MONTH),
Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
);
datePickerDialog.show();
}
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
date = day + "/" + (month + 1) + "/" + year;
datePickerTV.setText(date);
}
}

radioGroup.setOnCheckedChangeListener isn't working properly

i have a problem with radioGroup.setOnCheckedChangeListener and i dont know to fix it
I have a fragment that is used to gather data and create a new instance of payment class.
the problem that i am facing is when i try to reselect the teacher after choosing how many hours have been teached the total doesnt get updated, i know that the code responsible for updating the total is tied to the spinner but i tried to create an independent "setOnCheckedChangeListener" on the radio group but it still fails to update the total.
here is a screenshot of the UI so u can better understand what am talking about
here is the code for java class responsible for this part :
public class addPaymentFragment extends Fragment implements DatePickerDialog.OnDateSetListener {
private RadioGroup radioGroup;
private RadioButton radioButton;
private SchoolViewModel schoolViewModel;
private NumberPicker numberPicker;
private Button addPayment;
private Subject dummySubject, subject;
private Dialog dialog;
private RadioGroup radioGroup0;
private TextView datePickerTV, totalPaymentTV;
private String date;
private int hoursTeached, teacherFee;
private Payment payment;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_add_payment, container, false);
addPayment = v.findViewById(R.id.btn_add_payment);
totalPaymentTV = v.findViewById(R.id.tv_total_payment);
radioGroup0 = v.findViewById(R.id.rg_select_subject);
datePickerTV = v.findViewById(R.id.tv_date_picker);
radioGroup = v.findViewById(R.id.rg_add_payment);
numberPicker = v.findViewById(R.id.numberPicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(10);
hoursTeached = 0;
teacherFee = 0;
date = new String();
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
schoolViewModel.getTeacherByID(i).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
#Override
public void onChanged(Teacher teacher) {
teacherFee = teacher.getFee();
totalPaymentTV.setText(teacherFee * hoursTeached + " DA");
}
});
}
});
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int hours) {
if (!(radioGroup.getCheckedRadioButtonId() == -1)) {
schoolViewModel.getTeacherByID(radioGroup.getCheckedRadioButtonId()).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
#Override
public void onChanged(Teacher teacher) {
teacherFee = teacher.getFee();
hoursTeached = hours;
totalPaymentTV.setText(teacherFee * hours + " DA");
}
});
}
}
});
datePickerTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pickADate();
}
});
schoolViewModel = new ViewModelProvider(this).get(SchoolViewModel.class);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
schoolViewModel.getSingleTeacherWithSubjects(i).observe(getViewLifecycleOwner(), new Observer<TeacherWithSubjects>() {
#Override
public void onChanged(TeacherWithSubjects teacherWithSubjects) {
if (teacherWithSubjects.subjects.size() > 1) {
openDialog(teacherWithSubjects.subjects, radioGroup0);
} else {
subject = teacherWithSubjects.subjects.get(0);
}
}
});
}
});
schoolViewModel.getAllTeachers().observe(getViewLifecycleOwner(), new Observer<List<Teacher>>() {
#Override
public void onChanged(List<Teacher> teachers) {
addRadioButtons(teachers, radioGroup);
}
});
addPayment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(getContext(), "Choose a Teacher!!", Toast.LENGTH_SHORT).show();
return;
}
if (subject == null) {
Toast.makeText(getContext(), "Choose a Subject", Toast.LENGTH_SHORT).show();
return;
}
if (date.isEmpty()) {
Toast.makeText(getContext(), "Pick a Date", Toast.LENGTH_SHORT).show();
return;
}
if(hoursTeached == 0){
Toast.makeText(getContext(),"Choose how many hours have been teached!!",Toast.LENGTH_SHORT).show();
return;
}
SubjectTeacherCrossRef crossRef = new SubjectTeacherCrossRef(subject.getSubjectName(),radioGroup.getCheckedRadioButtonId());
int totalPayment = hoursTeached*teacherFee;
payment = new Payment(crossRef,date,totalPayment);
}
});
return v;
}
private void addRadioButtons(List<Teacher> teachers, RadioGroup radioGroup) {
for (Teacher i : teachers) {
//instantiate...
RadioButton radioButton = new RadioButton(getContext());
//set the values that you would otherwise hardcode in the xml...
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
params.bottomMargin = 25;
params.leftMargin = 20;
params.rightMargin = 20;
params.topMargin = 20;
radioButton.setLayoutParams(params);
//label the button...
radioButton.setBackground(new ColorDrawable(Color.TRANSPARENT));
radioButton.setMinWidth(250);
radioButton.setBackgroundResource(R.drawable.custom_checkbox);
radioButton.setElevation(16);
radioButton.setGravity(Gravity.CENTER);
radioButton.setText(i.getTeacherName());
radioButton.setPadding(50, 100, 50, 100);
radioButton.setButtonDrawable(R.drawable.custom_checkbox);
radioButton.setId(i.getTeacherId());
//add it to the group.
radioGroup.addView(radioButton);
}
}
void openDialog(List<Subject> subjects, RadioGroup radioGroup) {
dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.choose_teached_subject_dialog);
dialog.setCancelable(false);
radioGroup = dialog.findViewById(R.id.rg_select_subject);
Button confirmSubject = dialog.findViewById(R.id.btn_choose_subject);
Button cancelSubject = dialog.findViewById(R.id.btn_dont_choose_subject);
//populate the checkBox
for (int i = 0; i < subjects.size(); i++) {
RadioButton radioButton1 = new RadioButton(dialog.getContext());
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
params.bottomMargin = 25;
params.leftMargin = 20;
params.rightMargin = 20;
params.topMargin = 20;
radioButton1.setLayoutParams(params);
radioButton1.setBackground(new ColorDrawable(Color.TRANSPARENT));
radioButton1.setMinWidth(250);
radioButton1.setBackgroundResource(R.drawable.custom_checkbox);
radioButton1.setElevation(16);
radioButton1.setGravity(Gravity.CENTER);
radioButton1.setId(i);
radioButton1.setText(subjects.get(i).getSubjectName());
radioButton1.setPadding(50, 100, 50, 100);
radioButton1.setButtonDrawable(R.drawable.custom_checkbox);
//add it to the group.
radioGroup.addView(radioButton1);
}
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
dummySubject = subjects.get(i);
Toast.makeText(getContext(), dummySubject.getSubjectName(), Toast.LENGTH_SHORT).show();
}
});
confirmSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (dummySubject == null) {
Toast.makeText(getContext(), "Choose A Subject", Toast.LENGTH_SHORT).show();
} else {
subject = dummySubject;
dummySubject = null;
dialog.dismiss();
}
}
});
cancelSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dummySubject = null;
dialog.dismiss();
}
});
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setGravity(Gravity.CENTER);
dialog.show();
}
void pickADate() {
DatePickerDialog datePickerDialog = new DatePickerDialog(
getContext(), this,
Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.MONTH),
Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
);
datePickerDialog.show();
}
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
date = day + "/" + (month + 1) + "/" + year;
datePickerTV.setText(date);
}
}
Sorry if my question is so clear and please let me know if i need to provide any more information and thanks!

How to record dynamically generated buttons into the SQLite database

I'm building an app where a user dynamically generates semesters (buttons) through the Java code. Let's say that the user generates about 4 buttons (the user can generate up to 8), I want to store that into the SQLite database I've created. This is my first app ever and likely, my first time using an SQLite database. I went through the SQLite Android tutorials but my app is a bit different compared to the examples they were working with.
What I need help with, is to be able to store the dynamically generated buttons into my database so I have the exact same amount saved next time the app is launched again. I also need to wire the delete (menuItem and alertdialog) function with the onUpgrade.
This is my Mainactivity.java. This is where all my UI generation takes place. Its also my homepage.
public class MainActivity extends AppCompatActivity {
int counter = 0;
FloatingActionButton addingSemester;
Button semesterButton;
LinearLayout semesterLayout;
GridLayout semesterGridLayout;
LinearLayout.LayoutParams portraitLayoutParams = new LinearLayout.LayoutParams(
AppBarLayout.LayoutParams.MATCH_PARENT,
AppBarLayout.LayoutParams.WRAP_CONTENT);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addingSemester = (FloatingActionButton) findViewById(R.id.addActionButton);
semesterLayout = (LinearLayout) findViewById(R.id.main_layout);
semesterGridLayout = (GridLayout) findViewById(R.id.semester_grid_layout);
semesterButton = new Button(MainActivity.this);
if (savedInstanceState != null) {
counter = savedInstanceState.getInt("counter");
for (int i = 0; i < counter; i++) {
addSemesterButton(i);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.delete) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete everything?")
.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
if (semesterGridLayout.getChildCount() > 0) {
semesterGridLayout.removeAllViews();
} else {
Toast.makeText(MainActivity.this, "There is nothing to delete", Toast.LENGTH_SHORT).show();
}
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
if (semesterLayout.getChildCount() > 0) {
semesterLayout.removeAllViews();
} else {
Toast.makeText(MainActivity.this, "There is nothing to delete", Toast.LENGTH_SHORT).show();
}
}
counter = 0;
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
return true;
}
return super.onOptionsItemSelected(item);
}
public void addSemesterButton(int id) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
double width = (size.x) / 3;
semesterButton = new Button(MainActivity.this);
semesterButton.setId(id + 1);
semesterButton.setText("Semester " + (id + 1));
semesterButton.setBackgroundColor(getColor(R.color.colorPrimary));
semesterButton.setTextColor(Color.WHITE);
portraitLayoutParams.setMargins(24, 24, 24, 24);
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.setMargins(24, 24, 24, 24);
params.width = (int) width;
params.height = GridLayout.LayoutParams.WRAP_CONTENT;
semesterButton.setLayoutParams(params);
semesterGridLayout.addView(semesterButton);
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.addView(semesterButton);
semesterButton.setLayoutParams(portraitLayoutParams);
}
setOnLongClickListenerForSemesterButton();
setOnClickListenerForSemesterButton(counter);
}
public void onFloatActionButtonClick(View view) {
if (counter < 8) {
addSemesterButton(counter);
counter++;
setOnLongClickListenerForSemesterButton();
} else if (counter == 8) {
Toast.makeText(MainActivity.this, "You cannot add more than 8 semesters", Toast.LENGTH_SHORT).show();
} else if (counter == 0) {
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("counter", counter);
super.onSaveInstanceState(savedInstanceState);
}
private void setOnClickListenerForSemesterButton(int id){
semesterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SemesterBuilderActivity.class);
intent.putExtra("someKey", 1);
startActivity(intent);
}
});
}
private void setOnLongClickListenerForSemesterButton() {
semesterButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final Button b = (Button) v;
b.setTag(b.getText().toString());
b.setBackgroundColor(Color.RED);
b.setText("Delete");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Delete entry");
builder.setMessage("Are you sure you want to delete this entry?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterGridLayout.removeView(b);
for (int i = 0; i < semesterGridLayout.getChildCount(); i++) {
((Button) semesterGridLayout.getChildAt(i)).setText("Semester " + (i + 1));
}
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.removeView(b);
for (int i = 0; i < semesterLayout.getChildCount(); i++) {
((Button) semesterLayout.getChildAt(i)).setText("Semester " + (i + 1));
}
}
counter--;
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
b.cancelLongPress();
b.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
b.setText(b.getTag().toString());
dialog.cancel();
}
});
builder.show();
return true;
}
});
}
}
This is my Contract class:
public final class SemesterContract {
private SemesterContract(){}
public static final class SemesterEntry implements BaseColumns{
public static final String TABLE_NAME = "semesters";
public static final String _ID = BaseColumns._ID;
public static final String COLUMN_SEMESTER_NAME = "semester";
}
}
And finally this is my database helper:
public class SemesterDBHelper extends SQLiteOpenHelper{
public SemesterDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public static final String DATABASE_NAME = "semesters.db";
public static final int DATABASE_VERSION = 1;
#Override
public void onCreate(SQLiteDatabase db) {
String SQL_CREATE_SEMESTER_TABLE = "CREATE TABLE " + SemesterContract.SemesterEntry.TABLE_NAME + " ("
+ SemesterContract.SemesterEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ SemesterContract.SemesterEntry.COLUMN_SEMESTER_NAME + " TEXT NOT NULL";
db.execSQL(SQL_CREATE_SEMESTER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
I appreciate all of the help.

Android refresh rating bar upon triggeration

I am having some problem when trying to refresh the rating bar after user submitted their rating. So basically I am passing the existing rating amount when certain button on my other Activity was triggered:
viewDtlEventBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Object[] obj = new Object[2];
obj[0] = String.valueOf(eventIDTV.getText());
obj[1] = eventReviewModel;
new GetEventDetailAsyncTask(new GetEventDetailAsyncTask.OnRoutineFinished() {
public void onFinish() {
// Passing whole object with value into another activity
Intent eventDtlIntent = new Intent(context, EventDetailMain.class);
// Pass in a list of rating star together with amount
eventDtlIntent.putExtra("eventPopulateStarObj", populateRatingStar);
context.startActivity(eventDtlIntent);
}
}).execute(obj);
}
});
And I am populating the rating bar when onCreate():
ratingStarList = (ArrayList<EventReview>) i
.getSerializableExtra("eventPopulateStarObj");
public void populateRatingProgressBar() {
int totalStar = 0;
// Get the total amount of rate records
for (int j = 0; j < ratingStarList.size(); j++) {
if (ratingStarList.get(j).getStarAmt() != null) {
totalStar += Integer.parseInt(ratingStarList.get(j)
.getStarAmt());
}
}
txtTotalRate.setText(totalStar + " Ratings for this event");
// Set progress bar based on the each rates
for (int i = 0; i < ratingStarList.size(); i++) {
if (ratingStarList.get(i).getStarAmt() != null) {
if (ratingStarList.get(i).getEventReviewRate().equals("5")) {
pb5Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("4")) {
pb4Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("3")) {
pb3Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("2")) {
pb2Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("1")) {
pb1Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
}
}
}
}
It did populated correctly. However, I not sure how to refresh the rating bar after user submitted their rating. Here is the code when user submit their rating:
public void promptSubmitStar() {
AlertDialog.Builder Dialog = new AlertDialog.Builder(getActivity());
Dialog.setTitle("Confirm Rating");
LayoutInflater li = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View dialogView = li.inflate(R.layout.option_submit_star, null);
txtPromptStarRate = (TextView) dialogView
.findViewById(R.id.txtPromptStarRate);
txtPromptStarRate.setText("Confirm to submit " + starRate
+ " stars for this event?");
Dialog.setView(dialogView);
Dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EventReview eventReviewModel = new EventReview();
eventReviewModel.setEventID(eventID);
eventReviewModel.setEventReviewBy(userID);
eventReviewModel.setEventReviewRate(String.valueOf(starRate));
new CreateEventReviewAsyncTask(context)
.execute(eventReviewModel);
dialog.dismiss();
// Disable the rating bar by setting a touch listener which
// always return true
ratingBar.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View view, MotionEvent event) {
return true;
}
});
}
});
Dialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
Dialog d = Dialog.show();
EventDialogueBox.customizeDialogueBox(context, d);
}
Any ideas? Thanks in advance.
Use setRating(starRate); to programmatically set the rating on the RatingBar.

Fatal runtime error at android.media.audiofx.Equalizer.<init>

I am working on equalier app and no errors in code at all. when I run app on phone it force closes, I logcat and this is result
03-22 02:49:17.945: E/AndroidRuntime(4318): at android.media.audiofx.Equalizer.<init>(Equalizer.java:149)
03-22 02:50:34.796: E/AndroidRuntime(4423): at android.media.audiofx.Equalizer.<init>(Equalizer.java:149)
I tried on android gingerbread kitkat and jellybean
this is the main activity code:
public class MainActivity extends Activity
implements SeekBar.OnSeekBarChangeListener,
CompoundButton.OnCheckedChangeListener,
View.OnClickListener
{
//as usual "define variables"
TextView bass_boost_label = null;
SeekBar bass_boost = null;
CheckBox enabled = null;
Button flat = null;
Button Button1;
Equalizer eq = null;
BassBoost bb = null;
int min_level = 0;
int max_level = 100;
static final int MAX_SLIDERS = 8; // Must match the XML layout
SeekBar sliders[] = new SeekBar[MAX_SLIDERS];
TextView slider_labels[] = new TextView[MAX_SLIDERS];
int num_sliders = 0;
/*=============================================================================
onCreate
=============================================================================*/
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
/*=============================================================================
onCreate
=============================================================================*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//initalize layout
setContentView(R.layout.activity_main);
//initialize the checkbox
enabled = (CheckBox)findViewById(R.id.enabled);
enabled.setOnCheckedChangeListener (this);
//initialize flat button
flat = (Button)findViewById(R.id.flat);
flat.setOnClickListener(this);
Button1 = (Button)findViewById(R.id.button1);
Button1.setOnClickListener(this);
//the seekbars
bass_boost = (SeekBar)findViewById(R.id.bass_boost);
bass_boost.setOnSeekBarChangeListener(this);
bass_boost_label = (TextView) findViewById (R.id.bass_boost_label);
sliders[0] = (SeekBar)findViewById(R.id.slider_1);
slider_labels[0] = (TextView)findViewById(R.id.slider_label_1);
sliders[1] = (SeekBar)findViewById(R.id.slider_2);
slider_labels[1] = (TextView)findViewById(R.id.slider_label_2);
sliders[2] = (SeekBar)findViewById(R.id.slider_3);
slider_labels[2] = (TextView)findViewById(R.id.slider_label_3);
sliders[3] = (SeekBar)findViewById(R.id.slider_4);
slider_labels[3] = (TextView)findViewById(R.id.slider_label_4);
sliders[4] = (SeekBar)findViewById(R.id.slider_5);
slider_labels[4] = (TextView)findViewById(R.id.slider_label_5);
sliders[5] = (SeekBar)findViewById(R.id.slider_6);
slider_labels[5] = (TextView)findViewById(R.id.slider_label_6);
sliders[6] = (SeekBar)findViewById(R.id.slider_7);
slider_labels[6] = (TextView)findViewById(R.id.slider_label_7);
sliders[7] = (SeekBar)findViewById(R.id.slider_8);
slider_labels[7] = (TextView)findViewById(R.id.slider_label_8);
//define equilizer
eq = new Equalizer (0, 0);
if (eq != null)
{
eq.setEnabled (true);
int num_bands = eq.getNumberOfBands();
num_sliders = num_bands;
short r[] = eq.getBandLevelRange();
min_level = r[0];
max_level = r[1];
for (int i = 0; i < num_sliders && i < MAX_SLIDERS; i++)
{
int[] freq_range = eq.getBandFreqRange((short)i);
sliders[i].setOnSeekBarChangeListener(this);
slider_labels[i].setText (formatBandLabel (freq_range));
}
}
for (int i = num_sliders ; i < MAX_SLIDERS; i++)
{
sliders[i].setVisibility(View.GONE);
slider_labels[i].setVisibility(View.GONE);
}
bb = new BassBoost (0, 0);
if (bb != null)
{
}
else
{
bass_boost.setVisibility(View.GONE);
bass_boost_label.setVisibility(View.GONE);
}
updateUI();
}
/*=============================================================================
onProgressChanged
=============================================================================*/
#Override
public void onProgressChanged (SeekBar seekBar, int level,
boolean fromTouch)
{
if (seekBar == bass_boost)
{
bb.setEnabled (level > 0 ? true : false);
bb.setStrength ((short)level); // Already in the right range 0-1000
}
else if (eq != null)
{
int new_level = min_level + (max_level - min_level) * level / 100;
for (int i = 0; i < num_sliders; i++)
{
if (sliders[i] == seekBar)
{
eq.setBandLevel ((short)i, (short)new_level);
break;
}
}
}
}
/*=============================================================================
onStartTrackingTouch
=============================================================================*/
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
/*=============================================================================
onStopTrackingTouch
=============================================================================*/
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}
/*=============================================================================
formatBandLabel
=============================================================================*/
public String formatBandLabel (int[] band)
{
return milliHzToString(band[0]) + "-" + milliHzToString(band[1]);
}
/*=============================================================================
milliHzToString
=============================================================================*/
public String milliHzToString (int milliHz)
{
if (milliHz < 1000) return "";
if (milliHz < 1000000)
return "" + (milliHz / 1000) + "Hz";
else
return "" + (milliHz / 1000000) + "kHz";
}
/*=============================================================================
updateSliders
=============================================================================*/
public void updateSliders ()
{
for (int i = 0; i < num_sliders; i++)
{
int level;
if (eq != null)
level = eq.getBandLevel ((short)i);
else
level = 0;
int pos = 100 * level / (max_level - min_level) + 50;
sliders[i].setProgress (pos);
}
}
/*=============================================================================
updateBassBoost
=============================================================================*/
public void updateBassBoost ()
{
if (bb != null)
bass_boost.setProgress (bb.getRoundedStrength());
else
bass_boost.setProgress (0);
}
/*=============================================================================
onCheckedChange
=============================================================================*/
#Override
public void onCheckedChanged (CompoundButton view, boolean isChecked)
{
if (view == (View) enabled)
{
eq.setEnabled (isChecked);
}
}
/*=============================================================================
onClick
=============================================================================*/
#Override
public void onClick (View view)
{
if (view == (View) flat)
{
setFlat();
}
if (view == (View) Button1)
{
Intent myIntent = new Intent(MainActivity.this, Guide.class);
MainActivity.this.startActivity(myIntent);
}
}
/*=============================================================================
updateUI
=============================================================================*/
public void updateUI ()
{
updateSliders();
updateBassBoost();
enabled.setChecked (eq.getEnabled());
}
/*=============================================================================
setFlat
=============================================================================*/
public void setFlat ()
{
if (eq != null)
{
for (int i = 0; i < num_sliders; i++)
{
eq.setBandLevel ((short)i, (short)0);
}
}
if (bb != null)
{
bb.setEnabled (false);
bb.setStrength ((short)0);
}
updateUI();
}
/*=============================================================================
showAbout
=============================================================================*/
public void showAbout ()
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("About Simple EQ");
alertDialogBuilder.setMessage(R.string.copyright_message);
alertDialogBuilder.setCancelable(true);
alertDialogBuilder.setPositiveButton (R.string.ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
}
});
AlertDialog ad = alertDialogBuilder.create();
ad.show();
}
/*=============================================================================
onOptionsItemSelected
=============================================================================*/
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.about:
showAbout();
return true;
}
return super.onOptionsItemSelected(item);
}
}

Categories