avatar

Android Java sort files by type

Android Java sort files by type

bounty icon
$50
Single winner
Asked  9 months ago
Viewed  0 times

Complete example of Android Java sort files by type.

  • add comment
avatar

1. It is not difficult to just implement the sorting function of files. First look at the effect achieved.

Image for question

2. Code overview

Image for question

3. First realize the file information storage class, generally including file size, time, file path, etc.

package com.example.apple.myscdn;

/**
* Created by apple on 17/5/10.
*/

public class FileInfo {
private int fileImage;
private String fileSize;//File size
private long fileS;
private String fileTime;//File time
private String fileName;//File name
private String filePath;//File path
private String lastPath;//The name of the upper directory
private int FileNum;//Number of sub files
private boolean canRead;
private boolean canWrite;
private boolean selected;
private boolean isHidden;
private long ModifiedData;
private boolean isDir;
private boolean isFile;

public FileInfo() {
}

public FileInfo(int fileImage, String fileSize, long fileS, String fileTime, String fileName, String filePath, String lastPath, int fileNum, boolean canRead, boolean canWrite, boolean selected, boolean isHidden, long modifiedData, boolean isDir, boolean isFile) {
this.fileImage = fileImage;
this.fileSize = fileSize;
this.fileS = fileS;
this.fileTime = fileTime;
this.fileName = fileName;
this.filePath = filePath;
this.lastPath = lastPath;
FileNum = fileNum;
this.canRead = canRead;
this.canWrite = canWrite;
this.selected = selected;
this.isHidden = isHidden;
ModifiedData = modifiedData;
this.isDir = isDir;
this.isFile = isFile;
}

public int getFileImage() {
return fileImage;
}

public void setFileImage(int fileImage) {
this.fileImage = fileImage;
}

public String getFileSize() {
return fileSize;
}

public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}

public long getFileS() {
return fileS;
}

public void setFileS(long fileS) {
this.fileS = fileS;
}

public String getFileTime() {
return fileTime;
}

public void setFileTime(String fileTime) {
this.fileTime = fileTime;
}

public String getFileName() {
return fileName;
}

public void setFileName(String fileName) {
this.fileName = fileName;
}

public String getFilePath() {
return filePath;
}

public void setFilePath(String filePath) {
this.filePath = filePath;
}

public String getLastPath() {
return lastPath;
}

public void setLastPath(String lastPath) {
this.lastPath = lastPath;
}

public int getFileNum() {
return FileNum;
}

public void setFileNum(int fileNum) {
FileNum = fileNum;
}

public boolean isCanRead() {
return canRead;
}

public void setCanRead(boolean canRead) {
this.canRead = canRead;
}

public boolean isCanWrite() {
return canWrite;
}

public void setCanWrite(boolean canWrite) {
this.canWrite = canWrite;
}

public boolean isSelected() {
return selected;
}

public void setSelected(boolean selected) {
this.selected = selected;
}

public boolean isHidden() {
return isHidden;
}

public void setHidden(boolean hidden) {
isHidden = hidden;
}

public long getModifiedData() {
return ModifiedData;
}

public void setModifiedData(long modifiedData) {
ModifiedData = modifiedData;
}

public boolean isDir() {
return isDir;
}

public void setDir(boolean dir) {
isDir = dir;
}

public boolean isFile() {
return isFile;
}

public void setFile(boolean file) {
isFile = file;
}

@Override
public String toString() {
return "FileInfo{" +
"fileImage=" + fileImage +
", fileSize='" + fileSize +'\'' +
", fileS=" + fileS +
", fileTime='" + fileTime +'\'' +
", fileName='" + fileName +'\'' +
", filePath='" + filePath +'\'' +
", lastPath='" + lastPath +'\'' +
", FileNum=" + FileNum +
", canRead=" + canRead +
", canWrite=" + canWrite +
", selected=" + selected +
", isHidden=" + isHidden +
", ModifiedData=" + ModifiedData +
", isDir=" + isDir +
", isFile=" + isFile +
'}';
}
}

4. Sorting file implementation, generally file size, name, type, and time sorting

package com.example.apple.myscdn;

/**
* Created by apple on 17/5/10.
*/


import com.example.apple.myscdn.utils.Utils;

import java.util.Comparator;
import java.util.HashMap;

public class FileSortHelper {


public enum SortMethod {
name, size, date, type
}

private SortMethod mSort;

private boolean mFileFirst;

private HashMap<SortMethod, Comparator> mComparatorList = new HashMap<>();

public FileSortHelper() {
mSort = SortMethod.name;
mComparatorList.put(SortMethod.name, cmpName);
mComparatorList.put(SortMethod.size, cmpSize);
mComparatorList.put(SortMethod.date, cmpDate);
mComparatorList.put(SortMethod.type, cmpType);
}

public void setSortMethog(SortMethod s) {
mSort = s;
}

public SortMethod getSortMethod() {
return mSort;
}

public void setFileFirst(boolean f) {
mFileFirst = f;
}

public Comparator getComparator() {
return mComparatorList.get(mSort);
}

private abstract class FileComparator implements Comparator<FileInfo> {

@Override
public int compare(FileInfo object1, FileInfo object2) {
if (object1.isDir() == object2.isDir()) {
return doCompare(object1, object2);
}

if (mFileFirst) {
// the files are listed before the dirs
return (object1.isDir() ? 1 : -1);
} else {
// the dir-s are listed before the files
return object1.isDir() ? -1 : 1;
}
}

protected abstract int doCompare(FileInfo object1, FileInfo object2);
}

public Comparator cmpName = new FileComparator() {
@Override
public int doCompare(FileInfo object1, FileInfo object2) {
return object1.getFileName().compareToIgnoreCase(object2.getFileName());
}
};

public Comparator cmpSize = new FileComparator() {
@Override
public int doCompare(FileInfo object1, FileInfo object2) {
return longToCompareInt(object1.getFileS() - object2.getFileS());
}
};

public Comparator cmpDate = new FileComparator() {
@Override
public int doCompare(FileInfo object1, FileInfo object2) {
return longToCompareInt(object2.getModifiedData() - object1.getModifiedData());
}
};

private int longToCompareInt(long result) {
return result > 0 ? 1 : (result < 0 ? -1 : 0);
}
public Comparator cmpType = new FileComparator() {
@Override
public int doCompare(FileInfo object1, FileInfo object2) {
int result = Utils.getExtFromFilename(object1.getFileName()).compareToIgnoreCase(
Utils.getExtFromFilename(object2.getFileName()));
if (result != 0)
return result;
return Utils.getNameFromFilename(object1.getFileName()).compareToIgnoreCase(
Utils.getNameFromFilename(object2.getFileName()));
}
};
}

5. Realize the acquisition of data, generally through the file path or through the ContentResolver, and write according to actual needs.

public ArrayList<FileInfo> queryFile(String path, final FileSortHelper sortMethod) {

fileInfo.clear();
if (path != null) {
File file = new File(path);
File[] files = file.listFiles();
if (files != null) {
// Arrays.sort(files);
if (!file.exists())
return null;
for (File f: files) {
// String absolutePath = f.getAbsolutePath();
saveData(f);
}
Collections.sort(fileInfo, sortMethod.getComparator());
}
}

return fileInfo;
}


/**
* Save the query data to FileInfo
*
* @param f
*/
private void saveData(File f) {
FileInfo fi = new FileInfo();
//if (!f.getName().substring(0, 1).equals(".")) {//Remove the first file
try {
fi.setFileName(f.getName());
fi.setFilePath(f.getPath());
fi.setFileSize(Utils.FormatFileSize(f.length()));
fi.setFileTime(Utils.LongTimeToStr(f.lastModified()));
fi.setFileNum(Utils.getFileNum(f.getPath()));
fi.setDir(f.isDirectory());
fi.setHidden(f.isHidden());
fi.setModifiedData(f.lastModified());
fi.setCanRead(f.canRead());
fi.setCanWrite(f.canWrite());
fi.setFileS(f.length());
} catch (Exception e) {
e.printStackTrace();
}
//}
fileInfo.add(fi);
}

ContentResolver access

/**
* Find files according to file type and sorting method
*
* @param fileCategory
* @param sortMethod
* @return
*/
public ArrayList<FileInfo> query(FileCategory fileCategory, SortMethod sortMethod) {
Uri uri = getContentUriByCategory(fileCategory);
String selection = buildSelectionByCategory(fileCategory);
String sortOrder = buildSortOrder(sortMethod);
if (uri == null) {
return null;
}

String[] projection = new String[]{
MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.SIZE, MediaStore.Files.FileColumns.DATE_MODIFIED
};
ContentResolver resolver = context.getContentResolver();
/**
* Parameters:
Uri, specify to query a certain table under a certain application.
projection, specify the column name of the query.
selection, specify where constraints. Row
selectionArgs provides specific values ​​for the placeholders in where.
orderBy, specify the sorting method of query results.
*/
Cursor cursor = resolver.query(uri, projection, selection, null, sortOrder);
if (cursor != null) {
while (cursor.moveToNext()) {
File f = new File(cursor.getString(1));
saveData(f);
}
}
return fileInfo;
}

Complete code

package com.example.apple.myscdn;


import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import com.example.apple.myscdn.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;

/**
* Created by 550211 on 2017/4/24.
*/

