Star Rating in Dialogbox won't change saved value - java

// Custom Dialog Box
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this, R.style.Theme_AppCompat_Dialog_Alert);
final View mView = getLayoutInflater().inflate(R.layout.completed, null);
ImageButton imgForm = (ImageButton) mView.findViewById(R.id.RateButton);
mBuilder.setCancelable(false);
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show(); // Dialogbox appears
// Interest Rating
final AlertDialog.Builder nBuilder = new AlertDialog.Builder( MainActivity.this, R.style.Theme_AppCompat_Light_Dialog_Alert);
final View nView = getLayoutInflater().inflate(R.layout.intrst, null);
Save_Intrst = (Button) nView.findViewById(R.id.SaveIntrst);
nBuilder.setCancelable(false);
nBuilder.setView(nView);
final AlertDialog dilog = nBuilder.create();
// LongPress Image Button
imgForm.setOnLongClickListener(new View.OnLongClickListener(){
#Override
public boolean onLongClick(View view){
dialog.dismiss();
dilog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dilog.show(); // Dialogbox appears
return true;
}
});
Save_Intrst.setOnClickListener(new View.OnClickListener(){
String IntrstLvl;
#Override
public void onClick(View v){
RatingBar rBar = (RatingBar)nView.findViewById(R.id.ratingStar);
IntrstLvl = Integer.toString(rBar.getNumStars());
addData(IntrstLvl);
dilog.dismiss();
Log.d(TAG,"Dismissed");
}
});
Whenever I select "save" within the Save_Intrst it saves 5 stars regardless of what I choose. I'm still fairly new to Android development and have been java coding for a bit now.
This is just a snippet of code of the project and I believe it will be enough, it shows my submit button, the submit button will launch a dialog box that will have a secret button in an image (ImgForm) the image doesn't show but that's not the problem, after long pressing it will launch another dialog that has a 5 Star Rating Bar and a Save button, this is used for rating after the person completes the previous requirements. The rating will always save "5" regardless of what was inserted, even after a reinstall of app onto the device.

getNumStars() will tell you the maximum number of stars shown and will always be 5 as you have defined it. If you want the actual selected rating, you will need getRating(). See this documentation.

You need to use the rBar.getRating()
RatingBar rBar = (RatingBar)nView.findViewById(R.id.ratingStar);
IntrstLvl = Integer.toString(rBar.getRating());

https://developer.android.com/reference/android/widget/RatingBar.html
You are calling getNumStars() which according to the documentation "Returns the number of stars shown." which means the total number of stars a user can select. You should instead be checking getRating() which returns the number of stars currently selected.
https://developer.android.com/reference/android/widget/RatingBar.html#getRating()

Related

Can't get it to not play code more than once

I pass the text through Intent to another activity, through which it is determined what will be shown to the user, dialog window with victory/defeat.
Everything seems to work well, but the problem is that when the phone screen turns off, the actions are repeated. For example, after winning, I received a dialog about what I won, after that, closing the dialog box, turned off the screen while still in the same activity, then turned the screen back on and I get the dialog box again. It seems that I put the code for showing the dialog in onResume, but I didn't.
I tried turning off the re-show of the dialog box in the following ways, which I will show below:
getIntent().removeExtra("TEXT");
boolean
By the way, about boolean, when I created a variable with this code: boolean offScreen = false, then in onCreate I checked in the if condition, and in the action set boolean to true, the dialog box again appeared, it seems that the activity doesn't pay attention to the boolean.
Please tell me how should I.
Just in case, here's the whole code:
String win_lose_select;
String text = getIntent().getStringExtra("TEXT");
win_lose_select = text;
Handler handler4 = new Handler();
handler4.postDelayed(() -> {
if (Objects.equals(win_lose_select, "win")){
youWin_DIALOG();
soundPlay(star_sound);
}
if (Objects.equals(win_lose_select, "lose")){
youWin_DIALOG();
TextView textView = you_win_dia.findViewById(R.id.textWin);
textView.setText("You lost, don't be discouraged, maybe you'll be lucky next time!\nThe defeat is counted.");
soundPlay(lose_sound);
}
if (Objects.equals(win_lose_select, "winNetwork")){
youWin_DIALOG();
TextView textView = you_win_dia.findViewById(R.id.textWin);
textView.setText("You have won, congratulations, your opponent has surrendered!\nVictory counted.");
soundPlay(star_sound);
}
},2000);
public void youWin_DIALOG() {
you_win_dia = new Dialog(this);
you_win_dia.requestWindowFeature(Window.FEATURE_NO_TITLE);
you_win_dia.setContentView(R.layout.you_win);
you_win_dia.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
you_win_dia.setCancelable(true);
getIntent().removeExtra("TEXT");
win_lose_select = "no";
Button go_to_rooms_win = (Button) you_win_dia.findViewById(R.id.go_to_rooms_win);
go_to_rooms_win.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
soundPlay (tuck);
you_win_dia.dismiss();
}
});
you_win_dia.show();
Window window = you_win_dia.getWindow();
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
}

