How to reset input to DialogFramgment after initial build? - android

EDIT: Attached the code for my onCickListener which sends Rating Value to and then Show my Dialog.
I have a TextView which shows me a rating in numbers format (4.5). And when I press this TextView a dialog pops up to let me change the rating trough a RatingBar. The Ratingbar`s rating is set to equal the TextView Rating when it pops up. This functions as expected and the TextView is updated to the new rating when I press OK. BUT when I press the TextView again, the initial first value is shown and not the value which I just updated it to. I have figured out as much as this is because I have all my code within the onCreateDialog (). I have tried to get this to work by using OnStart() and onResume() but then my app crashes. How do I write this code correctly?
Attached is my functional code with all code set within the onCreadeDialog()
public class RatingDialog extends DialogFragment{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// 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
final View DialogView = inflater.inflate(R.layout.dialog_rating, null);
/**
* Retrieve the argument "num" (Previously rating) and set ratingbar´s rating equal to this.
*/
getArguments().getFloat("num");
RatingBar ValueView = (RatingBar) DialogView.findViewById(R.id.Ratingbar);
ValueView.setRating(getArguments().getFloat("num"));
builder.setView(DialogView)
// Add action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
/**
* Get the new value from the Ratingbar and send this back to the AddRating TextView
*/
RatingBar ValueView = (RatingBar) DialogView.findViewById(R.id.Ratingbar);
float Value = ValueView.getRating();
TextView Text = (TextView) getActivity().findViewById(R.id.AddRating);
Text.setText(String.valueOf(Value));
RatingDialog.this.getDialog().cancel();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
RatingDialog.this.getDialog().cancel();
}
});
return builder.create();
}
}
Below is the code for onCickListener which sends Rating Value to and then Show my Dialog:
/**
* Set the On Click Listener and send the Rating value to the Dialog
*/
final TextView Rating = (TextView) findViewById(R.id.AddRating);
String S = (String) Rating.getText();
final Float F;
if (S==""){
F=0.0f;}
else
F = Float.valueOf(S);
Rating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RatingDialog newFragment = new RatingDialog();
newFragment.show(getSupportFragmentManager(), "Rating");
/**
* Send Verdien av rating til dialogvinduet
*/
Bundle args = new Bundle();
args.putFloat("num", F);
newFragment.setArguments(args);
}
});

You are passing same F value all the time.
It should be:
final TextView rating = (TextView) findViewById(R.id.AddRating);
rating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RatingDialog newFragment = new RatingDialog();
newFragment.show(getSupportFragmentManager(), "Rating");
/**
* Send Verdien av rating til dialogvinduet
*/
Bundle args = new Bundle();
args.putFloat("num", TextUtils.isEmpty(rating.getText()) ?
0.0f : Float.valueOf(rating.getText().toString()));
newFragment.setArguments(args);
}
});
In that case you will pass actual value of rating TextView.
And yes, please follow java code convention. Because it's hard to read your code.

Related

Pass rating bar to dialog

I'm new to android and trying to pass rating bar to dialog but it throws a NPE.
This the code on my oncreate activity.
…
LinearLayout rating = findViewById(R.id.rating);
ratingBar = findViewById(R.id.ratingsbar);
flag = true;
rating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (flag) {
RatingBarDialog ratingBarDialog = new RatingBarDialog();
Bundle args = new Bundle();
args.putString("profileUid", profileUid);
ratingBarDialog.setArguments(args);
ratingBarDialog.show(getFragmentManager(), "rating");
}
}
});
I have method for adding rating in the same class
static public void addRatingToUser(float newRating, String profileUid) {
// calculate new rating within User class
dbUser.addRating((double) newRating);
// add new rating and ratingCount to firebase
DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("users").child(profileUid);
userRef.child("rating").setValue(dbUser.getRating());
userRef.child("ratingCount").setValue(dbUser.getRatingCount());
// set the stars of the ratingBar view
ratingBar.setRating((float) dbUser.getRating());
}
}
Here is my RatinDialog class
public class RatingBarDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
final LayoutInflater inflater = LayoutInflater.from(builder.getContext());
#SuppressLint("InflateParams") final View view = inflater.inflate(R.layout.activity_rate_user, null);
final RatingBar ratingBar = view.findViewById(R.id.editRatingBar);
final String profileUid = getArguments().getString("profileUid");
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(view)
.setTitle("Rate User")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
UserProfile.addRatingToUser(ratingBar.getRating(), profileUid);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
RatingBarDialog.this.getDialog().cancel();
}
});
return builder.create();
}
}
I have a model user with method for calculating ratings
void addRating(double newRating) {
// get total of all old ratings (multiply current average rating by # of ratings
double oldRatingTotal = rating * ratingCount;
// increment rating count
ratingCount++;
// add new rating to the total, then divide it by the new rating count to get new average
double newRatingTotal = oldRatingTotal + newRating;
rating = newRatingTotal / ratingCount;
}
This is my logcat error, I've tried but unable to fix the NPE. I'll appreciate any help.
Thank you
2018-12-18 19:49:56.710 27009-27009/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.reseller, PID: 27009
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.android.reseller.User.addRating(double)' on a null object reference
at com.android.reseller.UserProfile.addRatingToUser(UserProfile.java:215)
at com.android.reseller.RatingBarDialog$2.onClick(RatingBarDialog.java:38)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6566)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$Metho
Finally, I was able to fix the error.
I initially, created a variable of the model:
static User dbUser;
But failed to create an object of the model in my oncreate method, this lead to dbUser being null.
dbUser = new User();

how to create a custom dialog and receive results in android?

i have an activity that when user click on button , a dialog open. in this dialog there is a spinner that have 3 choices: Blue,Red,Green. and there is a submit button. i want that when user select a color and click on submit, in caller activity, its String color set to selected color in dialog. i try this: but not worked. please help me....
String color;
String dialogColor;
showDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("my dialog");
Spinner spinner = (Spinner) dialog.findViewById(R.id.spinner);
final TextView status = (TextView) dialog.findViewById(R.id.status);
Button submit = (Button) dialog.findViewById(R.id.submit);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
dialogColor = parent.getItemAtPosition(position).toString();
status.setText("Color is: "+dialogColor);
color = dialogColor;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("Color",dialogColor);
dialog.dismiss();
}
});
dialog.show();
}
});
i use both of direct and with intent ways to assign my color String to selected value. but not worked. where i have mistake?
I think the best way to create custom dialogs now is the Dialog Fragment, because the simple dialog it's limited. For example it's the way to create a dialogs with material design. And you have a differents ways to take info from dialog fragment, the first and the second for example.
This is basic code to create a dialog fragment:
//Method to call and start dialog fragment class
public void ShowPhotoFilesDialog(Activity context,File photo){
//Declaration of classes
Custom_DialogFragment custom_dialogFragment = new Custom_DialogFragment ();
FragmentManager fragmentManager = context.getFragmentManager();
// The device is using a large layout, so show the fragment as a dialog
custom_dialogFragment.show(fragmentManager, "dialog");
}
And this is the basic dialog fragment class:
public class Custom_DialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
try {
// The only reason you might override this method when using onCreateView() is
// to modify any dialog characteristics. For example, the dialog includes a
// title by default, but your custom layout might not need it. So here you can
// remove the dialog title, but you must call the superclass to get the Dialog.
Dialog dialog = super.onCreateDialog(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//To hide action bar from layout
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Declaration of controls
View v = getActivity().getLayoutInflater().inflate(R.layout.my_custom_layout);
builder.setView(v);
//My code
return builder.create();
}
catch (Exception ex){
Log.e("-- Custom_DialogFragment.onCreateDialog --","",ex);
return null;
}
}
}
Tell me if I helped you, good programming!

How to update dialogue in android

I have a popup dialog where the user inputs data, including a date. To select the date, I have a button to open another window with a date picker. When I select the date and it returns to the first dialog, the text field with the date is not changed unless I open the date picker a second time. How would I refresh or update the first dialog immediately after I return to it from the date picker window?
Here is the code for the first dialog:
public void addEntry(View view) {
final Dialog d = new Dialog(this);
d.setContentView(R.layout.dialog);
d.setTitle("Add Entry");
d.setCancelable(true);
d.show();
...
chooseDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = selectDate();
date.setText(str);
}
});
}
Here is the code for the second window where you would choose the date:
public String selectDate(){
final Dialog datePicker = new Dialog(this);
datePicker.setContentView(R.layout.choose_date);
datePicker.setTitle("Choose Date...");
datePicker.setCancelable(true);
datePicker.show();
Button selectFinalDate = (Button) datePicker.findViewById(R.id.selectDate);
final DatePicker dp = (DatePicker) datePicker.findViewById(R.id.datePicker1);
selectFinalDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strDateTime = (dp.getMonth() + 1) + "/" + dp.getDayOfMonth() + "/" + dp.getYear();
datePicker.dismiss();
}
});
return strDateTime;
};
Thanks!!
Put date.setText(datechoosen) in the second dialog on click and it will set the textView or button or whatever view that shows the date on the first dialog. Make it static in case it is not accessible in the second dialog but check if it is not null before accessing it.
not tested, but should work.
...
date.setText(str);
view.invalidate(); // the view that you are showing in the dialog
...
so in your code, you update this :
/**
* global variable for your dialog view
*/
View view =null;
// in your addEntry(View view)
...
Dialog d = new Dialog(this);
view = LayoutInflater.from(this).inflate(R.layout.dialog, null);
d.setContentView(view);
...
// selectDate()
...
date.setText(str);
view.invalidate(); // the view that you are showing in the dialog
...
see this answer

access a different layouts parameter from current activity

Suppose my current activity is Main.java and I have already declared its layout through setContentView(R.layout.layout1) from its onCreate method. Now, is it in any way possible for me to access a different layout? For e.g., assuming there is another layout - layout2 which has TextView with id tv, then I won't be able to execute the following code from Main.java :
TextView text = (TextView) findViewById(R.id.tv);
text.setText("blah blah");
Is there any way that I can set tv's value from Main.java.
My actual code is the following
setContentView(R.layout.layout);
Button button = (Button) findViewById(button);
button(buttonListener);
Dialog dialog;
Inside the listener, I have the following code:
TextView dialogTitle = (TextView) findViewById(R.id.dialog_title);
dialogTitle.setText("Email");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View customView = getLayoutInflater().inflate(R.layout.dialog, null);
builder.setView(customView);
dialog = builder.create();
dialog.show();
The problem that I am facing is that dialog_title is in dialog.xml and not in layout.xml
You can always inflate any XML layout you want at any time:
View layout2 = LayoutInflater.from(this).inflate(R.layout.layout2, null);
You can use Bundles
In Activity 1
String your_string = "Hello, World!";
Bundle bundle = new Bundle();
bundle.putString("The key for this string", your_string );
Intent ActivityToLaunch= new Intent(this, ActivityB.class);
ActivityToLaunch.putExtras(bundle);
this.startActivity(ActivityToLaunch);
In Activity 2
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2); //Setup some layout, set to your own
String content = getIntent().getExtras().getString("The key for this string");
TextView text = (TextView) findViewById(R.id.tv);
text.setText(content);
}
The thread starter said that he wanted to raise a custom dialog, so here goes the edit
This is my class which will generate a custom Dialog:
public class ErrorDialog {
TextView msgTextView;
Button toSettings;
final Context c;
Dialog errorDialog;
/**
* #param c The Context
* #param title Title of the Dialog
* #param msg Message og the Dialog
* #param textOnButton The text on the button
*/
public ErrorDialog(final Context c, String title, String msg, String textOnButton) {
this.c = c;
errorDialog = new Dialog(c);
errorDialog.setContentView(R.layout.error_dialog);
errorDialog.setTitle(title);
msgTextView = (TextView) errorDialog.findViewById(R.id.errorMSG);
msgTextView.setText(msg);
toSettings = (Button) errorDialog.findViewById(R.id.toSettings);
toSettings.setText(text);
toSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//doing operations when the user clicks my button in the dialog.
}
});
errorDialog.show();
errorDialog.setCancelable(true);
}
}
Use this class this way:
new ErrorDialog(getApplicationContext(), "My Title", "My Message to the user", "Text on the button");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View customView = getLayoutInflater().inflate(R.layout.dialog, null);
builder.setView(customView);
TextView dialogTitle = (TextView) customView.findViewById(R.id.dialog_title);
dialogTitle.setText("Email");

Open a rating bar when a button is tapped

Is it possible to make an 'AlertDialog-like display' that has rating bar inside it when a button is clicked? If yes, will I able to get the value of the rating that is entered? Thanks.
Here is some code I used in an application to show a dialog fragment and get a selection out of it:
public class FeedChooserFragment extends DialogFragment {
/**
* Implement this interface if the activity needs to do something
* after the dialog has been dismissed.
*/
public interface FeedChooserListener {
public void onFeedSelected(NewsFeed feed, Object userData);
}
/**
* Create a new instance of the fragment
*/
public static FeedChooserFragment newInstance(Serializable userData) {
FeedChooserFragment f = new FeedChooserFragment();
Bundle args = new Bundle();
args.putSerializable(Extra.USER_DATA, userData);
f.setArguments(args);
return f;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// This is a list of items, but it could be a custom dialog showing some rating bar
BaseActivity a = (BaseActivity) getActivity();
List<NewsFeed> feed = a.getDataCache().getAllNewsFeed();
adapter = new FeedAdapter(a);
adapter.addAll(feed);
// Here you would create a custom dialog, find the rating bar in the inflated view
// and keep it ready for when the dialog gets dismissed.
AlertDialog.Builder builder = new AlertDialog.Builder(a);
// Here you would set the button listeners instead of the listview listener
builder.setAdapter(adapter, dialogClickListener);
return builder.create();
}
private OnClickListener dialogClickListener = new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
NewsFeed selectedFeed = adapter.getItem(which);
// This is where we try to notify the calling activity or fragment
if (getActivity() instanceof FeedChooserListener) {
((FeedChooserListener) getActivity()).onFeedSelected(selectedFeed, userData);
}
if (getTargetFragment() instanceof FeedChooserListener) {
((FeedChooserListener) getTargetFragment()).onFeedSelected(selectedFeed, userData);
}
dialog.dismiss();
}
};
private Object userData;
private FeedAdapter adapter;
}
Yes, Its possible, Try something like this...
PopupWindow pw;
//We need to get the instance of the LayoutInflater, use the context of this activity
LayoutInflater inflater = (LayoutInflater) TouchPaint.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate the view from a predefined XML layout
View layout = inflater.inflate(R.layout.popup,
(ViewGroup) findViewById(R.id.popup_element));
//popup : name of the XML file which includes the popup_element(can be a linear layout which includes the rating bar)
pw = new PopupWindow(layout,70, 220, true);
pw.showAtLocation(layout, Gravity.LEFT,100,200);
rb =(RatingBar)layout. findViewById(R.id.RatingBar);
rb.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// To Do code
pw.dismiss();
}
});

Categories

Resources