public class FileCategoryHelper {
private final String TAG = "FileCategoryHelper";

//Store file data
private ArrayList<FileInfo> fileInfo = new ArrayList<>();

private Context context;
public static String sZipFileMimeType = "application/zip";

public FileCategoryHelper(Context context) {
this.context = context;
}

/**
* file type
*/
public enum FileCategory {
Picture, Video, Music, Doc, Zip, Apk, Bluetooth, Download, Collection, All, Lately, Other, Theme
}

/**
* sorting method
*/
public enum SortMethod {
name, size, date, type
}

/**
* Find files according to file type and sorting method
*
* @param fileCategory
* @param sortMethod
* @return
*/
public ArrayList<FileInfo> query(FileCategory fileCategory, SortMethod sortMethod) {
Uri uri = getContentUriByCategory(fileCategory);
String selection = buildSelectionByCategory(fileCategory);
String sortOrder = buildSortOrder(sortMethod);
if (uri == null) {
return null;
}

String[] projection = new String[]{
MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.SIZE, MediaStore.Files.FileColumns.DATE_MODIFIED
};
ContentResolver resolver = context.getContentResolver();
/**
* Parameters:
Uri, specify to query a certain table under a certain application.
projection, specify the column name of the query.
selection, specify where constraints. Row
selectionArgs provides specific values for the placeholders in where.
orderBy, specify the sorting method of query results.
*/
Cursor cursor = resolver.query(uri, projection, selection, null, sortOrder);
if (cursor != null) {
while (cursor.moveToNext()) {
File f = new File(cursor.getString(1));
saveData(f);
}
}
return fileInfo;
}

public ArrayList<FileInfo> queryFile(String path, final FileSortHelper sortMethod) {

fileInfo.clear();
if (path != null) {
File file = new File(path);
File[] files = file.listFiles();
if (files != null) {
// Arrays.sort(files);
if (!file.exists())
return null;
for (File f : files) {
// String absolutePath = f.getAbsolutePath();
saveData(f);
}
Collections.sort(fileInfo, sortMethod.getComparator());
}
}

return fileInfo;
}


/**
* Save query data to FileInfo
*
* @param f
*/
private void saveData(File f) {
FileInfo fi = new FileInfo();
//if (!f.getName().substring(0, 1).equals(".")) {//remove the first file
try {
fi.setFileName(f.getName());
fi.setFilePath(f.getPath());
fi.setFileSize(Utils.FormatFileSize(f.length()));
fi.setFileTime(Utils.LongTimeToStr(f.lastModified()));
fi.setFileNum(Utils.getFileNum(f.getPath()));
fi.setDir(f.isDirectory());
fi.setHidden(f.isHidden());
fi.setModifiedData(f.lastModified());
fi.setCanRead(f.canRead());
fi.setCanWrite(f.canWrite());
fi.setFileS(f.length());
} catch (Exception e) {
e.printStackTrace();
}
// }
fileInfo.add(fi);
}

private Uri getContentUriByCategory(FileCategory cat) {
Uri uri;
String volumeName = "external";
switch (cat) {
case Collection:
case Doc:
case Zip:
case Apk:
uri = MediaStore.Files.getContentUri(volumeName);
break;
case Music:
uri = MediaStore.Audio.Media.getContentUri(volumeName);
break;
case Video:
uri = MediaStore.Video.Media.getContentUri(volumeName);
break;
case Picture:
uri = MediaStore.Images.Media.getContentUri(volumeName);
break;
default:
uri = null;
}
return uri;
}

private String buildSelectionByCategory(FileCategory cat) {
String selection = null;
switch (cat) {
case Theme:
selection = MediaStore.Files.FileColumns.DATA + " LIKE '%.mtz'";
break;
case Doc:
selection = buildDocSelection();
break;
case Zip:
selection = "(" + MediaStore.Files.FileColumns.MIME_TYPE + " == '" + sZipFileMimeType + "')";
break;
case Apk:
selection = MediaStore.Files.FileColumns.DATA + " LIKE '%.apk'";
break;
default:
selection = null;
}
return selection;
}

private String buildDocSelection() {
StringBuilder selection = new StringBuilder();
Iterator<String> iter = sDocMimeTypesSet.iterator();
while (iter.hasNext()) {
selection.append("(" + MediaStore.Files.FileColumns.MIME_TYPE + "=='" + iter.next() + "') OR ");
}
return selection.substring(0, selection.lastIndexOf(")") + 1);
}

public static HashSet<String> sDocMimeTypesSet = new HashSet<String>() {
{
add("text/plain");
add("application/pdf");
add("application/msword");
add("application/vnd.ms-powerpointl");
add("application/vnd.ms-excel");

// add("text/plain");
// add("text/plain");
// add("application/pdf");
// add("application/msword");
// add("application/vnd.ms-excel");
// add("application/vnd.ms-excel");
}
};

private String buildSortOrder(SortMethod sort) {
String sortOrder = null;
switch (sort) {
case name:
sortOrder = MediaStore.Files.FileColumns.TITLE + " asc";
break;
case size:
sortOrder = MediaStore.Files.FileColumns.SIZE + " asc";
break;
case date:
sortOrder = MediaStore.Files.FileColumns.DATE_MODIFIED + " desc";
break;
case type:
sortOrder = MediaStore.Files.FileColumns.MIME_TYPE + " asc, " + MediaStore.Files.FileColumns.TITLE + " asc";
break;
}
return sortOrder;
}


}

6. Use sharedPreference to store the sorting method to avoid changes after refresh

package com.example.apple.myscdn;

import android.content.Context;
import android.content.SharedPreferences;

import static android.content.Context.MODE_PRIVATE;

/**
* Created by apple on 17/5/10.
*/

public class SPInfo {
public static void saveSort(Context context,int type){
SharedPreferences sp = context.getSharedPreferences("name",MODE_PRIVATE);
SharedPreferences.Editor editor= sp.edit();
editor.putInt("name",type);
editor.commit();
}

public static int getSort(Context context){
SharedPreferences sp = context.getSharedPreferences("name",MODE_PRIVATE);
return sp.getInt("name",0);
}
}

7. Some constant codes defined

package com.example.apple.myscdn.utils;

/**
* Created by apple on 17/5/10.
*/

public class Type {
public static final int ID_SORT_NAME_ASC = 20;
public static final int ID_SORT_NAME_DEC = 21;
public static final int ID_SORT_TYPE_ASC = 22;
public static final int ID_SORT_TYPE_DEC = 23;
public static final int ID_SORT_SIZE_ASC = 24;
public static final int ID_SORT_SIZE_DEC = 25;
public static final int ID_SORT_TIME_ASC = 26;
public static final int ID_SORT_TIME_DEC = 27;

public static final int START_PROGRESS = 1000;
public static final int CLOSE_PROGRESS = 1001;

public static final int UPDATE_LIST = 1002;
public static final int SHOW_TOP_PATH = 1003;
public static final String ALL_PATH = "/mnt/sdcard";
public static final String DOWNLOAD_PATH = "/mnt/sdcard/download";

public static final int IMAGE = 0;
public static final int VIDEO = 1;
public static final int MUSIC = 2;
public static final int DOC = 3;
public static final int ZIP=4;
public static final int APK = 5;
public static final int BLUETOOTH=6;
public static final int DOWNLOAD =7;
public static final int COLLECTION=8;
public static final int ALL = 9;
public static final int LATELY = 10;
public static final int OTHER = 11;
}

8. dividing line according to your needs

package com.example.apple.myscdn.utils;

/**
* Created by apple on 17/5/10.
*/

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
* This class is from the v7 samples of the Android SDK. It's not by me!
* <p/>
* See the license above for details.
*/
public class DividerItemDecoration extends RecyclerView.ItemDecoration {

private static final int[] ATTRS = new int[]{
android.R.attr.listDivider
};

public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;

private Drawable mDivider;

private int mOrientation;

public DividerItemDecoration(Context context, int orientation) {
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
setOrientation(orientation);
}

public void setOrientation(int orientation) {
if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
throw new IllegalArgumentException("invalid orientation");
}
mOrientation = orientation;
}

@Override
public void onDraw(Canvas c, RecyclerView parent) {

if (mOrientation == VERTICAL_LIST) {
drawVertical(c, parent);
} else {
drawHorizontal(c, parent);
}

}

public void drawVertical(Canvas c, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();

final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
android.support.v7.widget.RecyclerView v = new android.support.v7.widget.RecyclerView(parent.getContext());
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin;
final int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
public void drawHorizontal(Canvas c, RecyclerView parent) {
final int top = parent.getPaddingTop();
final int bottom = parent.getHeight() - parent.getPaddingBottom();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int left = child.getRight() + params.rightMargin;
final int right = left + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
@Override
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
} else {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
}
}
}

9. Adpater code to display data

package com.example.apple.myscdn;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;

/**
* Created by 550211 on 2017/4/25.
*/

public class MyFileCategoryAdapter extends RecyclerView.Adapter<MyFileCategoryAdapter.MyViewHolder> implements View.OnClickListener{
private final String TAG = "MyFileCategoryAdapter";
private Context context;
private ArrayList<FileInfo> fileInfo;
private OnItemClickListener mOnItemClickListener = null;

@Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(v,(int)v.getTag(),fileInfo.get((int)v.getTag()).getFilePath());
}
}

public interface OnItemClickListener {
void onItemClick(View view, int position, String filePath);
}

public void setOnItemClickListener(OnItemClickListener listener) {
this.mOnItemClickListener = listener;
}

public MyFileCategoryAdapter(Context context, ArrayList<FileInfo> fileInfo) {
this.context = context;
this.fileInfo = fileInfo;
}

/**
* update list data
* @param fileInfo
*/
public void setData(ArrayList<FileInfo> fileInfo){
this.fileInfo = fileInfo;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = View.inflate(viewGroup.getContext(), R.layout.item_file_category, null);
MyViewHolder holder = new MyViewHolder(view);
view.setOnClickListener(this);
return holder;
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.itemView.setTag(position);
holder.ivHead.setImageResource(R.drawable.ic_launcher);
holder.tvFileSize.setText(fileInfo.get(position).getFileSize());
holder.tvFileTime.setText(fileInfo.get(position).getFileTime());
holder.tvFileName.setText(fileInfo.get(position).getFileName());

}

@Override
public int getItemCount() {
if (fileInfo!=null &&fileInfo.size()>0) {
return fileInfo.size();
}
return 0;
}

class MyViewHolder extends RecyclerView.ViewHolder {
ImageView ivHead;
TextView tvFileName;
TextView tvFileTime;
TextView tvFileSize;


public MyViewHolder(View itemView) {
super(itemView);
ivHead = (ImageView) itemView.findViewById(R.id.iv_head);
tvFileName = (TextView) itemView.findViewById(R.id.tv_fileName);
tvFileTime = (TextView) itemView.findViewById(R.id.tv_fileTime);
tvFileSize = (TextView) itemView.findViewById(R.id.tv_fileSize);

}
}
}

Layout code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:padding="10dp">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">

<LinearLayout
android:layout_width="50dp"
android:layout_height="50dp"
android:gravity="center"
android:orientation="vertical">

<ImageView
android:id="@+id/iv_head"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY" />
</LinearLayout>


<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:gravity="center_vertical"
android:orientation="vertical">

<TextView
android:id="@+id/tv_fileName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sunny monday"
/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp">

<TextView
android:id="@+id/tv_fileTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2016/02/11"
/>

<TextView
android:id="@+id/tv_fileSize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="12.8mb"
/>
</LinearLayout>

</LinearLayout>
</LinearLayout>

</RelativeLayout>

10. Finally realize the overall code

The first is the code to display the top path, mainly a textview plus a HorizontalScrollView implementation

