Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

java - RecyclerView not shows all items

I create a RecyclerView to show some test post for my app. But when i run my app i can see only the username and not the test post imageView when i have create on my resource file. I start learning today about RecyclerView and i have a lot of problems with this view.

NOTE: i don't want to show any image from any url for now, but only the image when i already save in my drawable folder. And i know when is not reason to add the getImageUrl method in the model but maybe i will need it in the production, and that's the reason when i don't remove this method

HomeActivity code:

public class HomeActivity extends AppCompatActivity {

public Uri imguri;
DatabaseReference mRef;
final StorageReference mStorageRef = FirebaseStorage.getInstance().getReference("images");
List<PostModel> postList;

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


    final RecyclerView recyclerView = findViewById(R.id.recyclerView);
    RecyclerView.Adapter recyclerAdapter;
    final FirebaseAuth mAuth = FirebaseAuth.getInstance();
    final FirebaseUser user = mAuth.getCurrentUser();
    final ImageButton new_post = findViewById(R.id.new_post_btn);
    final ImageButton settings = findViewById(R.id.settingsButton);


    if (user == null) {
        finish();
        startActivity(new Intent(HomeActivity.this, MainActivity.class));
    }

    mRef = FirebaseDatabase.getInstance().getReference("users");

    postList = new ArrayList<>();

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

    for (int i = 0; i < 3; i++) {
        PostModel postModel = new PostModel("user " + i, "hello world");

        postList.add(postModel);
}

    recyclerAdapter = new RecyclerAdapter(postList, this);
    recyclerView.setAdapter(recyclerAdapter);


    settings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(HomeActivity.this,SettingsActivity.class));
        }
    });

    new_post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            fileChoose();
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null){
        imguri = data.getData();
    }
}

public String getFileExtension(Uri uri){
    ContentResolver cr = getContentResolver();
    MimeTypeMap typeMap = MimeTypeMap.getSingleton();
    return typeMap.getExtensionFromMimeType(cr.getType(uri));
}

public void FileUpload(){
    StorageReference ref = mStorageRef.child(System.currentTimeMillis() + "." + getFileExtension(imguri));

    ref.putFile(imguri)
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    // Get a URL to the uploaded content
                    //Uri downloadUrl = taskSnapshot.getDownloadUrl();

                    Toast.makeText(HomeActivity.this, "Meme image successfully uploaded.", Toast.LENGTH_SHORT).show();
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    // Handle unsuccessful uploads
                    // ...
                    Toast.makeText(HomeActivity.this, "error: " + exception, Toast.LENGTH_SHORT).show();
                }
            });
}

public void fileChoose(){
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(intent.ACTION_GET_CONTENT);
    startActivityForResult(intent,1);
}

}

Adapter code:

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder>{

List<PostModel> postList;
Context context;

public RecyclerAdapter(List<PostModel> postList, Context context) {
    this.postList = postList;
    this.context = context;
}

@NonNull
@NotNull
@Override
public ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.post_item,parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull @NotNull ViewHolder holder, int position) {
    PostModel postModel = postList.get(position);

    holder.username.setText(postModel.getName());
}

@Override
public int getItemCount() {
    return postList.size();
}

public class ViewHolder extends RecyclerView.ViewHolder{
    TextView username;
    ImageView postImg;

    public ViewHolder(@NonNull @NotNull View itemView) {
        super(itemView);

        username = itemView.findViewById(R.id.post_username);
        postImg = itemView.findViewById(R.id.post_image);
    }
}

}

XML resource file:

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:padding="15dp"
    app:cardCornerRadius="20dp"
    android:layout_gravity="center_horizontal"
    app:cardElevation="20dp"
    android:outlineSpotShadowColor="@color/teal_200">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/post_username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:layout_marginStart="10dp"
        android:layout_marginTop="5dp"
        android:clickable="true"
        android:focusable="true"
        android:text="By george sepetadelis"
        android:textColor="@color/black"
        android:textSize="17sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/post_image"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

    <ImageView
        android:id="@+id/post_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/post_username"
        tools:srcCompat="@drawable/m1" />

</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

And also my model code:

public class PostModel {
String name;
String imgUrl;

public PostModel(String name, String imgUrl) {
    this.name = name;
    this.imgUrl = imgUrl;
}

public String getName() {
    return name;
}

public String getImgUrl() {
    return imgUrl;
}
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Change tools:srcCompat to app:scrCompat because tools namespace is used only to preview the content in the Android studio preview tab and when you run the app, attributes with tools namespace is removed from the xml file

Check the official docs for more information on tools ns


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...