How to use Databinding with DialogFragment

In my app I have an ElementListFragment of items represented by a code object Element. I've data-bound these elements to the list and they display the correct information.
However, to continue filling in the information in each item I put a button on each element that shows a Dialog with additional fields.
But when the Dialog opens the fields are all blank (where one at least ought to be filled) and any fields I fill don't save the data (and don't effect changes on the list).
Appart from the values not being bound (displayed or written), the application works fine. I've essentially tried multiple variations of the sugestions in this question. Here is the code:
public class ElementDialogFragment extends DialogFragment {
private Element mElement;
private Dialog dialog;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.dialog_element, null);
final DialogSkillelementBinding binding = DialogElementBinding.inflate(LayoutInflater.from(getContext()));
builder.setView(v)
// Add action buttons
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//this was just an attempt to make it work
binding.executePendingBindings();
dialog.dismiss();
}
});
TextView Title = v.findViewById(R.id.skill_e_dialog_title);
Title.setText(ResourceLocator.getSkillName(mElement.getSkill()));
dialog = builder.create();
dialog.setContentView(binding.getRoot());
binding.setElement(mElement);
binding.executePendingBindings();
return dialog;
}
}
When debuging I've confirmed that mElement is correctly attributed, however it's also bound to the list shown beneath the dialog. The title is also displayed correctly.
Is there a problem double-binding an object?
Are some of the steps on the function maybe out of order?
Is the DialogBuilder somehow incompatible with databinding?
You should set LyfecycleOwner for your binding class for data updating.
binding.setLifecycleOwner(requireActivity())

How should I return to a previous dialog from another one?

I've got an inputDialog, which allows for some text inputs. On clicking save, the inputDialog checks if the entered text is already available (to prevent double entries). If this is the case, a new AlertDialog is created, simply stating "The value you entered already exists", with just an "Ok" button to dismiss this AlertDialog. This all works.
I would like to have the inputDialog pop back up again, after dismissing the AlertDialog, with the values that were entered by the user before still in the editText fields.
I'm not expecting any problems on getting those values back in the editText fields (Store them in a variable on clicking save, if the double entry error occurs, set those variables on the editText's. If I'm doing this in a stupid way, please let me know).
I am however having trouble with getting the first (inputDialog) dialog to come back. The code you see below is the code for my inputDialog fragment (The code is simplified, so if something seems to be missing, it probably is. Let me know, so I can add it back in.)
So, to repeat myself: How can I return to the previous dialog after dismissing the second one?
StuffManagerInputDialogFragment.java:
public class StuffManagerInputDialogFragment extends DialogFragment {
EditText nameInputField;
EditText tagInputField;
DBHandler dbHandler;
StuffManagerFragment f = new StuffManagerFragment();
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
final View v_iew = inflater.inflate(R.layout.fragment_inputdialog, null);
nameInputField = (EditText) v_iew.findViewById(R.id.inputdialogname);
tagInputField = (EditText) v_iew.findViewById(R.id.inputdialogtag);
dbHandler = new DBHandler(getActivity(), null, null, 1);
final MainActivity ma = (MainActivity) getActivity();
final AlertDialog.Builder newLinkDialog = new AlertDialog.Builder(getActivity());
newLinkDialog.setView(v_iew)
.setTitle("New Link")
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String nameInputFieldText = nameInputField.getText().toString();
String tagInputFieldText = tagInputField.getText().toString();
ArrayList<String> nameArray = dbHandler.nameArrayMethod();
ArrayList<String> tagArray = dbHandler.tagArrayMethod();
NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.nav_view);
Menu menu = navigationView.getMenu();
if (nameArray.contains(nameInputFieldText) || tagArray.contains(tagInputFieldText)) {
if (nameArray.contains(nameInputFieldText) && tagArray.contains(tagInputFieldText)) {
AlertDialog.Builder errorBoth = new AlertDialog.Builder(getActivity())
.setTitle("Error")
.setMessage("The name and tag you entered are already in use.")
.setIcon(R.drawable.ic_error_black)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Return to previous dialog here
}
});
errorBoth.show();
}
} else {
dbHandler.addLink(nameInputFieldText, tagInputFieldText);
nameArray = dbHandler.nameArrayMethod();
int nameArraySize = (nameArray.size() - 1);
MenuItem item = menu.add(R.id.group1, nameArraySize, 1, nameArray.get(nameArraySize));
Toast.makeText(getContext(), "'" + nameInputFieldText + " - " + tagInputFieldText + "' link saved.", Toast.LENGTH_SHORT).show();
ma.addSMVFFragments();
f.hideDeleteAllButton = false;
getActivity().invalidateOptionsMenu();
}
}
})
.setNegativeButton("Cancel", null);
return newLinkDialog.create();
}
}
A better solution is to have a dialog fragment for your input layout, and that dialog fragment would display an AlertDialog on OK if the text validation fails. The input dialog fragment would not dismiss in this case, it will remain in the background so when you dismiss the alert dialog to tell the user the input is invalid, you return to the input dialog as it was.
To prevent the dialog fragment from dismissing on OK you would override onStart and get a reference to the OK button and set the listener there, like this:
#Override
public void onStart() {
super.onStart();
AlertDialog alertDialog = (AlertDialog) getDialog();
if (alertDialog != null) {
mOKButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
mOkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (field OK) {
// save data
dismiss();
} else {
// show error dialog
}
}
});
}
}