private void showTextPath(String path) {
String[] spPath = path.split(Type.ALL_PATH);
StringBuilder sbBuilder = new StringBuilder();
StringTokenizer tokenizer = new StringTokenizer(spPath[1], "/");
while (tokenizer.hasMoreTokens()) {
sbBuilder.append(tokenizer.nextToken() + "> ");
}

String likeUsers = sbBuilder.substring(0, sbBuilder.lastIndexOf(">")).toString();
tvShowPath.setMovementMethod(LinkMovementMethod.getInstance());
tvShowPath.setText(addClickablePart(likeUsers), TextView.BufferType.SPANNABLE);
}

/**
* File header path display
* @param str
* @return
*/
public SpannableStringBuilder addClickablePart(String str){
SpannableString spanStr = new SpannableString("");
SpannableStringBuilder ssb = new SpannableStringBuilder(spanStr);
ssb.append(str);

String[] likeUsers = str.split(">");

if (likeUsers.length> 0) {
for (int i = 0; i <likeUsers.length; i++) {
final String name = likeUsers[i];
final int start = str.indexOf(name) + spanStr.length();
ssb.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
if (mCurrentPath != null) {
String[] spPath = mCurrentPath.split(removeAllSpace(name));
Log.e(TAG, "onClickPath=" + mCurrentPath + "aa=" + spPath[0]);
String newPath = spPath[0] + removeAllSpace(name);
mCurrentPath = newPath;//update current path
showTextPath(newPath);
//refreshFileList(spPath[0] + msg);
new RefreshFileThread(spPath[0] + removeAllSpace(name)).start();
}
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
// ds.setColor(context.getResources().getColor(R.color.black)); // set text color
ds.setUnderlineText(false);
}
}, start, start + name.length(), 0);
}
}
return ssb.append("");
}
/**
* Remove spaces
* @param str
* @return
*/
public String removeAllSpace(String str) {
String tmpstr=str.replace(" ","");
return tmpstr;
}

 /**
* openFile
*
* @param file
*/
public void openFile(File file) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
String type = Utils.getMIMEType(file);
intent.setDataAndType(Uri.fromFile(file), type);
startActivity(intent);
}

The following implements the sorting dialog box and data refresh method

public void onSortChanged(FileSortHelper.SortMethod s, String path) {
if (fileSortHelper.getSortMethod() != s) {
fileSortHelper.setSortMethog(s);
//refreshFileList(path);
new RefreshFileThread(path).start();
}
}

/**
* show sort list
*/
public void showDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View layout = inflater.inflate(R.layout.dialog_sort, null);//Get custom layout
builder.setView(layout);
// builder.setTitle(R.string.sort);//Set title content
final AlertDialog dlg = builder.create();
dlg.show();
RadioGroup rgSort = (RadioGroup) layout.findViewById(R.id.rg_sort);
Log.e(TAG, "getSort=" + sortType);
if (SPInfo.getSort(MainActivity.this) == 0) {
rgSort.check(R.id.rb_name);
} else {
sortType = SPInfo.getSort(MainActivity.this);
switch (sortType) {
case Type.ID_SORT_NAME_ASC:
rgSort.check(R.id.rb_name);
break;
case Type.ID_SORT_TYPE_ASC:
rgSort.check(R.id.rb_type);
break;
case Type.ID_SORT_SIZE_ASC:
rgSort.check(R.id.rb_size);
break;
case Type.ID_SORT_TIME_ASC:
rgSort.check(R.id.rb_time);
break;
}
}
rgSort.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb_name:
sortType = Type.ID_SORT_NAME_ASC;//name
onSortChanged(FileSortHelper.SortMethod.name,mCurrentPath);
break;
case R.id.rb_size:
sortType = Type.ID_SORT_SIZE_ASC;//type
onSortChanged(FileSortHelper.SortMethod.size,mCurrentPath);
break;
case R.id.rb_time:
sortType = Type.ID_SORT_TIME_ASC;//time
onSortChanged(FileSortHelper.SortMethod.name,mCurrentPath);
break;
case R.id.rb_type:
sortType = Type.ID_SORT_TYPE_ASC;//type
onSortChanged(FileSortHelper.SortMethod.type,mCurrentPath);
break;
default:
break;
}
SPInfo.saveSort(MainActivity.this, sortType);//Save the sorting method
Log.e(TAG, "sortType=" + sortType);
dlg.dismiss();
}
});
}
//refresh file
private void refreshFileList() {
//if (path != null) {
//info = fileCategoryHelper.queryFile(path, fileSortHelper);
adapter.setData(info);
rvCategory.setAdapter(adapter);
adapter.notifyDataSetChanged();
//}
sendMsg(Type.CLOSE_PROGRESS);
}
/**
* refresh file list thread
*/
class RefreshFileThread extends Thread {
private String path;

public RefreshFileThread(String path) {
this.path = path;
}

@Override
public void run() {

if (path != null) {
sendMsg(Type.START_PROGRESS);
info = fileCategoryHelper.queryFile(path, fileSortHelper);
sendMsg(Type.UPDATE_LIST);
}
}
}

private void sendMsg(int type) {
Message msg = new Message();
msg.what = type;
handler.sendMessage(msg);
}

The complete code is as follows

package com.example.apple.myscdn;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.apple.myscdn.utils.DividerItemDecoration;
import com.example.apple.myscdn.utils.Type;
import com.example.apple.myscdn.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private final String TAG = "MainActivity";

private RecyclerView rvCategory;
private ImageView iv_back;
private TextView tv_title;
private ImageView iv_search;
private ImageView iv_more;
private TextView tvNoFile;
private RelativeLayout rl_title_bar;
private LinearLayout llShowPath;
private TextView tvShowPath;
private HorizontalScrollView scrollView;
private TextView tvSdcard;
private ProgressBar pbUpdate;
private FileCategoryHelper fileCategoryHelper;
private int sortType = Type.ID_SORT_NAME_ASC;//Initial sorting method
private String mCurrentPath = "/mnt/sdcard";//current path

private FileSortHelper fileSortHelper;
private ArrayList<FileInfo> info;
private MyFileCategoryAdapter adapter;

private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {

case Type.START_PROGRESS:
pbUpdate.setVisibility(View.VISIBLE);
break;

case Type.CLOSE_PROGRESS:
pbUpdate.setVisibility(View.GONE);
break;

case Type.UPDATE_LIST://update list
refreshFileList();
break;

case Type.SHOW_TOP_PATH:
llShowPath.setVisibility(View.VISIBLE);
break;
}

super.handleMessage(msg);
}
};

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


initView();
fileSortHelper = new FileSortHelper();
initShow();
}
private void initView() {
iv_back = (ImageView) findViewById(R.id.iv_back);
iv_back.setOnClickListener(this);
tv_title = (TextView) findViewById(R.id.tv_title);
tv_title.setOnClickListener(this);
iv_search = (ImageView) findViewById(R.id.iv_search);
iv_more = (ImageView) findViewById(R.id.iv_more);
iv_more.setOnClickListener(this);
rl_title_bar = (RelativeLayout) findViewById(R.id.rl_title_bar);

tvSdcard = (TextView) findViewById(R.id.tv_sdcard);
tvSdcard.setOnClickListener(this);
llShowPath = (LinearLayout) findViewById(R.id.ll_show_path);
tvShowPath = (TextView) findViewById(R.id.tv_show_path);
tvNoFile = (TextView) findViewById(R.id.tv_no_file);
rvCategory = (RecyclerView) findViewById(R.id.rv_category);
pbUpdate = (ProgressBar) findViewById(R.id.pb_update);

scrollView = (HorizontalScrollView) findViewById(R.id.scrollView);


}

private void initShow() {
tv_title.setText("File Sorting");
fileCategoryHelper = new FileCategoryHelper(this);
info = fileCategoryHelper.queryFile(mCurrentPath, fileSortHelper);

adapter = new MyFileCategoryAdapter(MainActivity.this, info);
rvCategory.setHasFixedSize(true);
// Create a linear layout manager
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// Set the layout manager
rvCategory.setLayoutManager(layoutManager);
layoutManager.setOrientation(OrientationHelper.VERTICAL);
rvCategory.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
rvCategory.setAdapter(adapter);

adapter.setOnItemClickListener(new setOnItemClickListener());

}

private void showTextPath(String path) {
String[] spPath = path.split(Type.ALL_PATH);
StringBuilder sbBuilder = new StringBuilder();
StringTokenizer tokenizer = new StringTokenizer(spPath[1], "/");
while (tokenizer.hasMoreTokens()) {
sbBuilder.append(tokenizer.nextToken() + "> ");
}

String likeUsers = sbBuilder.substring(0, sbBuilder.lastIndexOf(">")).toString();
tvShowPath.setMovementMethod(LinkMovementMethod.getInstance());
tvShowPath.setText(addClickablePart(likeUsers), TextView.BufferType.SPANNABLE);
}

