我正在尝试使用适配器运行我的应用程序,并且在执行此操作时出现此错误:
提到有3个适配器:ReviewsAdapter
,StandupWithKey
和VideoAdapter
。
05-07 20:16:57.707 5326-5326 / com.example.sefi.authenticationproject E / ReviewsAdapter:onBindViewHolder()>> 0 05-07 20:16:57.708 5326-5326 / com.example.sefi.authenticationproject E / AndroidRuntime:FATAL EXCEPTION:main 处理:com.example.sefi.authenticationproject,PID:5326 java.lang.NullPointerException:尝试调用虚方法' void android.widget.TextView.setText(java.lang.CharSequence)'在null对象引用上 在com.example.sefi.authenticationproject.adapter.ReviewsAdapter.onBindViewHolder(ReviewsAdapter.java:48) 在com.example.sefi.authenticationproject.adapter.ReviewsAdapter.onBindViewHolder(ReviewsAdapter.java:18) 在android.support.v7.widget.RecyclerView $ Adapter.onBindViewHolder(RecyclerView.java:6482) 在android.support.v7.widget.RecyclerView $ Adapter.bindViewHolder(RecyclerView.java:6515) 在android.support.v7.widget.RecyclerView $ Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5458) 在android.support.v7.widget.RecyclerView $ Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5724) 在android.support.v7.widget.RecyclerView $ Recycler.getViewForPosition(RecyclerView.java:5563) 在android.support.v7.widget.RecyclerView $ Recycler.getViewForPosition(RecyclerView.java:5559) 在android.support.v7.widget.LinearLayoutManager $ LayoutState.next(LinearLayoutManager.java:2229) 在android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1556) 在android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1516) 在android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:608) 在android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3693) 在android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3109) 在android.view.View.measure(View.java:19734) 在android.support.constraint.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:1210) 在android.support.constraint.ConstraintLayout.onMeasure(ConstraintLayout.java:1550) 在android.view.View.measure(View.java:19734) 在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120) 在android.widget.FrameLayout.onMeasure(FrameLayout.java:185) 在android.view.View.measure(View.java:19734) 在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120) 在android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464) 在android.widget.LinearLayout.measureVertical(LinearLayout.java:758) 在android.widget.LinearLayout.onMeasure(LinearLayout.java:640) 在android.view.View.measure(View.java:19734) 在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120) 在android.widget.FrameLayout.onMeasure(FrameLayout.java:185) 在com.android.internal.policy.DecorView.onMeasure(DecorView.java:687) 在android.view.View.measure(View.java:19734) 在android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2271) 在android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1358) 在android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1607) 在android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246) 在android.view.ViewRootImpl $ TraversalRunnable.run(ViewRootImpl.java:6301) 在android.view.Choreographer $ CallbackRecord.run(Choreographer.java:871) 在android.view.Choreographer.doCallbacks(Choreographer.java:683) 在android.view.Choreographer.doFrame(Choreographer.java:619) 在android.view.Choreographer $ FrameDisplayEventReceiver.run(Choreographer.java:857) 在android.os.Handler.handleCallback(Handler.java:751) 在android.os.Handler.dispatchMessage(Handler.java:95) 在android.os.Looper.loop(Looper.java:154) 在android.app.ActivityThread.main(ActivityThread.java:6077) at java.lang.reflect.Method.invoke(Native Method) 在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:866) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
这是我的档案:
ReviewsAdapter.java
public class ReviewsAdapter extends RecyclerView.Adapter<ReviewsAdapter.ReviewViewHolder> {
private final String TAG = "ReviewsAdapter";
private List<Review> reviewsList;
public ReviewsAdapter(List<Review> reviewsList) {
this.reviewsList = reviewsList;
}
@Override
public ReviewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.e(TAG,"onCreateViewHolder() >>");
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_standup_details, parent, false);
Log.e(TAG,"onCreateViewHolder() <<");
return new ReviewViewHolder(parent.getContext(),itemView);
}
@Override
public void onBindViewHolder(ReviewViewHolder holder, int position) {
Log.e(TAG,"onBindViewHolder() >> " + position);
Review review = reviewsList.get(position);
holder.getUserMail().setText(review.getUserEmail());
holder.getUserReview().setText(review.getUserReview());
holder.getUserRating().setRating(review.getUserRating());
Log.e(TAG,"onBindViewHolder() << "+ position);
}
@Override
public int getItemCount() {
return reviewsList.size();
}
public class ReviewViewHolder extends RecyclerView.ViewHolder {
private TextView userReview;
private TextView userMail;
private RatingBar userRating;
public ReviewViewHolder(Context context, View view) {
super(view);
userReview = (TextView) view.findViewById(R.id.user_review);
userMail = (TextView) view.findViewById(R.id.user_mail);
userRating = (RatingBar) view.findViewById(R.id.user_rating);
}
public TextView getUserReview() {
return userReview;
}
public void setUserReview(TextView userReview) {
this.userReview = userReview;
}
public TextView getUserMail() {
return userMail;
}
public void setUserMail(TextView userMail) {
this.userMail = userMail;
}
public RatingBar getUserRating() {
return userRating;
}
public void setUserRating(RatingBar userRating) {
this.userRating = userRating;
}
}
}
StandupDetails.java
public class StandupDetails extends Activity {
public final String TAG = "StandupDetails";
private Standup standup;
private String key;
private User user;
private FloatingActionButton writeReview;
private Button buyPlay;
private MediaPlayer mediaPlayer;
private RecyclerView recyclerViewStandupReviews;
private DatabaseReference standupReviewsRef;
private List<Review> reviewsList = new ArrayList<>();
private boolean standupWasPurchased;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_standup_details);
key = getIntent().getStringExtra("key");
standup = getIntent().getParcelableExtra("standup");
user = getIntent().getParcelableExtra("user");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
StorageReference thumbRef = FirebaseStorage
.getInstance()
.getReference()
.child("thumbs/" + standup.getThumbImage());
// Load the image using Glide
thumbRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Glide.with(StandupDetails.this).load(uri)
.into((ImageView)findViewById(R.id.imageViewSong));
}
});
((TextView) findViewById(R.id.textViewName)).setText(standup.getName());
buyPlay = ((Button) findViewById(R.id.buttonBuyPlay));
buyPlay.setText("BUY $" + standup.getPrice());
Iterator i = user.getMyStandups().iterator();
while (i.hasNext()) {
if (i.next().equals(key)) {
standupWasPurchased = true;
buyPlay.setText("PLAY");
break;
}
}
buyPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.e(TAG, "buyPlay.onClick() >> file=" + standup.getName());
FirebaseUser fbUser = FirebaseAuth.getInstance().getCurrentUser();
String info = fbUser.getProviderId();
if (standupWasPurchased) {
Log.e(TAG, "buyPlay.onClick() >> Playing purchased standup");
//User purchased the standup so he can play it
playCurrentStandup(standup.getFile());
}
else{
Log.e(TAG, "buyPlay.onClick() >> Purchase the standup");
user.getMyStandups().add(key);
user.upgdateTotalPurchase(standup.getPrice());
DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("Users");
userRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(user);
standupWasPurchased = true;
buyPlay.setText("PLAY");
}
Log.e(TAG, "playStandup.onClick() <<");
}
});
writeReview = (FloatingActionButton) findViewById(R.id.buttonNewReview);
writeReview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.e(TAG, "writeReview.onClick() >>");
Intent intent = new Intent(getApplicationContext(),ReviewActivity.class);
intent.putExtra("standup", standup);
intent.putExtra("key", key);
intent.putExtra("user",user);
startActivity(intent);
finish();
Log.e(TAG, "writeReview.onClick() <<");
}
});
recyclerViewStandupReviews = findViewById(R.id.standup_reviews);
recyclerViewStandupReviews.setHasFixedSize(true);
recyclerViewStandupReviews.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerViewStandupReviews.setItemAnimator(new DefaultItemAnimator());
ReviewsAdapter reviewsAdapter = new ReviewsAdapter(reviewsList);
recyclerViewStandupReviews.setAdapter(reviewsAdapter);
standupReviewsRef = FirebaseDatabase.getInstance().getReference("Standup/" + key +"/reviews");
standupReviewsRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
Log.e(TAG, "onDataChange() >> Standup/" + key);
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Review review = dataSnapshot.getValue(Review.class);
reviewsList.add(review);
}
recyclerViewStandupReviews.getAdapter().notifyDataSetChanged();
Log.e(TAG, "onDataChange(Review) <<");
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled(Review) >>" + databaseError.getMessage());
}
});
Log.e(TAG, "onCreate() <<");
}
@Override
protected void onPause() {
super.onPause();
stopPlayingCurrentStandup();
}
private void playCurrentStandup(String standupFile) {
Log.e(TAG, "playCurrentStandup() >> standupFile=" + standupFile);
if (stopPlayingCurrentStandup()) {
Log.e(TAG, "playCurrentStandup() << Stop playing current Standup");
return;
}
FirebaseStorage.getInstance()
.getReference("StandupsFile/" + standupFile)
.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri downloadUrl) {
Log.e(TAG, "onSuccess() >> " + downloadUrl.toString());
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(downloadUrl.toString()));
intent.setDataAndType(Uri.parse(downloadUrl.toString()), "video/mp4");
startActivity(intent);
//mediaPlayer.setDataSource(downloadUrl.toString());
//mediaPlayer.prepare(); // might take long! (for buffering, etc)
//mediaPlayer.start();
} catch (Exception e) {
Log.w(TAG, "playStandup() error:" + e.getMessage());
}
Log.e(TAG, "onSuccess() <<");
}
});
Log.e(TAG, "playCurrentStandup() << ");
}
private boolean stopPlayingCurrentStandup() {
if (mediaPlayer.isPlaying()) {
Log.e(TAG, "onSuccess() >> Stop the media player");
//Stop the media player
mediaPlayer.stop();
mediaPlayer.reset();
buyPlay.setText("PLAY");
return true;
}
return false;
}
}
ReviewActivity
public class ReviewActivity extends AppCompatActivity {
private final String TAG = "ReviewActivity";
private Standup standup;
private String key;
private User user;
private int prevRating = -1;
private TextView userReview;
private RatingBar userRating;
private DatabaseReference standupRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.e(TAG, "onCreate() >>");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_review);
key = getIntent().getStringExtra("key");
standup = getIntent().getParcelableExtra("standup");
user = getIntent().getParcelableExtra("user");
userReview = findViewById(R.id.new_user_review);
userRating = findViewById(R.id.new_user_rating);
standupRef = FirebaseDatabase.getInstance().getReference("Standup/" + key);
standupRef.child("/reviews/" + FirebaseAuth.getInstance().getCurrentUser().getUid()).
addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
Log.e(TAG, "onDataChange(Review) >> " + snapshot.getKey());
Review review = snapshot.getValue(Review.class);
if (review != null) {
userReview.setText(review.getUserReview());
userRating.setRating(review.getUserRating());
prevRating = review.getUserRating();
}
Log.e(TAG, "onDataChange(Review) <<");
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled(Review) >>" + databaseError.getMessage());
}
});
Log.e(TAG, "onCreate() <<");
}
public void onSubmitClick(View v) {
Log.e(TAG, "onSubmitClick() >>");
standupRef.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
Log.e(TAG, "doTransaction() >>" );
Standup standup = mutableData.getValue(Standup.class);
if (standup == null ) {
Log.e(TAG, "doTransaction() << standup is null" );
return Transaction.success(mutableData);
}
if (prevRating == -1) {
// Increment the review count and rating only in case the user enters a new review
standup.incrementReviewCount();
standup.incrementRating((int)userRating.getRating());
} else{
standup.incrementRating((int)userRating.getRating() - prevRating);
}
mutableData.setValue(standup);
Log.e(TAG, "doTransaction() << standup was set");
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean committed, DataSnapshot dataSnapshot) {
Log.e(TAG, "onComplete() >>" );
if (databaseError != null) {
Log.e(TAG, "onComplete() << Error:" + databaseError.getMessage());
return;
}
if (committed) {
Review review = new Review(
userReview.getText().toString(),
(int)userRating.getRating(),
user.getEmail());
standupRef.child("/reviews/" + FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(review);
}
Intent intent = new Intent(getApplicationContext(),StandupDetails.class);
intent.putExtra("standup", standup);
intent.putExtra("key", key);
intent.putExtra("user",user);
startActivity(intent);
finish();
Log.e(TAG, "onComplete() <<" );
}
});
Log.e(TAG, "onSubmitClick() <<");
}
}
StandupPlayerMain.java
public class StandupPlayerMain extends Activity {
private final String TAG = "StandUp Player Tag";
private DatabaseReference allStandupRef;
private DatabaseReference myUserRef;
private List<StandupWithKey> standupList = new ArrayList<>();
private GoogleSignInClient mGoogleSignInClient;
private RecyclerView recyclerView;
private VideoAdapter standupAdapter;
private User myUser;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_standup_player_main);
Log.e(TAG, "onCreate() >>");
mAuth= FirebaseAuth.getInstance();
recyclerView = (RecyclerView) findViewById(R.id.standups_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
FirebaseUser fbUser = FirebaseAuth.getInstance().getCurrentUser();
if (fbUser != null) {
myUserRef = FirebaseDatabase.getInstance().getReference("Users/" + fbUser.getUid());
myUserRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
Log.e(TAG, "onDataChange(User) >> " + snapshot.getKey());
myUser = snapshot.getValue(User.class);
getAllStandups();
Log.e(TAG, "onDataChange(User) <<");
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled(Users) >>" + databaseError.getMessage());
}
});
Log.e(TAG, "onCreate() <<");
} else {
getAllStandups();
}
}
private void getAllStandups() {
Log.e(TAG,"GET ALL STANDUPS >>");
standupList.clear();
standupAdapter = new VideoAdapter(standupList,myUser);
recyclerView.setAdapter(standupAdapter);
//getAllSongsUsingValueListenrs();
getAllVideoUsingChildListenrs();
Log.e(TAG,"GET ALL STANDUPS <<");
}
private void getAllVideoUsingChildListenrs() {
allStandupRef = FirebaseDatabase.getInstance().getReference("Standup");
allStandupRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
Log.e(TAG, "onDataChange(Standup) >> " + snapshot.getKey());
updateStandupList(snapshot);
Log.e(TAG, "onDataChange(Standup) <<");
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled(Songs) >>" + databaseError.getMessage());
}
});
}
private void getAllSongsUsingChildListenrs() {
allStandupRef = FirebaseDatabase.getInstance().getReference("Standup");
allStandupRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot snapshot, String previousChildName){
Log.e(TAG, "onChildAdded(Standup) >> " + snapshot.getKey());
StandupWithKey standupwithKey = new StandupWithKey(snapshot.getKey(),snapshot.getValue(Standup.class));
standupList.add(standupwithKey);
recyclerView.getAdapter().notifyDataSetChanged();
Log.e(TAG, "onChildAdded(Standup) <<");
}
@Override
public void onChildChanged(DataSnapshot snapshot, String previousChildName){
Log.e(TAG, "onChildChanged(Standup) >> " + snapshot.getKey());
Standup standup = snapshot.getValue(Standup.class);
String key = snapshot.getKey();
for (int i = 0 ; i < standupList.size() ; i++) {
StandupWithKey standupWithKey = (StandupWithKey) standupList.get(i);
if (standupWithKey.getKey().equals(snapshot.getKey())) {
standupWithKey.setStandup(standup);
recyclerView.getAdapter().notifyDataSetChanged();
break;
}
}
Log.e(TAG, "onChildChanged(Standup) <<");
}
@Override
public void onChildMoved(DataSnapshot snapshot, String previousChildName){
Log.e(TAG, "onChildMoved(Standup) >> " + snapshot.getKey());
Log.e(TAG, "onChildMoved(Standup) << Doing nothing");
}
@Override
public void onChildRemoved(DataSnapshot snapshot){
Log.e(TAG, "onChildRemoved(Standup) >> " + snapshot.getKey());
Standup standup =snapshot.getValue(Standup.class);
String key = snapshot.getKey();
for (int i = 0 ; i < standupList.size() ; i++) {
StandupWithKey standupwithKey = (StandupWithKey) standupList.get(i);
if (standupwithKey.getKey().equals(snapshot.getKey())) {
standupList.remove(i);
recyclerView.getAdapter().notifyDataSetChanged();
Log.e(TAG, "onChildRemoved(Standup) >> i="+i);
break;
}
}
Log.e(TAG, "onChildRemoved(Standup) <<");
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled(Standup) >>" + databaseError.getMessage());
}
});
}
private void updateStandupList(DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Standup standup = dataSnapshot.getValue(Standup.class);
Log.e(TAG, "updateStandupList() >> adding standup: " + standup.getName());
String key = dataSnapshot.getKey();
standupList.add(new StandupWithKey(key,standup));
}
recyclerView.getAdapter().notifyDataSetChanged();
}
public void onSignOutClick(View V) {
Log.e(TAG, "onSignOutClick() >>");
logOutFromGoogleAccount();
LoginManager.getInstance().logOut();
mAuth.signOut();
Intent intent = new Intent(StandupPlayerMain.this,LogInActivity.class);
startActivity(intent);
Log.e(TAG, "onSignOutClick() <<");
}
private void logOutFromGoogleAccount()
{
Log.e(TAG, "logOutFromGoogleAccount() >>");
GoogleSignInOptions gso = new GoogleSignInOptions
.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestProfile()
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
mGoogleSignInClient.signOut();
Log.e(TAG, "logOutFromGoogleAccount() <<");
}
public void onSearchButtonClick(View v) {
String searchString = ((EditText)findViewById(R.id.edit_text_search_standup)).getText().toString();
String orderBy = ((RadioButton)findViewById(R.id.radioButtonByReviews)).isChecked() ? "reviewsCount" : "price";
Query searchStandup;
Log.e(TAG, "onSearchButtonClick() >> searchString="+searchString+ ",orderBy="+orderBy);
standupList.clear();
if (searchString != null && !searchString.isEmpty()) {
searchStandup = allStandupRef.orderByChild("name").startAt(searchString).endAt(searchString + "\uf8ff");
} else {
searchStandup = allStandupRef.orderByChild(orderBy);
}
searchStandup.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
Log.e(TAG, "onDataChange(Query) >> " + snapshot.getKey());
updateStandupList(snapshot);
Log.e(TAG, "onDataChange(Query) <<");
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled() >>" + databaseError.getMessage());
}
});
Log.e(TAG, "onSearchButtonClick() <<");
}
public void onRadioButtonCLick(View v) {
switch (v.getId()) {
case R.id.radioButtonByPrice:
((RadioButton)findViewById(R.id.radioButtonByReviews)).setChecked(false);
break;
case R.id.radioButtonByReviews:
((RadioButton)findViewById(R.id.radioButtonByPrice)).setChecked(false);
break;
}
}
}
答案 0 :(得分:4)
您对StandupDetails
活动和回收商列表项使用相同的布局:
的 activity_standup_details.xml 强>
setContentView(R.layout.activity_standup_details);
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_standup_details, parent, false);
您可能想要使用不同的布局。因此,视图持有者中的findViewById返回null,这就是你获得NPE的原因。