我有一个显示评级栏的警报。
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);
当我触发onclick侦听器时,它显示NULL POINTER EXCEPTION。和第二行错误表示getNumStars()行中的错误。之后强制关闭。
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());
我可以通过其他方式获得评级栏的价值吗?我见过很少像ratingBar.getRating(); ratingBar.getNumStars();
所有这些都无法工作......即使我将值直接放入int。
final int cleaninput = (int) cleanbar.getRating(); //fails
EDITTED(SOLVE)::
final RatingBar cleanbar = (RatingBar)v.findViewById(R.id.clealiness);
我将评级栏替换为v而不是它的工作原理!我不知道原因>。<
答案 0 :(得分:2)
我认为你的问题是:
final RatingBar cleanbar = (RatingBar) ratingbar.findViewById(R.id.clealiness);
它不会正确初始化RatingBar,因为你没有从Activity的布局(包含RatingBar)初始化RatingBar,这就是你在
获得NPE
的原因
cleanbar.getNumStars() // cleanbar is assigned as null
将其更改为
final RatingBar cleanbar = (RatingBar) findViewById(R.id.clealiness);
现在应该可以了。
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();
现在正确获取价值:
RatingBar cleanbar = (RatingBar) ratingView.findViewById(R.id.clealiness);
您需要将RatingBar
与View
分配给您。
现在它应该有效:
final int cleaninput = (int) cleanbar.getRating();