Firebase UI:RecyclerView 中的项目未显示。

huangapple go评论88阅读模式
英文:

Firebase UI : RecyclerView items are not shown

问题

// AllUsersActivity.java
public class AllUsersActivity extends AppCompatActivity {
    // ... (omitting imports and other code)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_users);

        recyclerView = findViewById(R.id.recycler_view);

        linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);

        query = FirebaseDatabase.getInstance().getReference().child("Users");

    }

    FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>()
            .setQuery(query, Users.class)
            .build();

    FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(options) {

        @Override
        protected void onBindViewHolder(@NonNull UsersViewHolder holder, int position, @NonNull Users model) {
            holder.setName(model.getName());
        }

        @Override
        public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.activity_all_users, parent, false);

            return new UsersViewHolder(view);
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        adapter.startListening();
    }

    @Override
    protected void onStop() {
        super.onStop();
        adapter.stopListening();
    }
}

class UsersViewHolder extends RecyclerView.ViewHolder {
    View mView;

    UsersViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
    }

    public void setName(String name) {
        TextView mName = mView.findViewById(R.id.user_single_name);
        mName.setText(name);
    }
}
// ProfileInfoActivity.java
public class ProfileInfoActivity extends AppCompatActivity {
    // ... (omitting imports and other code)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_info);

        mDisplayImage = findViewById(R.id.circle_image);
        mName = findViewById(R.id.name);
        mEditName = findViewById(R.id.et_name);
        mEmail = findViewById(R.id.et_email_address);
        mStatus = findViewById(R.id.status);
        mStatusBtn = findViewById(R.id.status_btn);

        // ... (other initialization)

        mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);
        mDatabaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                // ... (data retrieval and setting to views)
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

        mDisplayImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent galleryIntent = new Intent();
                galleryIntent.setType("image/*");
                galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

                startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);
            }
        });

        mStatusBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // ... (status button click handling)
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == GALLERY_PICK && resultCode == RESULT_OK ) {
            Uri imageUri = data.getData();

            CropImage.activity(imageUri)
                    .setAspectRatio(1, 1)
                    .start(this);
        }

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                // ... (image cropping and uploading)
            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Exception error = result.getError();
            }
        }
    }
}

Note: I've translated the provided code snippets, but please keep in mind that this code involves Firebase and UI interactions. Ensure that you have the necessary Firebase dependencies and configurations set up correctly in your project.

英文:

I have been trying to implement Firebase-UI in my app with RecyclerView.
I created a recyclerView users list in a chat app with Realtime database and Firebase-UI, I wanted to retrieve data from ProfileActivity and display them in my AllUsersActivity. The issue is that the RecyclerView items are not displaying and I'm getting this error :

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.schoolteacher, PID: 19631
java.lang.NullPointerException: Attempt to invoke virtual method &#39;com.google.firebase.database.ChildEventListener com.google.firebase.database.Query.addChildEventListener(com.google.firebase.database.ChildEventListener)&#39; on a null object reference
at com.firebase.ui.database.FirebaseArray.onCreate(FirebaseArray.java:54)
at com.firebase.ui.common.BaseObservableSnapshotArray.addChangeEventListener(BaseObservableSnapshotArray.java:97)
at com.firebase.ui.database.FirebaseRecyclerAdapter.startListening(FirebaseRecyclerAdapter.java:52)
at com.example.schoolteacher.AllUsersActivity.onStart(AllUsersActivity.java:112)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1419)
at android.app.Activity.performStart(Activity.java:7479)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3454)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
at android.os.Handler.dispatchMessage(Handler.java:112)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)

Here is my code :

AllUsersActivity.java

public class AllUsersActivity extends AppCompatActivity {
private DatabaseReference mUsersDatabase;
private LinearLayoutManager linearLayoutManager;
private RecyclerView recyclerView;
private Query query;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_users);
recyclerView = findViewById(R.id.recycler_view);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
query = FirebaseDatabase.getInstance().getReference().child(&quot;Users&quot;);
}       
FirebaseRecyclerOptions&lt;Users&gt; options = new FirebaseRecyclerOptions.Builder&lt;Users&gt;()
.setQuery(query, Users.class)
.build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter&lt;Users, UsersViewHolder&gt;(options) {
@Override
protected void onBindViewHolder(@NonNull UsersViewHolder holder, int position, @NonNull Users model) {
holder.setName(model.getName());
}
@Override
public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_all_users, parent, false);
return new UsersViewHolder(view);
}
};
@Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
@Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name) {
TextView mName = mView.findViewById(R.id.user_single_name);
mName.setText(name);
}
}

ProfileInfoActivity