Getting value from EditText within an AlertDialog Builder

Right, I know there's alot of similar questions. I've researched on stackoverflow as well as on the internet about this but still stumped.
This code is in a fragment.
...
private Context context = getActivity();
public void Dialog(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View mView = inflater.inflate(R.layout.dialog, null);
alertDialogBuilder.setView(mView);
EditText a = (EditText) mView.findViewById(R.id.a);
EditText b = (EditText) mView.findViewById(R.id.b);
EditText c = (EditText) mView.findViewById(R.id.c);
//a.setText("abc");
//b.setText("xyz");
//c.setText("123");
strA = a.getText().toString();
strB = b.getText().toString();
final String strC = c.getText().toString();
}
This should be a typical approach to getting the view of the inflated layout and using it to access the elements inside the view, but it's not working no matter what I tried, I just could not get strA, strB and strC values using getText().toString().
//a.setText("abc");
//b.setText("xyz");
//c.setText("123");
But, if I uncomment the above 3 lines, the values get sent across. And I can receive them inside strA, strB, strC. Why is this so? I don't get it at all.
Any help greatly appreciated, thank you!
You are trying to get values at the time you initialize the dialog. you need to get values after an action, like a button click
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
strA = a.getText().toString();
strB = b.getText().toString();
}
});
Have a look at this display textview in alert dialog
Looks to me like you're checking the values of the EditTexts as soon as they're created. Which of course the value is going to be null every time since your user hasn't had time to type anything. I think you need a SubmitButton or something similar that checks the EditTexts in its onClickListener. Though I'll admit I've never inflated a view into an alert dialog.
Try like this.
MyDialogue is your Activity name.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MyDialogue.this);
// Get the layout inflater
LayoutInflater inflater = MyDialogue.this.getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View mView = inflater.inflate(R.layout.dialog, null);
alertDialogBuilder.setView(mView);
final EditText a = (EditText) mView.findViewById(R.id.a);
final EditText b = (EditText) mView.findViewById(R.id.b);
final EditText c = (EditText) mView.findViewById(R.id.c);
a.setText("abc");
b.setText("xyz");
c.setText("123");
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final String strA = a.getText().toString();
final String strB = b.getText().toString();
final String strC = c.getText().toString();
Log.e("tag", strA + " " + strB + " " + strC );
}
});
alertDialogBuilder.show();
The layout is not yet initiated when you are trying to set the values, you need to call AlertDialog alertDialog = alertDialogBuilder.create(); and then alertDialog.show(); or just alertDialogBuilder.show() before you can edit the textView content.

Removing TextViews when i clicked backbutton

My problem is I have a button and that button is doing create new textview but that textviews removing when i click back button. How I saved textviews in activity?
My java sourcecodes here
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notlar);
Button btnNotEkle = (Button) findViewById(R.id.btnNotEkle);
final EditText etNot = new EditText(NotEkle.this);
final LinearLayout layoutNotlar = (LinearLayout) findViewById(R.id.layoutNotlar);
final TextView tv1 = (TextView) findViewById(R.id.tvnotOrtalama);
etNot.setInputType(InputType.TYPE_CLASS_NUMBER);
AlertDialog.Builder notEkle = new AlertDialog.Builder(NotEkle.this);
notEkle.setTitle("Notunuz");
notEkle.setView(etNot);
//Positive button
notEkle.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
tvNot = new TextView(NotEkle.this);//girelen not burdaki textview e yazdırılacak.
girilenNot = etNot.getText().toString();//Girilen notu alıyoruz
tvNot.setText(girilenNot);//girilen notu textviewa veriyoruz
notTopla += Integer.parseInt(girilenNot);//Notları topluyoruz
layoutNotlar.addView(tvNot);
count = layoutNotlar.getChildCount();
dersOrtalamaYazdir=String.valueOf(dersOrtalama());
tv1.setText("Ders Ortalamanız : "+dersOrtalamaYazdir);
dialog.cancel();
}
});
final AlertDialog notEkleCreate = notEkle.create();
btnNotEkle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
notEkleCreate.show();
}
});
}
}
Try giving your TextView objects ids.
You need to know that when you click back button - by default your activity is destroyed so all views are removed.
When you are adding new TextView you should add information about this TextView (like the text itself) to some list declared as field in your activity.
Then you can save this list when activity is recreated see: onSaveInstanceState/nRestoreInstanceState
You can also pass this list back or to new activity so that they can take actions based on this list.
Following my understanding your TextView had been created inside Dialog and after you press back button the dialog dismisses and all views you created inside will be removed and you can't access it from your Activity.
You may try to create TextView in onCreate, pass and in Dialog just call setText. I hope this is the answer you're looking for.
Cheers.

Categories

Resources