/**
* File header path display
* @param str
* @return
*/
public SpannableStringBuilder addClickablePart(String str){
SpannableString spanStr = new SpannableString("");
SpannableStringBuilder ssb = new SpannableStringBuilder(spanStr);
ssb.append(str);

String[] likeUsers = str.split(">");

if (likeUsers.length> 0) {
for (int i = 0; i <likeUsers.length; i++) {
final String name = likeUsers[i];
final int start = str.indexOf(name) + spanStr.length();
ssb.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
if (mCurrentPath != null) {
String[] spPath = mCurrentPath.split(removeAllSpace(name));
Log.e(TAG, "onClickPath=" + mCurrentPath + "aa=" + spPath[0]);
String newPath = spPath[0] + removeAllSpace(name);
mCurrentPath = newPath;//update current path
showTextPath(newPath);
//refreshFileList(spPath[0] + msg);
new RefreshFileThread(spPath[0] + removeAllSpace(name)).start();
}
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
// ds.setColor(context.getResources().getColor(R.color.black)); // set text color
ds.setUnderlineText(false);
}
}, start, start + name.length(), 0);
}
}
return ssb.append("");
}
/**
* Remove spaces
* @param str
* @return
*/
public String removeAllSpace(String str) {
String tmpstr=str.replace(" ","");
return tmpstr;
}
//short onclick
class setOnItemClickListener implements MyFileCategoryAdapter.OnItemClickListener {
@Override
public void onItemClick(View view, int position, String filePath) {
mCurrentPath = filePath;
File file = new File(filePath);
if (file.exists() && file.canRead() && file.isDirectory()) {
new RefreshFileThread(filePath).start();
} else {
openFile(file);
}
if (!mCurrentPath.equals(Type.ALL_PATH) && file.isDirectory()) {
showTextPath(filePath);
}
scrollView.post(new Runnable() {
public void run() {
scrollView.fullScroll(View.FOCUS_RIGHT);
}
});
}
}
/**
* open a file
*
* @param file
*/
public void openFile(File file) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
String type = Utils.getMIMEType(file);
intent.setDataAndType(Uri.fromFile(file), type);
startActivity(intent);
}

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.iv_back:
finish();
break;
case R.id.iv_more:
showDialog();
break;
case R.id.tv_sdcard:
//refreshFileList(Type.ALL_PATH);
new RefreshFileThread(Type.ALL_PATH).start();
tvShowPath.setText("");
mCurrentPath = Type.ALL_PATH;//update current path
break;
}
}
public void onSortChanged(FileSortHelper.SortMethod s, String path) {
if (fileSortHelper.getSortMethod() != s) {
fileSortHelper.setSortMethog(s);
//refreshFileList(path);
new RefreshFileThread(path).start();
}
}
/**
* show sort list
*/
public void showDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View layout = inflater.inflate(R.layout.dialog_sort, null);//Get custom layout
builder.setView(layout);
// builder.setTitle(R.string.sort);//Set title content
final AlertDialog dlg = builder.create();
dlg.show();
RadioGroup rgSort = (RadioGroup) layout.findViewById(R.id.rg_sort);
Log.e(TAG, "getSort=" + sortType);
if (SPInfo.getSort(MainActivity.this) == 0) {
rgSort.check(R.id.rb_name);
} else {
sortType = SPInfo.getSort(MainActivity.this);
switch (sortType) {
case Type.ID_SORT_NAME_ASC:
rgSort.check(R.id.rb_name);
break;
case Type.ID_SORT_TYPE_ASC:
rgSort.check(R.id.rb_type);
break;
case Type.ID_SORT_SIZE_ASC:
rgSort.check(R.id.rb_size);
break;
case Type.ID_SORT_TIME_ASC:
rgSort.check(R.id.rb_time);
break;
}
}
rgSort.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb_name:
sortType = Type.ID_SORT_NAME_ASC;//name
onSortChanged(FileSortHelper.SortMethod.name,mCurrentPath);
break;
case R.id.rb_size:
sortType = Type.ID_SORT_SIZE_ASC;//type
onSortChanged(FileSortHelper.SortMethod.size,mCurrentPath);
break;
case R.id.rb_time:
sortType = Type.ID_SORT_TIME_ASC;//time
onSortChanged(FileSortHelper.SortMethod.name,mCurrentPath);
break;
case R.id.rb_type:
sortType = Type.ID_SORT_TYPE_ASC;//type
onSortChanged(FileSortHelper.SortMethod.type,mCurrentPath);
break;
default:
break;
}
SPInfo.saveSort(MainActivity.this, sortType);//Save the sorting method
Log.e(TAG, "sortType=" + sortType);
dlg.dismiss();
}
});
}
//refresh file
private void refreshFileList() {
//if (path != null) {
//info = fileCategoryHelper.queryFile(path, fileSortHelper);
adapter.setData(info);
rvCategory.setAdapter(adapter);
adapter.notifyDataSetChanged();
//}
sendMsg(Type.CLOSE_PROGRESS);
}
/**
* refresh file list thread
*/
class RefreshFileThread extends Thread {
private String path;
public RefreshFileThread(String path) {
this.path = path;
}
@Override
public void run() {
if (path != null) {
sendMsg(Type.START_PROGRESS);
info = fileCategoryHelper.queryFile(path, fileSortHelper);
sendMsg(Type.UPDATE_LIST);
}
}
}

private void sendMsg(int type) {
Message msg = new Message();
msg.what = type;
handler.sendMessage(msg);
}
}

Layout code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.a550211.mycsdn.MainActivity">

<include layout="@layout/title_bar" />
<LinearLayout
android:id="@+id/ll_show_path"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp">

<TextView
android:id="@+id/tv_sdcard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Internal storage device> "/>


<HorizontalScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none">

<TextView
android:id="@+id/tv_show_path"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</HorizontalScrollView>

</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.RecyclerView
android:id="@+id/rv_category"
android:layout_width="match_parent"
android:layout_height="wrap_content"></android.support.v7.widget.RecyclerView>

<TextView
android:id="@+id/tv_no_file"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="No files"
android:visibility="gone" />

<ProgressBar
android:id="@+id/pb_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" />
</RelativeLayout>
</LinearLayout>

Sorting dialog layout code implementation

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:padding="10dp"
android:textSize="23dp"
android:gravity="center"
android:layout_width="match_parent"
android:text="sort"
android:layout_height="wrap_content" />

<RadioGroup
android:id="@+id/rg_sort"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<RadioButton
android:id="@+id/rb_name"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:button="@null"
android:drawableRight="@android:drawable/btn_radio"
android:paddingLeft="30dip"
android:text="name"
android:textSize="20dip" />

<RadioButton
android:id="@+id/rb_time"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:button="@null"
android:drawableRight="@android:drawable/btn_radio"
android:paddingLeft="30dip"
android:text="time"
android:textSize="20dip" />

<RadioButton
android:id="@+id/rb_type"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:button="@null"
android:drawableRight="@android:drawable/btn_radio"
android:paddingLeft="30dip"
android:text="type"
android:textSize="20dip" />

<RadioButton
android:id="@+id/rb_size"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:button="@null"
android:drawableRight="@android:drawable/btn_radio"
android:paddingLeft="30dip"
android:text="size"
android:textSize="20dip" />

</RadioGroup>

</LinearLayout>

title_bar.xml code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="51dp"
android:gravity="center_vertical"
android:id="@+id/rl_title_bar"
android:padding="5dp">

<LinearLayout
android:id="@+id/ll_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:gravity="center_vertical"
android:orientation="horizontal">

<ImageView
android:id="@+id/iv_back"
android:layout_width="12dp"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />

<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:text="file management"
android:textSize="18sp" />

</LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="12dp"
android:orientation="horizontal">

<ImageView
android:id="@+id/iv_search"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />

<ImageView
android:id="@+id/iv_more"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:src="@drawable/ic_launcher" />
</LinearLayout>
</RelativeLayout>

utils code

package com.example.apple.myscdn.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* Created by apple on 17/5/10.
*/

public class Utils {
/**
* Convert file size
*
* @param fileS
* @return
*/
public static String FormatFileSize(long fileS) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
String wrongSize = "0B";
if (fileS == 0) {
return wrongSize;
}
if (fileS <1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS <1048576) {
fileSizeString = df.format((double) fileS / 1024) + "KB";
} else if (fileS <1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "MB";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "GB";
}
return fileSizeString;
}
/**
* Convert milliseconds to a specific time format
*
* @param time
* @return
*/
public static String LongTimeToStr(long time) {
int m = 1000;
int f = m * 60;
int h = f * 60;
Date date = new Date(time);
if (time <h * f * m) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
return sdf.format(date);
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
return sdf.format(date);
}
}
/**
* Get the number of files
*
* @param path
* @return
*/
public static int getFileNum(String path) {
File file = new File(path);
int fileNum = 0;
File[] fileArray = file.listFiles();
if (fileArray!=null) {
for (File f: fileArray) {
if (f.isFile() || f.isDirectory() && !f.isHidden()) {
fileNum++;
}
}
}
return fileNum;
}
/**
* Get file size
*
* @param file
* @return
* @throws Exception
*/
public static long getFileSize(File file) throws Exception {
long size = 0;
if (file.exists() && !file.isDirectory()) {
FileInputStream fis = null;
fis = new FileInputStream(file);
size = fis.available();
} else {
file.createNewFile();
Log.e("Get file size", "File does not exist!");
}
return size;
}
/*
* A new method is adopted to obtain the APK icon. The previous failure was due to a bug in android.
* appInfo.publicSourceDir = apkPath; to fix this problem, see for details:
* http://code.google.com/p/android/issues/detail?id=9151
*/
public static Drawable getApkIcon(Context context, String apkPath) {
PackageManager pm = context.getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(apkPath,
PackageManager.GET_ACTIVITIES);
if (info != null) {
ApplicationInfo appInfo = info.applicationInfo;
appInfo.sourceDir = apkPath;
appInfo.publicSourceDir = apkPath;
try {
return appInfo.loadIcon(pm);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
}
return null;
}
public static String getMIMEType(File f) {
String type = "";
String fileName = f.getName();
String ext = fileName.substring(fileName.lastIndexOf(".")
+ 1, fileName.length()).toLowerCase();
if (ext.equals("jpg") || ext.equals("jpeg") || ext.equals("gif")
|| ext.equals("png") || ext.equals("bmp") || ext.equals("wbmp")) {
type = "image/*";
} else if (ext.equals("mp3") || ext.equals("amr") || ext.equals("wma")
|| ext.equals("aac") || ext.equals("m4a") || ext.equals("mid")
|| ext.equals("xmf") || ext.equals("ogg") || ext.equals("wav")
|| ext.equals("qcp") || ext.equals("awb") || ext.equals("flac") || ext.equals("3gpp")) {
type = "audio/*";
} else if (ext.equals("3gp") || ext.equals("avi") || ext.equals("mp4")
|| ext.equals("3g2") || ext.equals("wmv") || ext.equals("divx")
|| ext.equals("mkv") || ext.equals("webm") || ext.equals("ts")
|| ext.equals("asf") || ext.equals("flv") || ext.equals("mov") || ext.equals("mpg")) {
type = "video/*";
} else if (ext.equals("apk")) {
type = "application/vnd.android.package-archive";
} else if (ext.equals("vcf")) {
type = "text/x-vcard";
} else if (ext.equals("txt")) {
type = "text/plain";
} else if (ext.equals("doc") || ext.equals("docx")) {
type = "application/msword";
}else if (ext.equals("xls") || ext.equals("xlsx")) {
type = "application/vnd.ms-excel";
} else if (ext.equals("ppt") || ext.equals("pptx")) {
type = "application/vnd.ms-powerpoint";
} else if (ext.equals("pdf")) {
type = "application/pdf";
} else if (ext.equals("xml")) {
type = "text/xml";
} else if (ext.equals("html")) {
type = "text/html";
} else if (ext.equals("zip")) {
type = "application/zip";
} else {
type = "application/octet-stream";
}
return type;
}
public static String getExtFromFilename(String filename) {
int dotPosition = filename.lastIndexOf('.');
if (dotPosition != -1) {
return filename.substring(dotPosition + 1, filename.length());
}
return "";
}
public static String getNameFromFilename(String filename) {
int dotPosition = filename.lastIndexOf('.');
if (dotPosition != -1) {
return filename.substring(0, dotPosition);
}
return "";
}
}

use permissions

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>

Remember to add the recycleview.jar package

compile files('libs/android-support-v7-recyclerview.jar')

  • Taken
  • add comment
  • 0