public class ProfileInfoActivity extends AppCompatActivity {
private DatabaseReference mDatabaseReference;
private FirebaseUser mCurrentUser;
private CircleImageView mDisplayImage;
private TextView mName;
private TextInputEditText mEditName, mEmail;
private TextView mStatus;
private ImageButton mStatusBtn;
private static final int GALLERY_PICK = 1;
private StorageReference mImageStorage;
private ProgressDialog mProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_info);
mDisplayImage = findViewById(R.id.circle_image);
mName = findViewById(R.id.name);
mEditName = findViewById(R.id.et_name);
mEmail = findViewById(R.id.et_email_address);
mStatus = findViewById(R.id.status);
mStatusBtn = findViewById(R.id.status_btn);
mImageStorage = FirebaseStorage.getInstance().getReference();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String userID = mCurrentUser.getUid();
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child(&quot;Users&quot;).child(userID);
mDatabaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.child(&quot;name&quot;).getValue().toString();
String et_name = dataSnapshot.child(&quot;name&quot;).getValue().toString();
String et_email_adress = dataSnapshot.child(&quot;email&quot;).getValue().toString();
String image = dataSnapshot.child(&quot;image&quot;).getValue().toString();
String status = dataSnapshot.child(&quot;status&quot;).getValue().toString();
String thumb_image = dataSnapshot.child(&quot;thumb_image&quot;).getValue().toString();
mName.setText(name);
mEditName.setText(et_name);
mEmail.setText(et_email_adress);
mStatus.setText(&quot;Teacher at &quot;+ status);
Picasso.get().load(image).into(mDisplayImage);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
mDisplayImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setType(&quot;image/*&quot;);
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, &quot;SELECT IMAGE&quot;), GALLERY_PICK);
}
});
mStatusBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//send status data to changeSchoolActivity to retrieve it
String status_value = mStatus.getText().toString();
Intent status_intent = new Intent(ProfileInfoActivity.this, ChangeSchoolActivity.class);
status_intent.putExtra(&quot;status_value&quot;, status_value);
startActivity(status_intent);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_PICK &amp;&amp; resultCode == RESULT_OK ) {
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setAspectRatio(1, 1)
.start(this);
//Toast.makeText(ProfileInfoActivity.this, imageUri, Toast.LENGTH_SHORT).show();
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mProgressDialog = new ProgressDialog(ProfileInfoActivity.this);
mProgressDialog.setTitle(&quot;Uploading Image...&quot;);
mProgressDialog.setMessage(&quot;Please wait while we upload and process the image&quot;);
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
Uri resultUri = result.getUri();
String current_user_id = mCurrentUser.getUid();
final StorageReference filepath = mImageStorage.child(&quot;profile_images&quot;).child(current_user_id + &quot;.jpg&quot;);
filepath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener&lt;UploadTask.TaskSnapshot&gt;() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener&lt;Uri&gt;() {
@Override
public void onSuccess(Uri uri) {
String download_url = uri.toString();
mDatabaseReference.child(&quot;image&quot;).setValue(download_url).addOnSuccessListener(new OnSuccessListener&lt;Void&gt;() {
@Override
public void onSuccess(Void aVoid) {
mProgressDialog.dismiss();
Toast.makeText(ProfileInfoActivity.this,&quot;Success Uploading&quot;,Toast.LENGTH_SHORT).show();
}
});
}
});
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}

答案1

得分: 1

根据您的最后一条评论:

> protected void onStart() { super.onStart(); firebaseRecyclerAdapter.startListening(); }

出现错误的就是这一行。为了解决这个问题,请将 firebaseRecyclerAdapter 变量创建为全局变量,方法是在代码中添加以下行:

private FirebaseRecyclerAdapter firebaseRecyclerAdapter;

紧接着:

private Query query;

然后从您的代码中删除类型声明部分:

// FirebaseRecyclerAdapter 不再存在
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter&lt;Users, UsersViewHolder&gt;(firebaseRecyclerOptions) {
    @NonNull
    @Override
    public UsersViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_single_layout, parent, false);
        return new UsersViewHolder(mView);
    }

    @Override
    protected void onBindViewHolder(@NonNull UsersViewHolder holder, int position, @NonNull Users model) {
        holder.setName(model.getName());
    }
};
英文:

According to your last comment:

> protected void onStart() { super.onStart(); firebaseRecyclerAdapter.startListening(); }

Is the line at which the error occurs. To solve this, please create the firebaseRecyclerAdapter variable as a global variable by adding the following line of code:

private FirebaseRecyclerAdapter firebaseRecyclerAdapter;

Right after:

private Query query;

And remove the type declaration from your code:

//FirebaseRecyclerAdapter does not exist anymore
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter&lt;Users, UsersViewHolder&gt;(firebaseRecyclerOptions) {
@NonNull
@Override
public UsersViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_single_layout, parent, false);
return new UsersViewHolder(mView);
}
@Override
protected void onBindViewHolder(@NonNull UsersViewHolder holder, int position, @NonNull Users model) {
holder.setName(model.getName());
}
};

huangapple
  • 本文由 发表于 2020年4月3日 20:41:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/61012146.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定