Pass rating bar to dialog - android

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();

Related

Sending data from Dialog to Fragment

I am trying to send some data from a DialogFragment to a TextView from a Fragment.
After inserting the data in the available input and pressing SAVE, the app crashes.
I assume there is something wrong with the IncomeDialogListener.
I would appreciate some hints where I did wrong.
This is the Dialog Class
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_incomedialog, null);
builder.setView(view)
.setTitle("Add Income")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String Amount = enter_income_amount.getText().toString();
String Note = enter_income_note.getText().toString();
String Date = enter_income_date.getText().toString();
incomeDialogListener.addDetails(Amount, Note, Date);
}
});
enter_income_amount = view.findViewById(R.id.enter_income_amount);
enter_income_note = view.findViewById(R.id.enter_income_note);
enter_income_date = view.findViewById(R.id.enter_income_date);
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
incomeDialogListener = (IncomeDialogListener) getTargetFragment();
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + "Must Implement IncomeDialogListener");
}
}
public interface IncomeDialogListener {
void addDetails(String Amount, String Note, String Date);
}
This is the Fragment to which I want to send the data
public class IncomeFragment extends Fragment implements
IncomeDialog.IncomeDialogListener {
DatabaseHelper myDB;
Button btn_add_income;
TextView display_income;
public IncomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_placeholder2 , container, false);
display_income = (TextView) v.findViewById(R.id.display_income);
btn_add_income = (Button) v.findViewById(R.id.btn_add_income);
myDB = new DatabaseHelper(getActivity());
btn_add_income.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openIncomeDialog();
}
});
return v;
}
private void openIncomeDialog() {
android.support.v4.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
IncomeDialog incomeDialog = new IncomeDialog();
incomeDialog.show(fragmentTransaction, "income dialog" );
}
#Override
public void addDetails(String Amount, String Note, String Date) {
display_income.setText(Amount);
}
}
Here is my solution for you:
IncomeFragment.java
public static final int INCOME_DIALOG_FRAGMENT = 1; // Add this line
private void openIncomeDialog() {
android.support.v4.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
IncomeDialog incomeDialog = new IncomeDialog();
incomeDialog.setTargetFragment(IncomeFragment.this, INCOME_DIALOG_FRAGMENT); // Add this line
incomeDialog.show(fragmentTransaction, "income dialog");
}
IncomeDialog.java
#Override
public void onClick(DialogInterface dialog, int which) {
String Amount = enter_income_amount.getText().toString();
String Note = enter_income_note.getText().toString();
String Date = enter_income_date.getText().toString();
IncomeDialogListener listener = (IncomeDialogListener) getTargetFragment();
listener.addDetails(Amount, Note, Date);
}
Update: There is no magic behind, when you open dialog from fragment, you passed itself to dialog by calling setTargetFragment. Then in the dialog you can refer to the fragment that opened it by calling getTargetFragment. Actually there are 2 solutions you can use.
IncomeFragment incomeFragment = (IncomeFragment) getTargetFragment();
incomeFragment.addDetails(Amount, Note, Date);
or
IncomeDialogListener listerner = (IncomeDialogListener) getTargetFragment();
listerner.addDetails(Amount, Note, Date);
I prefer to use the second one because the dialog don't need to know about specific fragment that opened it. This makes the dialog is usable. Imagine a situation, three days later, you would like to open the dialog from another fragment, in that case you don't need to modify the dialog again, just let the another fragment implements IncomeDialogListener. If you use the first one, you must go to the dialog and modify it to make sure it works for the another fragment.

How to reset input to DialogFramgment after initial build?

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.

Send back information from Dialog to Activity using Interface

This is my interface:
public interface TaskEditDialogListener {
public void passTask(String taskTitle, String note);
}
This is my Dialog Class
public class TaskEditDialog extends DialogFragment {
private TaskEditDialogListener mListerner;
public void setListerner(TaskEditDialogListener listerner) {
mListerner = listerner;
}
#BindView(R.id.dialog_TaskEdt)
EditText mTaskEdt;
#BindView(R.id.dialog_NotesEdt)
EditText mNoteEdt;
LayoutInflater inflater;
View v;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
inflater = getActivity().getLayoutInflater();
v = inflater.inflate(R.layout.task_edit_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(v).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ButterKnife.bind(getActivity());
String taskTitle = mTaskEdt.getText().toString();
String note = mNoteEdt.getText().toString();
mListerner.passTask(taskTitle,note);
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return builder.create();
}
}
This is my Activity class
public class DetailedTaskActivity extends AppCompatActivity implements TaskEditDialogListener {
private String mTaskTitle;
// Bind the widget
#BindView(R.id.detailedTaskAct_TaskLabelTv)
TextView mTaskLabelTv;
#BindView(R.id.detailedTaskAct_TaskTv)
TextView mTaskTv;
#BindView(R.id.detailedTaskAct_DueDateLabelTv)
TextView mDueDateLabelTv;
#BindView(R.id.detailedTaskAct_DueDateTv)
TextView mDueDateTv;
#BindView(R.id.detailedTaskAct_NotesLabelTv)
TextView mNotesLabelTv;
#BindView(R.id.detailedTaskAct_NotesTv)
TextView mNotesTv;
#BindView(R.id.detailedTaskAct_PriorityLabelTv)
TextView mPriorityLabelTv;
#BindView(R.id.detailedTaskAct_PriorityTv)
TextView mPriorityTv;
#BindView(R.id.DetailedTaskAct_StatusLabelTv)
TextView mStatusLabelTv;
#BindView(R.id.detailedTaskAct_StatusTv)
TextView mStatusTv;
// Add delete button to Actionbar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.delete_button, menu);
return true;
}
#Override
public void passTask(String taskTitle, String note) {
TaskEditDialog dialog = new TaskEditDialog();
dialog.setListerner(this);
Task task = new Select().from(Task.class).where("task_title = ?", mTaskTitle)
.executeSingle();
task.setTaskTitle(taskTitle);
task.setNotes(note);
mTaskTv.setText(taskTitle);
mNotesTv.setText(note);
}
}
I try to get the information from the dialog to the Activity and update a database and set the textview. However, I always receive the nullException Error like this
10-04 19:13:39.274 21018-21018/com.example.rubit1359.tudu E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rubit1359.tudu, PID: 20819
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.rubit1359.tudu.ui.dialog.TaskEditDialog$2.onClick(TaskEditDialog.java:49)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Please help me.
The error has nothing to do with sending data from DialogFragment to Activity. It's is due to NPE.
You are not correctly binding the views with ButterKnife in TaskEditDialog. It should be like this:
v = inflater.inflate(R.layout.task_edit_dialog, null);
ButterKnife.bind(this, v); // this refers to TaskEditDialog class object.
EDIT 1:
Since you are using DialogFragment, then you can directly communicate to its parent activity.
Do something like this:
((DetailedTaskActivity)getActivity()).passTask(someData); // where passTask() is any public method in the activity.