Sign In
Sign In
avatar

Android Java sort files by type

Android Java sort files by type

bounty icon
$50
Single winner
Asked  9 months ago
Viewed  0 times

Complete example of Android Java sort files by type.

  • add comment
avatar

1. It is not difficult to just implement the sorting function of files. First look at the effect achieved.

Image for question

2. Code overview

Image for question

3. First realize the file information storage class, generally including file size, time, file path, etc.

package com.example.apple.myscdn;

/**
* Created by apple on 17/5/10.
*/

public class FileInfo {
private int fileImage;
private String fileSize;//File size
private long fileS;
private String fileTime;//File time
private String fileName;//File name
private String filePath;//File path
private String lastPath;//The name of the upper directory
private int FileNum;//Number of sub files
private boolean canRead;
private boolean canWrite;
private boolean selected;
private boolean isHidden;
private long ModifiedData;
private boolean isDir;
private boolean isFile;

public FileInfo() {
}

public FileInfo(int fileImage, String fileSize, long fileS, String fileTime, String fileName, String filePath, String lastPath, int fileNum, boolean canRead, boolean canWrite, boolean selected, boolean isHidden, long modifiedData, boolean isDir, boolean isFile) {
this.fileImage = fileImage;
this.fileSize = fileSize;
this.fileS = fileS;
this.fileTime = fileTime;
this.fileName = fileName;
this.filePath = filePath;
this.lastPath = lastPath;
FileNum = fileNum;
this.canRead = canRead;
this.canWrite = canWrite;
this.selected = selected;
this.isHidden = isHidden;
ModifiedData = modifiedData;
this.isDir = isDir;
this.isFile = isFile;
}

public int getFileImage() {
return fileImage;
}

public void setFileImage(int fileImage) {
this.fileImage = fileImage;
}

public String getFileSize() {
return fileSize;
}

public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}

public long getFileS() {
return fileS;
}

public void setFileS(long fileS) {
this.fileS = fileS;
}

public String getFileTime() {
return fileTime;
}

public void setFileTime(String fileTime) {
this.fileTime = fileTime;
}

public String getFileName() {
return fileName;
}

public void setFileName(String fileName) {
this.fileName = fileName;
}

public String getFilePath() {
return filePath;
}

public void setFilePath(String filePath) {
this.filePath = filePath;
}

public String getLastPath() {
return lastPath;
}

public void setLastPath(String lastPath) {
this.lastPath = lastPath;
}

public int getFileNum() {
return FileNum;
}

public void setFileNum(int fileNum) {
FileNum = fileNum;
}

public boolean isCanRead() {
return canRead;
}

public void setCanRead(boolean canRead) {
this.canRead = canRead;
}

public boolean isCanWrite() {
return canWrite;
}

public void setCanWrite(boolean canWrite) {
this.canWrite = canWrite;
}

public boolean isSelected() {
return selected;
}

public void setSelected(boolean selected) {
this.selected = selected;
}

public boolean isHidden() {
return isHidden;
}

public void setHidden(boolean hidden) {
isHidden = hidden;
}

public long getModifiedData() {
return ModifiedData;
}

public void setModifiedData(long modifiedData) {
ModifiedData = modifiedData;
}

public boolean isDir() {
return isDir;
}

public void setDir(boolean dir) {
isDir = dir;
}

public boolean isFile() {
return isFile;
}

public void setFile(boolean file) {
isFile = file;
}

@Override
public String toString() {
return "FileInfo{" +
"fileImage=" + fileImage +
", fileSize='" + fileSize +'\'' +
", fileS=" + fileS +
", fileTime='" + fileTime +'\'' +
", fileName='" + fileName +'\'' +
", filePath='" + filePath +'\'' +
", lastPath='" + lastPath +'\'' +
", FileNum=" + FileNum +
", canRead=" + canRead +
", canWrite=" + canWrite +
", selected=" + selected +
", isHidden=" + isHidden +
", ModifiedData=" + ModifiedData +
", isDir=" + isDir +
", isFile=" + isFile +
'}';
}
}

4. Sorting file implementation, generally file size, name, type, and time sorting

package com.example.apple.myscdn;

/**
* Created by apple on 17/5/10.
*/


import com.example.apple.myscdn.utils.Utils;

import java.util.Comparator;
import java.util.HashMap;

public class FileSortHelper {


public enum SortMethod {
name, size, date, type
}

private SortMethod mSort;

private boolean mFileFirst;

private HashMap<SortMethod, Comparator> mComparatorList = new HashMap<>();

public FileSortHelper() {
mSort = SortMethod.name;
mComparatorList.put(SortMethod.name, cmpName);
mComparatorList.put(SortMethod.size, cmpSize);
mComparatorList.put(SortMethod.date, cmpDate);
mComparatorList.put(SortMethod.type, cmpType);
}

public void setSortMethog(SortMethod s) {
mSort = s;
}

public SortMethod getSortMethod() {
return mSort;
}

public void setFileFirst(boolean f) {
mFileFirst = f;
}

public Comparator getComparator() {
return mComparatorList.get(mSort);
}

private abstract class FileComparator implements Comparator<FileInfo> {

@Override
public int compare(FileInfo object1, FileInfo object2) {
if (object1.isDir() == object2.isDir()) {
return doCompare(object1, object2);
}

if (mFileFirst) {
// the files are listed before the dirs
return (object1.isDir() ? 1 : -1);
} else {
// the dir-s are listed before the files
return object1.isDir() ? -1 : 1;
}
}

protected abstract int doCompare(FileInfo object1, FileInfo object2);
}

public Comparator cmpName = new FileComparator() {
@Override
public int doCompare(FileInfo object1, FileInfo object2) {
return object1.getFileName().compareToIgnoreCase(object2.getFileName());
}
};

public Comparator cmpSize = new FileComparator() {
@Override
public int doCompare(FileInfo object1, FileInfo object2) {
return longToCompareInt(object1.getFileS() - object2.getFileS());
}
};

public Comparator cmpDate = new FileComparator() {
@Override
public int doCompare(FileInfo object1, FileInfo object2) {
return longToCompareInt(object2.getModifiedData() - object1.getModifiedData());
}
};

private int longToCompareInt(long result) {
return result > 0 ? 1 : (result < 0 ? -1 : 0);
}
public Comparator cmpType = new FileComparator() {
@Override
public int doCompare(FileInfo object1, FileInfo object2) {
int result = Utils.getExtFromFilename(object1.getFileName()).compareToIgnoreCase(
Utils.getExtFromFilename(object2.getFileName()));
if (result != 0)
return result;
return Utils.getNameFromFilename(object1.getFileName()).compareToIgnoreCase(
Utils.getNameFromFilename(object2.getFileName()));
}
};
}

5. Realize the acquisition of data, generally through the file path or through the ContentResolver, and write according to actual needs.

public ArrayList<FileInfo> queryFile(String path, final FileSortHelper sortMethod) {

fileInfo.clear();
if (path != null) {
File file = new File(path);
File[] files = file.listFiles();
if (files != null) {
// Arrays.sort(files);
if (!file.exists())
return null;
for (File f: files) {
// String absolutePath = f.getAbsolutePath();
saveData(f);
}
Collections.sort(fileInfo, sortMethod.getComparator());
}
}

return fileInfo;
}


/**
* Save the query data to FileInfo
*
* @param f
*/
private void saveData(File f) {
FileInfo fi = new FileInfo();
//if (!f.getName().substring(0, 1).equals(".")) {//Remove the first file
try {
fi.setFileName(f.getName());
fi.setFilePath(f.getPath());
fi.setFileSize(Utils.FormatFileSize(f.length()));
fi.setFileTime(Utils.LongTimeToStr(f.lastModified()));
fi.setFileNum(Utils.getFileNum(f.getPath()));
fi.setDir(f.isDirectory());
fi.setHidden(f.isHidden());
fi.setModifiedData(f.lastModified());
fi.setCanRead(f.canRead());
fi.setCanWrite(f.canWrite());
fi.setFileS(f.length());
} catch (Exception e) {
e.printStackTrace();
}
//}
fileInfo.add(fi);
}

ContentResolver access

/**
* Find files according to file type and sorting method
*
* @param fileCategory
* @param sortMethod
* @return
*/
public ArrayList<FileInfo> query(FileCategory fileCategory, SortMethod sortMethod) {
Uri uri = getContentUriByCategory(fileCategory);
String selection = buildSelectionByCategory(fileCategory);
String sortOrder = buildSortOrder(sortMethod);
if (uri == null) {
return null;
}

String[] projection = new String[]{
MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.SIZE, MediaStore.Files.FileColumns.DATE_MODIFIED
};
ContentResolver resolver = context.getContentResolver();
/**
* Parameters:
Uri, specify to query a certain table under a certain application.
projection, specify the column name of the query.
selection, specify where constraints. Row
selectionArgs provides specific values ​​for the placeholders in where.
orderBy, specify the sorting method of query results.
*/
Cursor cursor = resolver.query(uri, projection, selection, null, sortOrder);
if (cursor != null) {
while (cursor.moveToNext()) {
File f = new File(cursor.getString(1));
saveData(f);
}
}
return fileInfo;
}

Complete code

package com.example.apple.myscdn;


import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import com.example.apple.myscdn.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;

/**
* Created by 550211 on 2017/4/24.
*/

