如何以降序查看RecyclerView项目

时间:2018-09-24 15:08:03

标签: javascript android-studio

如何从Firebase数据库中按降序查看RecyclerView项目 ImagesActivity.java 这是我的ImagesActivity java

public class ImagesActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private ProgressBar mProgressCircle;
private DatabaseReference mDatabaseRef;
private List<Upload> mUploads;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_images);
    mRecyclerView = findViewById(R.id.recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mProgressCircle = findViewById(R.id.progress_circle);
    mUploads = new ArrayList<>();
    mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
    mDatabaseRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                Upload upload = postSnapshot.getValue(Upload.class);
                mUploads.add(upload);
            }
            mAdapter = new ImageAdapter(ImagesActivity.this, mUploads);
            mRecyclerView.setAdapter(mAdapter);
            mProgressCircle.setVisibility(View.INVISIBLE);
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(ImagesActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
            mProgressCircle.setVisibility(View.INVISIBLE);
        }
    });
}}

ImageAdapter.java 这是我的ImageAdapter

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;

public ImageAdapter(Context context, List<Upload> uploads) {
    mContext = context;
    mUploads = uploads;
}
@Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
    return new ImageViewHolder(v);
}
@Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
    Upload uploadCurrent = mUploads.get(position);
    holder.textViewName.setText(uploadCurrent.getName());
    Picasso.with(mContext)
            .load(uploadCurrent.getImageUrl())
            .placeholder(R.mipmap.ic_launcher)
            .fit()
            .centerCrop()
            .into(holder.imageView);
}
@Override
public int getItemCount() {
    return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
    public TextView textViewName;
    public ImageView imageView;
    public ImageViewHolder(View itemView) {
        super(itemView);
        textViewName = itemView.findViewById(R.id.text_view_name);
        imageView = itemView.findViewById(R.id.image_view_upload);
    }
}}

activity_images.xml 这是我的活动图像xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.codinginflow.firebaseuploadexample.ImagesActivity"> 
<ProgressBar
    android:id="@+id/progress_circle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true" />
<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

image_item.xml 这是我的图像项目xml

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp" 
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <TextView
        android:id="@+id/text_view_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:text="Name"
        android:textColor="@android:color/black"
        android:textSize="20sp" />
    <ImageView
        android:id="@+id/image_view_upload"
        android:layout_width="match_parent"
        android:layout_height="200dp" /> 
</LinearLayout> 

Upload.java 这是“我的项目”的“我的Java”类

public class Upload {
private String mName;
private String mImageUrl;

public Upload() {
    //empty constructor needed
}

public Upload(String name, String imageUrl) {
    if (name.trim().equals("")) {
        name = "No Name";
    }

    mName = name;
    mImageUrl = imageUrl;
}

public String getName() {
    return mName;
}

public void setName(String name) {
    mName = name;
}

public String getImageUrl() {
    return mImageUrl;
}

public void setImageUrl(String imageUrl) {
    mImageUrl = imageUrl;
}}

MainActivity.java

这是我项目的主要活动

 private static final int PICK_IMAGE_REQUEST = 1; 
private Button mButtonChooseImage;
private Button mButtonUpload;
private TextView mTextViewShowUploads;
private EditText mEditTextFileName;
private ImageView mImageView;
private ProgressBar mProgressBar; 
private Uri mImageUri;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef; 
private StorageTask mUploadTask; 
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); 
    mButtonChooseImage = findViewById(R.id.button_choose_image);
    mButtonUpload = findViewById(R.id.button_upload);
    mTextViewShowUploads = findViewById(R.id.text_view_show_uploads);
    mEditTextFileName = findViewById(R.id.edit_text_file_name);
    mImageView = findViewById(R.id.image_view);
    mProgressBar = findViewById(R.id.progress_bar);
    mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
    mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads"); 
    mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openFileChooser();
        }
    }); 
    mButtonUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mUploadTask != null && mUploadTask.isInProgress()) {
                Toast.makeText(MainActivity.this, "Upload in progress", Toast.LENGTH_SHORT).show();
            } else {
                uploadFile();
            }
        }
    }); 
    mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openImagesActivity();
        }
    });
} 
private void openFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
            && data != null && data.getData() != null) {
        mImageUri = data.getData();

        Picasso.with(this).load(mImageUri).into(mImageView);
    }
} 
private String getFileExtension(Uri uri) {
    ContentResolver cR = getContentResolver();
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    return mime.getExtensionFromMimeType(cR.getType(uri));
} 
private void uploadFile() {
    if (mImageUri != null) {
        StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
                + "." + getFileExtension(mImageUri));

        mUploadTask = fileReference.putFile(mImageUri)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mProgressBar.setProgress(0);
                            }
                        }, 500);
                        Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_LONG).show();
                        Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
                                taskSnapshot.getDownloadUrl().toString());
                        String uploadId = mDatabaseRef.push().getKey();
                        mDatabaseRef.child(uploadId).setValue(upload);
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
                        mProgressBar.setProgress((int) progress);
                    }
                });
    } else {
        Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
    }
}
private void openImagesActivity() {
    Intent intent = new Intent(this, ImagesActivity.class);
    startActivity(intent);
}}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context="com.codinginflow.firebaseuploadexample.MainActivity"> 
<Button
    android:id="@+id/button_choose_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Choose file" /> 
<EditText
    android:id="@+id/edit_text_file_name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_toEndOf="@+id/button_choose_image"
    android:hint="Enter file name" /> 
<ImageView
    android:id="@+id/image_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/progress_bar"
    android:layout_below="@id/edit_text_file_name"
    android:layout_marginTop="16dp" /> 
<ProgressBar
    android:id="@+id/progress_bar"
    style="@style/Widget.AppCompat.ProgressBar.Horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/button_upload"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="16dp" /> 
<Button
    android:id="@+id/button_upload"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:text="Upload" />
<TextView
    android:id="@+id/text_view_show_uploads"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/button_upload"
    android:layout_alignTop="@+id/button_upload"
    android:layout_marginStart="25dp"
    android:layout_toEndOf="@+id/button_upload"
    android:gravity="center"
    android:text="Show Uploads"
    android:textSize="16sp" />

1 个答案:

答案 0 :(得分:0)

在ImageActivity中->在onCreate()中

 super.onCreate(savedInstanceState);
setContentView(R.layout.activity_images);
mRecyclerView = findViewById(R.id.recycler_view);
mProgressCircle = findViewById(R.id.progress_circle);


mUploads = new ArrayList<>();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mDatabaseRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
            Upload upload = postSnapshot.getValue(Upload.class);
            mUploads.add(upload);
        }
        mAdapter = new ImageAdapter(ImagesActivity.this, mUploads);
        mRecyclerView.setAdapter(mAdapter);
        mProgressCircle.setVisibility(View.INVISIBLE);
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        Toast.makeText(ImagesActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
        mProgressCircle.setVisibility(View.INVISIBLE);
    }
});

yourAdapter = new YourAdapter(yourList); 
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); 
//this will show lsit from end
//if you want your list to be sorted based on logic, use Collection.sort and then pass the list to adapter
layoutManager.setReverseLayout(true); 
layoutManager.setStackFromEnd(true); 
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setAdapter(yourAdapter);