NullPointerException when using database object [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm new to Android, and i've got some issues.
It looks like it's saying DB.EmployeeOperations.open() is having an null object passed to it, but I'm not sure.
Where I missed a step?
Any help is appreciated.
Thanks in advance.
Logcat:
* 06-10 16:10:52.605 17203-17203/com.androidtutorialpoint.employeemanagementsystem E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.androidtutorialpoint.employeemanagementsystem, PID: 17203
java.lang.RuntimeException: Unable to resume activity {com.androidtutorialpoint.employeemanagementsystem/com.androidtutorialpoint.employeemanagementsystem.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations.open()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3019)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3050)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2425)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations.open()' on a null object reference
at com.androidtutorialpoint.employeemanagementsystem.MainActivity.onResume(MainActivity.java:148)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
at android.app.Activity.performResume(Activity.java:6076)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3008)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3050)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2425)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
Java Code:
public class MainActivity extends AppCompatActivity{
private Button addEmployeeButton;
private Button editEmployeeButton;
private Button deleteEmployeeButton;
private Button viewAllEmployeeButton;
private EmployeeOperations employeeOps;
private static final String EXTRA_EMP_ID = "com.androidtutorialpoint.empId";
private static final String EXTRA_ADD_UPDATE = "com.androidtutorialpoint.add_update";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addEmployeeButton = (Button) findViewById(R.id.button_add_employee);
editEmployeeButton = (Button) findViewById(R.id.button_edit_employee);
deleteEmployeeButton = (Button) findViewById(R.id.button_delete_employee);
viewAllEmployeeButton = (Button)findViewById(R.id.button_view_employees);
addEmployeeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,AddUpdateEmployee.class);
i.putExtra(EXTRA_ADD_UPDATE, "Add");
startActivity(i);
}
});
editEmployeeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getEmpIdAndUpdateEmp();
}
});
deleteEmployeeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getEmpIdAndRemoveEmp();
}
});
viewAllEmployeeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, ViewAllEmployees.class);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.employee_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_item_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void getEmpIdAndUpdateEmp(){
LayoutInflater li = LayoutInflater.from(this);
View getEmpIdView = li.inflate(R.layout.dialog_get_emp_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_emp_id.xml to alertdialog builder
alertDialogBuilder.setView(getEmpIdView);
final EditText userInput = (EditText) getEmpIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// get user input and set it to result
// edit text
Intent i = new Intent(MainActivity.this,AddUpdateEmployee.class);
i.putExtra(EXTRA_ADD_UPDATE, "Update");
i.putExtra(EXTRA_EMP_ID, Long.parseLong(userInput.getText().toString()));
startActivity(i);
}
}).create()
.show();
}
public void getEmpIdAndRemoveEmp(){
LayoutInflater li = LayoutInflater.from(this);
View getEmpIdView = li.inflate(R.layout.dialog_get_emp_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_emp_id.xml to alertdialog builder
alertDialogBuilder.setView(getEmpIdView);
final EditText userInput = (EditText) getEmpIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// get user input and set it to result
// edit text
employeeOps = new EmployeeOperations(MainActivity.this);
employeeOps.removeEmployee(employeeOps.getEmployee(Long.parseLong(userInput.getText().toString())));
Toast t = Toast.makeText(MainActivity.this,"Employee removed successfully!",Toast.LENGTH_SHORT);
t.show();
}
}).create()
.show();
}
#Override
protected void onResume() {
super.onResume();
employeeOps.open();
}
#Override
protected void onPause() {
super.onPause();
employeeOps.close();
}
}
The problem is you're calling employeeOps.open() in onResume(), but employeeOps is not instantiated yet, it's value is still null.
Take a look at the Activity lifecycle.
As you can see, when an Activity gets created two methods get called before onResume(): onCreate() and onStart().
If you would like to call the open() method of EmployeeOperations in onResume(), you need to have an instance of it by then.
Call the following in onCreate():
employeeOps = new EmployeeOperations(this);
Your problem is a misunderstanding of the Android lifecycle. Specifically, from that resource,
Once the onCreate() finishes execution, the system calls the onStart() and onResume() methods in quick succession.
What this means for you is that onResume() triggers before you ever set employeeOps to a non-null value. You're only initializing it in response to a button press, but your Activity is only visible for a very short duration before onResume is triggered.

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