public class FileCategoryHelper {
private final String TAG = "FileCategoryHelper";

//Store file data
private ArrayList<FileInfo> fileInfo = new ArrayList<>();

private Context context;
public static String sZipFileMimeType = "application/zip";

public FileCategoryHelper(Context context) {
this.context = context;
}

/**
* file type
*/
public enum FileCategory {
Picture, Video, Music, Doc, Zip, Apk, Bluetooth, Download, Collection, All, Lately, Other, Theme
}

/**
* sorting method
*/
public enum SortMethod {
name, size, date, type
}

/**
* Find files according to file type and sorting method
*
* @param fileCategory
* @param sortMethod
* @return
*/
public ArrayList<FileInfo> query(FileCategory fileCategory, SortMethod sortMethod) {
Uri uri = getContentUriByCategory(fileCategory);
String selection = buildSelectionByCategory(fileCategory);
String sortOrder = buildSortOrder(sortMethod);
if (uri == null) {
return null;
}

String[] projection = new String[]{
MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.SIZE, MediaStore.Files.FileColumns.DATE_MODIFIED
};
ContentResolver resolver = context.getContentResolver();
/**
* Parameters:
Uri, specify to query a certain table under a certain application.
projection, specify the column name of the query.
selection, specify where constraints. Row
selectionArgs provides specific values for the placeholders in where.
orderBy, specify the sorting method of query results.
*/
Cursor cursor = resolver.query(uri, projection, selection, null, sortOrder);
if (cursor != null) {
while (cursor.moveToNext()) {
File f = new File(cursor.getString(1));
saveData(f);
}
}
return fileInfo;
}

public ArrayList<FileInfo> queryFile(String path, final FileSortHelper sortMethod) {

fileInfo.clear();
if (path != null) {
File file = new File(path);
File[] files = file.listFiles();
if (files != null) {
// Arrays.sort(files);
if (!file.exists())
return null;
for (File f : files) {
// String absolutePath = f.getAbsolutePath();
saveData(f);
}
Collections.sort(fileInfo, sortMethod.getComparator());
}
}

return fileInfo;
}


/**
* Save query data to FileInfo
*
* @param f
*/
private void saveData(File f) {
FileInfo fi = new FileInfo();
//if (!f.getName().substring(0, 1).equals(".")) {//remove the first file
try {
fi.setFileName(f.getName());
fi.setFilePath(f.getPath());
fi.setFileSize(Utils.FormatFileSize(f.length()));
fi.setFileTime(Utils.LongTimeToStr(f.lastModified()));
fi.setFileNum(Utils.getFileNum(f.getPath()));
fi.setDir(f.isDirectory());
fi.setHidden(f.isHidden());
fi.setModifiedData(f.lastModified());
fi.setCanRead(f.canRead());
fi.setCanWrite(f.canWrite());
fi.setFileS(f.length());
} catch (Exception e) {
e.printStackTrace();
}
// }
fileInfo.add(fi);
}

private Uri getContentUriByCategory(FileCategory cat) {
Uri uri;
String volumeName = "external";
switch (cat) {
case Collection:
case Doc:
case Zip:
case Apk:
uri = MediaStore.Files.getContentUri(volumeName);
break;
case Music:
uri = MediaStore.Audio.Media.getContentUri(volumeName);
break;
case Video:
uri = MediaStore.Video.Media.getContentUri(volumeName);
break;
case Picture:
uri = MediaStore.Images.Media.getContentUri(volumeName);
break;
default:
uri = null;
}
return uri;
}

private String buildSelectionByCategory(FileCategory cat) {
String selection = null;
switch (cat) {
case Theme:
selection = MediaStore.Files.FileColumns.DATA + " LIKE '%.mtz'";
break;
case Doc:
selection = buildDocSelection();
break;
case Zip:
selection = "(" + MediaStore.Files.FileColumns.MIME_TYPE + " == '" + sZipFileMimeType + "')";
break;
case Apk:
selection = MediaStore.Files.FileColumns.DATA + " LIKE '%.apk'";
break;
default:
selection = null;
}
return selection;
}

private String buildDocSelection() {
StringBuilder selection = new StringBuilder();
Iterator<String> iter = sDocMimeTypesSet.iterator();
while (iter.hasNext()) {
selection.append("(" + MediaStore.Files.FileColumns.MIME_TYPE + "=='" + iter.next() + "') OR ");
}
return selection.substring(0, selection.lastIndexOf(")") + 1);
}

public static HashSet<String> sDocMimeTypesSet = new HashSet<String>() {
{
add("text/plain");
add("application/pdf");
add("application/msword");
add("application/vnd.ms-powerpointl");
add("application/vnd.ms-excel");

// add("text/plain");
// add("text/plain");
// add("application/pdf");
// add("application/msword");
// add("application/vnd.ms-excel");
// add("application/vnd.ms-excel");
}
};

private String buildSortOrder(SortMethod sort) {
String sortOrder = null;
switch (sort) {
case name:
sortOrder = MediaStore.Files.FileColumns.TITLE + " asc";
break;
case size:
sortOrder = MediaStore.Files.FileColumns.SIZE + " asc";
break;
case date:
sortOrder = MediaStore.Files.FileColumns.DATE_MODIFIED + " desc";
break;
case type:
sortOrder = MediaStore.Files.FileColumns.MIME_TYPE + " asc, " + MediaStore.Files.FileColumns.TITLE + " asc";
break;
}
return sortOrder;
}


}

6. Use sharedPreference to store the sorting method to avoid changes after refresh

package com.example.apple.myscdn;

import android.content.Context;
import android.content.SharedPreferences;

import static android.content.Context.MODE_PRIVATE;

/**
* Created by apple on 17/5/10.
*/

public class SPInfo {
public static void saveSort(Context context,int type){
SharedPreferences sp = context.getSharedPreferences("name",MODE_PRIVATE);
SharedPreferences.Editor editor= sp.edit();
editor.putInt("name",type);
editor.commit();
}

public static int getSort(Context context){
SharedPreferences sp = context.getSharedPreferences("name",MODE_PRIVATE);
return sp.getInt("name",0);
}
}

7. Some constant codes defined

package com.example.apple.myscdn.utils;

/**
* Created by apple on 17/5/10.
*/

public class Type {
public static final int ID_SORT_NAME_ASC = 20;
public static final int ID_SORT_NAME_DEC = 21;
public static final int ID_SORT_TYPE_ASC = 22;
public static final int ID_SORT_TYPE_DEC = 23;
public static final int ID_SORT_SIZE_ASC = 24;
public static final int ID_SORT_SIZE_DEC = 25;
public static final int ID_SORT_TIME_ASC = 26;
public static final int ID_SORT_TIME_DEC = 27;

public static final int START_PROGRESS = 1000;
public static final int CLOSE_PROGRESS = 1001;

public static final int UPDATE_LIST = 1002;
public static final int SHOW_TOP_PATH = 1003;
public static final String ALL_PATH = "/mnt/sdcard";
public static final String DOWNLOAD_PATH = "/mnt/sdcard/download";

public static final int IMAGE = 0;
public static final int VIDEO = 1;
public static final int MUSIC = 2;
public static final int DOC = 3;
public static final int ZIP=4;
public static final int APK = 5;
public static final int BLUETOOTH=6;
public static final int DOWNLOAD =7;
public static final int COLLECTION=8;
public static final int ALL = 9;
public static final int LATELY = 10;
public static final int OTHER = 11;
}

8. dividing line according to your needs

package com.example.apple.myscdn.utils;

/**
* Created by apple on 17/5/10.
*/

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
* This class is from the v7 samples of the Android SDK. It's not by me!
* <p/>
* See the license above for details.
*/
public class DividerItemDecoration extends RecyclerView.ItemDecoration {

private static final int[] ATTRS = new int[]{
android.R.attr.listDivider
};

public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;

private Drawable mDivider;

private int mOrientation;

public DividerItemDecoration(Context context, int orientation) {
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
setOrientation(orientation);
}

public void setOrientation(int orientation) {
if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
throw new IllegalArgumentException("invalid orientation");
}
mOrientation = orientation;
}

@Override
public void onDraw(Canvas c, RecyclerView parent) {

if (mOrientation == VERTICAL_LIST) {
drawVertical(c, parent);
} else {
drawHorizontal(c, parent);
}

}

public void drawVertical(Canvas c, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();

final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
android.support.v7.widget.RecyclerView v = new android.support.v7.widget.RecyclerView(parent.getContext());
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin;
final int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
public void drawHorizontal(Canvas c, RecyclerView parent) {
final int top = parent.getPaddingTop();
final int bottom = parent.getHeight() - parent.getPaddingBottom();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int left = child.getRight() + params.rightMargin;
final int right = left + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
@Override
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
} else {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
}
}
}

9. Adpater code to display data

package com.example.apple.myscdn;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;

/**
* Created by 550211 on 2017/4/25.
*/

public class MyFileCategoryAdapter extends RecyclerView.Adapter<MyFileCategoryAdapter.MyViewHolder> implements View.OnClickListener{
private final String TAG = "MyFileCategoryAdapter";
private Context context;
private ArrayList<FileInfo> fileInfo;
private OnItemClickListener mOnItemClickListener = null;

@Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(v,(int)v.getTag(),fileInfo.get((int)v.getTag()).getFilePath());
}
}

public interface OnItemClickListener {
void onItemClick(View view, int position, String filePath);
}

public void setOnItemClickListener(OnItemClickListener listener) {
this.mOnItemClickListener = listener;
}

public MyFileCategoryAdapter(Context context, ArrayList<FileInfo> fileInfo) {
this.context = context;
this.fileInfo = fileInfo;
}

/**
* update list data
* @param fileInfo
*/
public void setData(ArrayList<FileInfo> fileInfo){
this.fileInfo = fileInfo;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = View.inflate(viewGroup.getContext(), R.layout.item_file_category, null);
MyViewHolder holder = new MyViewHolder(view);
view.setOnClickListener(this);
return holder;
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.itemView.setTag(position);
holder.ivHead.setImageResource(R.drawable.ic_launcher);
holder.tvFileSize.setText(fileInfo.get(position).getFileSize());
holder.tvFileTime.setText(fileInfo.get(position).getFileTime());
holder.tvFileName.setText(fileInfo.get(position).getFileName());

}

@Override
public int getItemCount() {
if (fileInfo!=null &&fileInfo.size()>0) {
return fileInfo.size();
}
return 0;
}

class MyViewHolder extends RecyclerView.ViewHolder {
ImageView ivHead;
TextView tvFileName;
TextView tvFileTime;
TextView tvFileSize;


public MyViewHolder(View itemView) {
super(itemView);
ivHead = (ImageView) itemView.findViewById(R.id.iv_head);
tvFileName = (TextView) itemView.findViewById(R.id.tv_fileName);
tvFileTime = (TextView) itemView.findViewById(R.id.tv_fileTime);
tvFileSize = (TextView) itemView.findViewById(R.id.tv_fileSize);

}
}
}

Layout code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:padding="10dp">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">

<LinearLayout
android:layout_width="50dp"
android:layout_height="50dp"
android:gravity="center"
android:orientation="vertical">

<ImageView
android:id="@+id/iv_head"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY" />
</LinearLayout>


<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:gravity="center_vertical"
android:orientation="vertical">

<TextView
android:id="@+id/tv_fileName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sunny monday"
/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp">

<TextView
android:id="@+id/tv_fileTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2016/02/11"
/>

<TextView
android:id="@+id/tv_fileSize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="12.8mb"
/>
</LinearLayout>

</LinearLayout>
</LinearLayout>

</RelativeLayout>

10. Finally realize the overall code

The first is the code to display the top path, mainly a textview plus a HorizontalScrollView implementation

