what i am trying to built a user-experience dialog with rating and comments.
I have built the dialog and everything works but when i press the possitive button it crashes for some reason...
My onCreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_profile);
rateButton = (FloatingActionButton) findViewById(R.id.rate);
shareButton = (FloatingActionButton) findViewById(R.id.share);
ratingBar = (RatingBar) findViewById(R.id.ratingBar);
ratingComment = (EditText) findViewById(R.id.ratingComment);
ratingNum = (TextView) findViewById(R.id.ratingNum);
ratingCommentText = (TextView) findViewById(R.id.Comment);
setupButtonEvents();
}
the setupButtonEvents()
private void setupButtonEvents() {
rateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(UserProfile.this);
View newLayout = getLayoutInflater().inflate(R.layout.rate_dialog,(ViewGroup)findViewById(R.id.rootLayout));
builder.setView(newLayout)
.setTitle(getString(R.string.rateDialogTitle))
.setPositiveButton(R.string.posButtonRate, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
insertDataToDatabaseFromRating();
}
}).create();
builder.show();
}
});
and the insertDataToDatabaseFromRating()
private void insertDataToDatabaseFromRating() {
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
percent = (int) ratingBar.getRating();
ratingNum.setText("" + percent);
}
});
comTxt = ratingComment.getText().toString();
if (!comTxt.isEmpty()) {
ratingCommentText.setText(comTxt);
}
}
The Logcat out Error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RatingBar.setOnRatingBarChangeListener(android.widget.RatingBar$OnRatingBarChangeListener)' on a null object reference
at com.order.app.order.UserProfile.insertDataToDatabaseFromRating(UserProfile.java:144)
Line 144: ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
Can anyone help me out with this??? Thanks in advance!!!!
Probably RatingBar
is inside AlertDialog
layout. to access views from AlertDialog layout use view object which is passed in builder.setView(newLayout)
.
In your case add View parameter to insertDataToDatabaseFromRating
method then access RatingBar
as:
private void insertDataToDatabaseFromRating(View view) {
ratingBar = (RatingBar)view. findViewById(R.id.ratingBar);
.....
}
and pass newLayout
object to insertDataToDatabaseFromRating
when calling.
Do same for other views which want to access from AlertDialog