سؤال

i've got a alertdialog which shows rating bar.

LayoutInflater rating = LayoutInflater.from(RatingActivity.this);
            final View v = rating.inflate(R.layout.rating_layout, null);

            AlertDialog.Builder adb = new AlertDialog.Builder(RatingActivity.this);
            adb.setTitle("Rate us!);
            adb.setView(v);
            AlertDialog ratingbar = adb.create();

final RatingBar cleanbar = (RatingBar) ratingbar.findViewById(R.id.clealiness);

when I triggered onclick listener, it shows NULL POINTER EXCEPTION. and 2nd line error says error in getNumStars() line.. Force close after that.

adb.setPositiveButton("Rate", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
    //this line error. means they cant get the rating value?
final String cleaninput = Integer.toString(cleanbar.getNumStars());

may i know any other ways to get the value of ratingbar? i've seen few like ratingBar.getRating(); ratingBar.getNumStars();

all of them could not work... even i put the value direct into int.

final int cleaninput = (int) cleanbar.getRating();  //fails

EDITTED (SOLVE)::

final RatingBar cleanbar = (RatingBar)v.findViewById(R.id.clealiness); 

i replace the ratingbar to v instead and it works! i do not know the reason >.<

هل كانت مفيدة؟

المحلول

I think your problem is this:

final RatingBar cleanbar = (RatingBar) ratingbar.findViewById(R.id.clealiness);

It won't initialise correctly RatingBar because you are not initialising RatingBar from layout of Activity(that contains RatingBar) and this is reason why you get NPE at

cleanbar.getNumStars() // cleanbar is assigned as null

Change it to

final RatingBar cleanbar = (RatingBar) findViewById(R.id.clealiness);

Now it should work.

Update:

LayoutInflater rating = LayoutInflater.from(RatingActivity.this);
final View ratingView = rating.inflate(R.layout.rating_layout, null);

AlertDialog.Builder adb = new AlertDialog.Builder(RatingActivity.this);               
adb.setTitle("Rate us!);
adb.setView(ratingView);

AlertDialog ratingbar = adb.create();

Now for getting value correctly:

RatingBar cleanbar = (RatingBar) ratingView.findViewById(R.id.clealiness);

You need to assign RatingBar with View you inflated.

Now it should works:

final int cleaninput = (int) cleanbar.getRating(); 
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top