private void showTextPath(String path) {
String[] spPath = path.split(Type.ALL_PATH);
StringBuilder sbBuilder = new StringBuilder();
StringTokenizer tokenizer = new StringTokenizer(spPath[1], "/");
while (tokenizer.hasMoreTokens()) {
sbBuilder.append(tokenizer.nextToken() + "> ");
}

String likeUsers = sbBuilder.substring(0, sbBuilder.lastIndexOf(">")).toString();
tvShowPath.setMovementMethod(LinkMovementMethod.getInstance());
tvShowPath.setText(addClickablePart(likeUsers), TextView.BufferType.SPANNABLE);
}

/**
* File header path display
* @param str
* @return
*/
public SpannableStringBuilder addClickablePart(String str){
SpannableString spanStr = new SpannableString("");
SpannableStringBuilder ssb = new SpannableStringBuilder(spanStr);
ssb.append(str);

String[] likeUsers = str.split(">");

if (likeUsers.length> 0) {
for (int i = 0; i <likeUsers.length; i++) {
final String name = likeUsers[i];
final int start = str.indexOf(name) + spanStr.length();
ssb.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
if (mCurrentPath != null) {
String[] spPath = mCurrentPath.split(removeAllSpace(name));
Log.e(TAG, "onClickPath=" + mCurrentPath + "aa=" + spPath[0]);
String newPath = spPath[0] + removeAllSpace(name);
mCurrentPath = newPath;//update current path
showTextPath(newPath);
//refreshFileList(spPath[0] + msg);
new RefreshFileThread(spPath[0] + removeAllSpace(name)).start();
}
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
// ds.setColor(context.getResources().getColor(R.color.black)); // set text color
ds.setUnderlineText(false);
}
}, start, start + name.length(), 0);
}
}
return ssb.append("");
}
/**
* Remove spaces
* @param str
* @return
*/
public String removeAllSpace(String str) {
String tmpstr=str.replace(" ","");
return tmpstr;
}

 /**
* openFile
*
* @param file
*/
public void openFile(File file) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
String type = Utils.getMIMEType(file);
intent.setDataAndType(Uri.fromFile(file), type);
startActivity(intent);
}

The following implements the sorting dialog box and data refresh method

public void onSortChanged(FileSortHelper.SortMethod s, String path) {
if (fileSortHelper.getSortMethod() != s) {
fileSortHelper.setSortMethog(s);
//refreshFileList(path);
new RefreshFileThread(path).start();
}
}

/**
* show sort list
*/
public void showDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View layout = inflater.inflate(R.layout.dialog_sort, null);//Get custom layout
builder.setView(layout);
// builder.setTitle(R.string.sort);//Set title content
final AlertDialog dlg = builder.create();
dlg.show();
RadioGroup rgSort = (RadioGroup) layout.findViewById(R.id.rg_sort);
Log.e(TAG, "getSort=" + sortType);
if (SPInfo.getSort(MainActivity.this) == 0) {
rgSort.check(R.id.rb_name);
} else {
sortType = SPInfo.getSort(MainActivity.this);
switch (sortType) {
case Type.ID_SORT_NAME_ASC:
rgSort.check(R.id.rb_name);
break;
case Type.ID_SORT_TYPE_ASC:
rgSort.check(R.id.rb_type);
break;
case Type.ID_SORT_SIZE_ASC:
rgSort.check(R.id.rb_size);
break;
case Type.ID_SORT_TIME_ASC:
rgSort.check(R.id.rb_time);
break;
}
}
rgSort.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb_name:
sortType = Type.ID_SORT_NAME_ASC;//name
onSortChanged(FileSortHelper.SortMethod.name,mCurrentPath);
break;
case R.id.rb_size:
sortType = Type.ID_SORT_SIZE_ASC;//type
onSortChanged(FileSortHelper.SortMethod.size,mCurrentPath);
break;
case R.id.rb_time:
sortType = Type.ID_SORT_TIME_ASC;//time
onSortChanged(FileSortHelper.SortMethod.name,mCurrentPath);
break;
case R.id.rb_type:
sortType = Type.ID_SORT_TYPE_ASC;//type
onSortChanged(FileSortHelper.SortMethod.type,mCurrentPath);
break;
default:
break;
}
SPInfo.saveSort(MainActivity.this, sortType);//Save the sorting method
Log.e(TAG, "sortType=" + sortType);
dlg.dismiss();
}
});
}
//refresh file
private void refreshFileList() {
//if (path != null) {
//info = fileCategoryHelper.queryFile(path, fileSortHelper);
adapter.setData(info);
rvCategory.setAdapter(adapter);
adapter.notifyDataSetChanged();
//}
sendMsg(Type.CLOSE_PROGRESS);
}
/**
* refresh file list thread
*/
class RefreshFileThread extends Thread {
private String path;

public RefreshFileThread(String path) {
this.path = path;
}

@Override
public void run() {

if (path != null) {
sendMsg(Type.START_PROGRESS);
info = fileCategoryHelper.queryFile(path, fileSortHelper);
sendMsg(Type.UPDATE_LIST);
}
}
}

private void sendMsg(int type) {
Message msg = new Message();
msg.what = type;
handler.sendMessage(msg);
}

The complete code is as follows

package com.example.apple.myscdn;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.apple.myscdn.utils.DividerItemDecoration;
import com.example.apple.myscdn.utils.Type;
import com.example.apple.myscdn.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private final String TAG = "MainActivity";

private RecyclerView rvCategory;
private ImageView iv_back;
private TextView tv_title;
private ImageView iv_search;
private ImageView iv_more;
private TextView tvNoFile;
private RelativeLayout rl_title_bar;
private LinearLayout llShowPath;
private TextView tvShowPath;
private HorizontalScrollView scrollView;
private TextView tvSdcard;
private ProgressBar pbUpdate;
private FileCategoryHelper fileCategoryHelper;
private int sortType = Type.ID_SORT_NAME_ASC;//Initial sorting method
private String mCurrentPath = "/mnt/sdcard";//current path

private FileSortHelper fileSortHelper;
private ArrayList<FileInfo> info;
private MyFileCategoryAdapter adapter;

private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {

case Type.START_PROGRESS:
pbUpdate.setVisibility(View.VISIBLE);
break;

case Type.CLOSE_PROGRESS:
pbUpdate.setVisibility(View.GONE);
break;

case Type.UPDATE_LIST://update list
refreshFileList();
break;

case Type.SHOW_TOP_PATH:
llShowPath.setVisibility(View.VISIBLE);
break;
}

super.handleMessage(msg);
}
};

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


initView();
fileSortHelper = new FileSortHelper();
initShow();
}
private void initView() {
iv_back = (ImageView) findViewById(R.id.iv_back);
iv_back.setOnClickListener(this);
tv_title = (TextView) findViewById(R.id.tv_title);
tv_title.setOnClickListener(this);
iv_search = (ImageView) findViewById(R.id.iv_search);
iv_more = (ImageView) findViewById(R.id.iv_more);
iv_more.setOnClickListener(this);
rl_title_bar = (RelativeLayout) findViewById(R.id.rl_title_bar);

tvSdcard = (TextView) findViewById(R.id.tv_sdcard);
tvSdcard.setOnClickListener(this);
llShowPath = (LinearLayout) findViewById(R.id.ll_show_path);
tvShowPath = (TextView) findViewById(R.id.tv_show_path);
tvNoFile = (TextView) findViewById(R.id.tv_no_file);
rvCategory = (RecyclerView) findViewById(R.id.rv_category);
pbUpdate = (ProgressBar) findViewById(R.id.pb_update);

scrollView = (HorizontalScrollView) findViewById(R.id.scrollView);


}

private void initShow() {
tv_title.setText("File Sorting");
fileCategoryHelper = new FileCategoryHelper(this);
info = fileCategoryHelper.queryFile(mCurrentPath, fileSortHelper);

adapter = new MyFileCategoryAdapter(MainActivity.this, info);
rvCategory.setHasFixedSize(true);
// Create a linear layout manager
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// Set the layout manager
rvCategory.setLayoutManager(layoutManager);
layoutManager.setOrientation(OrientationHelper.VERTICAL);
rvCategory.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
rvCategory.setAdapter(adapter);

adapter.setOnItemClickListener(new setOnItemClickListener());

}

private void showTextPath(String path) {
String[] spPath = path.split(Type.ALL_PATH);
StringBuilder sbBuilder = new StringBuilder();
StringTokenizer tokenizer = new StringTokenizer(spPath[1], "/");
while (tokenizer.hasMoreTokens()) {
sbBuilder.append(tokenizer.nextToken() + "> ");
}

String likeUsers = sbBuilder.substring(0, sbBuilder.lastIndexOf(">")).toString();
tvShowPath.setMovementMethod(LinkMovementMethod.getInstance());
tvShowPath.setText(addClickablePart(likeUsers), TextView.BufferType.SPANNABLE);
}

