Recently Added

6/recent/ticker-posts

Add Sorting option in Recyclerview part 8

 

In this blog, I am going to show you how to sort recycler view  like sort by name, sort by date, sort by size in the android studio
So let's start



Create an Item in your menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">


<item
android:id="@+id/search"
android:icon="@drawable/search_icon"
android:title="Search"
app:actionViewClass="androidx.appcompat.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView" />

<item
android:id="@+id/sortby"
android:icon="@drawable/ic_baseline_sort_24"
android:title="SortBy"
app:showAsAction="ifRoom">

<menu>

<item
android:id="@+id/sort_by_date"
android:title="ByDate"
app:showAsAction="never"/>

<item
android:id="@+id/sort_by_name"
android:title="ByName"
app:showAsAction="never"/>

<item
android:id="@+id/sort_by_size"
android:title="BySize"
app:showAsAction="never"/>

</menu>

</item>

</menu>


Add this code in your VideoFolder.java

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.player.R;
import com.example.player.VideoModel;
import com.example.player.adapter.VideosAdapter;

import java.util.ArrayList;
import java.util.Locale;

public class VideoFolder extends AppCompatActivity
implements SearchView.OnQueryTextListener {

private static final String MY_SORT_PREF = "sortOrder";
Toolbar toolbar;
private RecyclerView recyclerView;
private String name;
private ArrayList<VideoModel> videoModelArrayList = new ArrayList<>();
private VideosAdapter videosAdapter;

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


recyclerView = findViewById(R.id.video_recyclerview);

name = getIntent().getStringExtra("folderName");
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(getResources().getDrawable(R.drawable.go_back));
int index = name.lastIndexOf("/");
String onlyFolderName = name.substring(index + 1);
toolbar.setTitle(onlyFolderName);
loadVideos();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_toolbar, menu);
MenuItem menuItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView) menuItem.getActionView();
ImageView ivClose = searchView.findViewById(androidx.appcompat.R.id.search_close_btn);
ivClose.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.white),
android.graphics.PorterDuff.Mode.SRC_IN);
searchView.setQueryHint("Search file name");
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onQueryTextSubmit(String query) {
return false;
}

@Override
public boolean onQueryTextChange(String newText) {
String input = newText.toLowerCase();
ArrayList<VideoModel> searchList = new ArrayList<>();
for (VideoModel model : videoModelArrayList) {
if (model.getTitle().toLowerCase().contains(input)) {
searchList.add(model);
}
}
videosAdapter.updateSearchList(searchList);

return false;
}

private void loadVideos() {
videoModelArrayList = getallVideoFromFolder(this, name);
if (name != null && videoModelArrayList.size() > 0) {
videosAdapter = new VideosAdapter(videoModelArrayList, this);
//if your recyclerview lagging then just add this line
recyclerView.setHasFixedSize(true);
recyclerView.setItemViewCacheSize(20);
recyclerView.setDrawingCacheEnabled(true);
recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
recyclerView.setNestedScrollingEnabled(false);

recyclerView.setAdapter(videosAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this,
RecyclerView.VERTICAL, false));
} else {
Toast.makeText(this, "can't find any videos", Toast.LENGTH_SHORT).show();
}

}

private ArrayList<VideoModel> getallVideoFromFolder(Context context, String name) {
SharedPreferences preferences = getSharedPreferences(MY_SORT_PREF, MODE_PRIVATE);
//which one you want to set default in sorting
// i am setting by date
String sort = preferences.getString("sorting", "sortByDate");
String order = null;
switch (sort) {

case "sortByDate":
order = MediaStore.MediaColumns.DATE_ADDED + " ASC";
break;

case "sortByName":
order = MediaStore.MediaColumns.DISPLAY_NAME + " ASC";
break;

case "sortBySize":
order = MediaStore.MediaColumns.DATE_ADDED + " DESC";
break;

}
ArrayList<VideoModel> list = new ArrayList<>();
Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] projection = {
MediaStore.Video.Media._ID,
MediaStore.Video.Media.DATA,
MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.SIZE,
MediaStore.Video.Media.HEIGHT,
MediaStore.Video.Media.DURATION,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.BUCKET_DISPLAY_NAME,
MediaStore.Video.Media.RESOLUTION
};
String selection = MediaStore.Video.Media.DATA + " like?";
String[] selectionArgs = new String[]{"%" + name + "%"};

Cursor cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, order);

if (cursor != null) {
while (cursor.moveToNext()) {

String id = cursor.getString(0);
String path = cursor.getString(1);
String title = cursor.getString(2);
int size = cursor.getInt(3);
String resolution = cursor.getString(4);
int duration = cursor.getInt(5);
String disName = cursor.getString(6);
String bucket_display_name = cursor.getString(7);
String width_height = cursor.getString(8);

//this method convert 1204 in 1MB
String human_can_read = null;
if (size < 1024) {
human_can_read = String.format(context.getString(R.string.size_in_b), (double) size);
} else if (size < Math.pow(1024, 2)) {
human_can_read = String.format(context.getString(R.string.size_in_kb), (double) (size / 1024));
} else if (size < Math.pow(1024, 3)) {
human_can_read = String.format(context.getString(R.string.size_in_mb), size / Math.pow(1024, 2));
} else {
human_can_read = String.format(context.getString(R.string.size_in_gb), size / Math.pow(1024, 3));
}

//this method convert any random video duration like 1331533132 into 1:21:12
String duration_formatted;
int sec = (duration / 1000) % 60;
int min = (duration / (1000 * 60)) % 60;
int hrs = duration / (1000 * 60 * 60);

if (hrs == 0) {
duration_formatted = String.valueOf(min)
.concat(":".concat(String.format(Locale.UK, "%02d", sec)));
} else {
duration_formatted = String.valueOf(hrs)
.concat(":".concat(String.format(Locale.UK, "%02d", min)
.concat(":".concat(String.format(Locale.UK, "%02d", sec)))));
}


VideoModel files = new VideoModel(id, path, title,
human_can_read, resolution, duration_formatted,
disName, width_height);
if (name.endsWith(bucket_display_name))
list.add(files);

}
cursor.close();
}

return list;
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {

SharedPreferences.Editor editor = getSharedPreferences(MY_SORT_PREF, MODE_PRIVATE).edit();
switch (item.getItemId()) {

case R.id.sort_by_date:
editor.putString("sorting", "sortByDate");
editor.apply();
this.recreate();
break;

case R.id.sort_by_name:
editor.putString("sorting", "sortByName");
editor.apply();
this.recreate();
break;

case R.id.sort_by_size:
editor.putString("sorting", "sortBySize");
editor.apply();
this.recreate();
break;
}

return super.onOptionsItemSelected(item);
}


}

Watch Full Video Tutorials




Post a Comment

0 Comments