/**
* File header path display
* @param str
* @return
*/
public SpannableStringBuilder addClickablePart(String str){
SpannableString spanStr = new SpannableString("");
SpannableStringBuilder ssb = new SpannableStringBuilder(spanStr);
ssb.append(str);

String[] likeUsers = str.split(">");

if (likeUsers.length> 0) {
for (int i = 0; i <likeUsers.length; i++) {
final String name = likeUsers[i];
final int start = str.indexOf(name) + spanStr.length();
ssb.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
if (mCurrentPath != null) {
String[] spPath = mCurrentPath.split(removeAllSpace(name));
Log.e(TAG, "onClickPath=" + mCurrentPath + "aa=" + spPath[0]);
String newPath = spPath[0] + removeAllSpace(name);
mCurrentPath = newPath;//update current path
showTextPath(newPath);
//refreshFileList(spPath[0] + msg);
new RefreshFileThread(spPath[0] + removeAllSpace(name)).start();
}
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
// ds.setColor(context.getResources().getColor(R.color.black)); // set text color
ds.setUnderlineText(false);
}
}, start, start + name.length(), 0);
}
}
return ssb.append("");
}
/**
* Remove spaces
* @param str
* @return
*/
public String removeAllSpace(String str) {
String tmpstr=str.replace(" ","");
return tmpstr;
}
//short onclick
class setOnItemClickListener implements MyFileCategoryAdapter.OnItemClickListener {
@Override
public void onItemClick(View view, int position, String filePath) {
mCurrentPath = filePath;
File file = new File(filePath);
if (file.exists() && file.canRead() && file.isDirectory()) {
new RefreshFileThread(filePath).start();
} else {
openFile(file);
}
if (!mCurrentPath.equals(Type.ALL_PATH) && file.isDirectory()) {
showTextPath(filePath);
}
scrollView.post(new Runnable() {
public void run() {
scrollView.fullScroll(View.FOCUS_RIGHT);
}
});
}
}
/**
* open a file
*
* @param file
*/
public void openFile(File file) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
String type = Utils.getMIMEType(file);
intent.setDataAndType(Uri.fromFile(file), type);
startActivity(intent);
}

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.iv_back:
finish();
break;
case R.id.iv_more:
showDialog();
break;
case R.id.tv_sdcard:
//refreshFileList(Type.ALL_PATH);
new RefreshFileThread(Type.ALL_PATH).start();
tvShowPath.setText("");
mCurrentPath = Type.ALL_PATH;//update current path
break;
}
}
public void onSortChanged(FileSortHelper.SortMethod s, String path) {
if (fileSortHelper.getSortMethod() != s) {
fileSortHelper.setSortMethog(s);
//refreshFileList(path);
new RefreshFileThread(path).start();
}
}
/**
* show sort list
*/
public void showDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View layout = inflater.inflate(R.layout.dialog_sort, null);//Get custom layout
builder.setView(layout);
// builder.setTitle(R.string.sort);//Set title content
final AlertDialog dlg = builder.create();
dlg.show();
RadioGroup rgSort = (RadioGroup) layout.findViewById(R.id.rg_sort);
Log.e(TAG, "getSort=" + sortType);
if (SPInfo.getSort(MainActivity.this) == 0) {
rgSort.check(R.id.rb_name);
} else {
sortType = SPInfo.getSort(MainActivity.this);
switch (sortType) {
case Type.ID_SORT_NAME_ASC:
rgSort.check(R.id.rb_name);
break;
case Type.ID_SORT_TYPE_ASC:
rgSort.check(R.id.rb_type);
break;
case Type.ID_SORT_SIZE_ASC:
rgSort.check(R.id.rb_size);
break;
case Type.ID_SORT_TIME_ASC:
rgSort.check(R.id.rb_time);
break;
}
}
rgSort.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb_name:
sortType = Type.ID_SORT_NAME_ASC;//name
onSortChanged(FileSortHelper.SortMethod.name,mCurrentPath);
break;
case R.id.rb_size:
sortType = Type.ID_SORT_SIZE_ASC;//type
onSortChanged(FileSortHelper.SortMethod.size,mCurrentPath);
break;
case R.id.rb_time:
sortType = Type.ID_SORT_TIME_ASC;//time
onSortChanged(FileSortHelper.SortMethod.name,mCurrentPath);
break;
case R.id.rb_type:
sortType = Type.ID_SORT_TYPE_ASC;//type
onSortChanged(FileSortHelper.SortMethod.type,mCurrentPath);
break;
default:
break;
}
SPInfo.saveSort(MainActivity.this, sortType);//Save the sorting method
Log.e(TAG, "sortType=" + sortType);
dlg.dismiss();
}
});
}
//refresh file
private void refreshFileList() {
//if (path != null) {
//info = fileCategoryHelper.queryFile(path, fileSortHelper);
adapter.setData(info);
rvCategory.setAdapter(adapter);
adapter.notifyDataSetChanged();
//}
sendMsg(Type.CLOSE_PROGRESS);
}
/**
* refresh file list thread
*/
class RefreshFileThread extends Thread {
private String path;
public RefreshFileThread(String path) {
this.path = path;
}
@Override
public void run() {
if (path != null) {
sendMsg(Type.START_PROGRESS);
info = fileCategoryHelper.queryFile(path, fileSortHelper);
sendMsg(Type.UPDATE_LIST);
}
}
}

private void sendMsg(int type) {
Message msg = new Message();
msg.what = type;
handler.sendMessage(msg);
}
}

Layout code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.a550211.mycsdn.MainActivity">

<include layout="@layout/title_bar" />
<LinearLayout
android:id="@+id/ll_show_path"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp">

<TextView
android:id="@+id/tv_sdcard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Internal storage device> "/>


<HorizontalScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none">

<TextView
android:id="@+id/tv_show_path"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</HorizontalScrollView>

</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.RecyclerView
android:id="@+id/rv_category"
android:layout_width="match_parent"
android:layout_height="wrap_content"></android.support.v7.widget.RecyclerView>

<TextView
android:id="@+id/tv_no_file"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="No files"
android:visibility="gone" />

<ProgressBar
android:id="@+id/pb_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" />
</RelativeLayout>
</LinearLayout>

Sorting dialog layout code implementation

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:padding="10dp"
android:textSize="23dp"
android:gravity="center"
android:layout_width="match_parent"
android:text="sort"
android:layout_height="wrap_content" />

<RadioGroup
android:id="@+id/rg_sort"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<RadioButton
android:id="@+id/rb_name"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:button="@null"
android:drawableRight="@android:drawable/btn_radio"
android:paddingLeft="30dip"
android:text="name"
android:textSize="20dip" />

<RadioButton
android:id="@+id/rb_time"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:button="@null"
android:drawableRight="@android:drawable/btn_radio"
android:paddingLeft="30dip"
android:text="time"
android:textSize="20dip" />

<RadioButton
android:id="@+id/rb_type"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:button="@null"
android:drawableRight="@android:drawable/btn_radio"
android:paddingLeft="30dip"
android:text="type"
android:textSize="20dip" />

<RadioButton
android:id="@+id/rb_size"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:button="@null"
android:drawableRight="@android:drawable/btn_radio"
android:paddingLeft="30dip"
android:text="size"
android:textSize="20dip" />

</RadioGroup>

</LinearLayout>

title_bar.xml code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="51dp"
android:gravity="center_vertical"
android:id="@+id/rl_title_bar"
android:padding="5dp">

<LinearLayout
android:id="@+id/ll_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:gravity="center_vertical"
android:orientation="horizontal">

<ImageView
android:id="@+id/iv_back"
android:layout_width="12dp"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />

<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:text="file management"
android:textSize="18sp" />

</LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="12dp"
android:orientation="horizontal">

<ImageView
android:id="@+id/iv_search"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />

<ImageView
android:id="@+id/iv_more"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:src="@drawable/ic_launcher" />
</LinearLayout>
</RelativeLayout>

utils code

package com.example.apple.myscdn.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* Created by apple on 17/5/10.
*/

public class Utils {
/**
* Convert file size
*
* @param fileS
* @return
*/
public static String FormatFileSize(long fileS) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
String wrongSize = "0B";
if (fileS == 0) {
return wrongSize;
}
if (fileS <1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS <1048576) {
fileSizeString = df.format((double) fileS / 1024) + "KB";
} else if (fileS <1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "MB";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "GB";
}
return fileSizeString;
}
/**
* Convert milliseconds to a specific time format
*
* @param time
* @return
*/
public static String LongTimeToStr(long time) {
int m = 1000;
int f = m * 60;
int h = f * 60;
Date date = new Date(time);
if (time <h * f * m) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
return sdf.format(date);
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
return sdf.format(date);
}
}
/**
* Get the number of files
*
* @param path
* @return
*/
public static int getFileNum(String path) {
File file = new File(path);
int fileNum = 0;
File[] fileArray = file.listFiles();
if (fileArray!=null) {
for (File f: fileArray) {
if (f.isFile() || f.isDirectory() && !f.isHidden()) {
fileNum++;
}
}
}
return fileNum;
}
/**
* Get file size
*
* @param file
* @return
* @throws Exception
*/
public static long getFileSize(File file) throws Exception {
long size = 0;
if (file.exists() && !file.isDirectory()) {
FileInputStream fis = null;
fis = new FileInputStream(file);
size = fis.available();
} else {
file.createNewFile();
Log.e("Get file size", "File does not exist!");
}
return size;
}
/*
* A new method is adopted to obtain the APK icon. The previous failure was due to a bug in android.
* appInfo.publicSourceDir = apkPath; to fix this problem, see for details:
* http://code.google.com/p/android/issues/detail?id=9151
*/
public static Drawable getApkIcon(Context context, String apkPath) {
PackageManager pm = context.getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(apkPath,
PackageManager.GET_ACTIVITIES);
if (info != null) {
ApplicationInfo appInfo = info.applicationInfo;
appInfo.sourceDir = apkPath;
appInfo.publicSourceDir = apkPath;
try {
return appInfo.loadIcon(pm);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
}
return null;
}
public static String getMIMEType(File f) {
String type = "";
String fileName = f.getName();
String ext = fileName.substring(fileName.lastIndexOf(".")
+ 1, fileName.length()).toLowerCase();
if (ext.equals("jpg") || ext.equals("jpeg") || ext.equals("gif")
|| ext.equals("png") || ext.equals("bmp") || ext.equals("wbmp")) {
type = "image/*";
} else if (ext.equals("mp3") || ext.equals("amr") || ext.equals("wma")
|| ext.equals("aac") || ext.equals("m4a") || ext.equals("mid")
|| ext.equals("xmf") || ext.equals("ogg") || ext.equals("wav")
|| ext.equals("qcp") || ext.equals("awb") || ext.equals("flac") || ext.equals("3gpp")) {
type = "audio/*";
} else if (ext.equals("3gp") || ext.equals("avi") || ext.equals("mp4")
|| ext.equals("3g2") || ext.equals("wmv") || ext.equals("divx")
|| ext.equals("mkv") || ext.equals("webm") || ext.equals("ts")
|| ext.equals("asf") || ext.equals("flv") || ext.equals("mov") || ext.equals("mpg")) {
type = "video/*";
} else if (ext.equals("apk")) {
type = "application/vnd.android.package-archive";
} else if (ext.equals("vcf")) {
type = "text/x-vcard";
} else if (ext.equals("txt")) {
type = "text/plain";
} else if (ext.equals("doc") || ext.equals("docx")) {
type = "application/msword";
}else if (ext.equals("xls") || ext.equals("xlsx")) {
type = "application/vnd.ms-excel";
} else if (ext.equals("ppt") || ext.equals("pptx")) {
type = "application/vnd.ms-powerpoint";
} else if (ext.equals("pdf")) {
type = "application/pdf";
} else if (ext.equals("xml")) {
type = "text/xml";
} else if (ext.equals("html")) {
type = "text/html";
} else if (ext.equals("zip")) {
type = "application/zip";
} else {
type = "application/octet-stream";
}
return type;
}
public static String getExtFromFilename(String filename) {
int dotPosition = filename.lastIndexOf('.');
if (dotPosition != -1) {
return filename.substring(dotPosition + 1, filename.length());
}
return "";
}
public static String getNameFromFilename(String filename) {
int dotPosition = filename.lastIndexOf('.');
if (dotPosition != -1) {
return filename.substring(0, dotPosition);
}
return "";
}
}

use permissions

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>

Remember to add the recycleview.jar package

compile files('libs/android-support-v7-recyclerview.jar')

  • Taken
  • add comment
  • 0