Show pic cover pdf in Listview - android

I have pdf reader with listview with icon pdf
and how to make cover pdf show in listview like this?
or
source code: https://deepshikhapuri.wordpress.com/2017/04/24/open-pdf-file-from-sdcard-in-android-programmatically/
How to change pdf icon to cover pdf in listview?
thanks
Main Activity.java
ListView lv_pdf;
public static ArrayList<File> fileList = new ArrayList<File>();
PDFAdapter obj_adapter;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
File dir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
lv_pdf = (ListView) findViewById(R.id.lv_pdf);
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"Pdf");
fn_permission();
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
intent.putExtra("position", i);
startActivity(intent);
Log.e("Position", i + "Pdf");
}
});
}
public static ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
getfile(listFile[i]);
} else {
boolean booleanpdf = false;
if (listFile[i].getName().endsWith(".pdf")) {
for (int j = 0; j < fileList.size(); j++) {
if (fileList.get(j).getName().equals(listFile[i].getName())) {
booleanpdf = true;
} else {
}
}
if (booleanpdf) {
booleanpdf = false;
} else {
fileList.add(listFile[i]);
}
}
}
}
}
return fileList;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
PdfActivity
public static final String SAMPLE_FILE = "android_tutorial.pdf";
PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
String TAG = "PdfActivity";
int position = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
init();
}
private void init() {
pdfView = (PDFView) findViewById(R.id.pdfView);
//position = Environment.getExternalStorageDirectory()+"/sdcard/Pdf"
position = getIntent().getIntExtra("position", -1);
displayFromSdcard();
//String position = Environment.getExternalStorageDirectory().getAbsolutePath() +"/Pdf/";
}
private void displayFromSdcard() {
pdfFileName = MainActivity.fileList.get(position).getName();
pdfView.fromFile(MainActivity.fileList.get(position))
.defaultPage(pageNumber)
.enableSwipe(true)
.password("123456")
.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
#Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
}
#Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), "-");
}
public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {
Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));
if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + "-");
}
}
}
PdfAdapter
Context context;
ViewHolder viewHolder;
ArrayList<File> al_pdf;
public PDFAdapter(Context context, ArrayList<File> al_pdf) {
super(context, R.layout.adapter_pdf, al_pdf);
this.context = context;
this.al_pdf = al_pdf;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_pdf.size() > 0) {
return al_pdf.size();
} else {
return 1;
}
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
if (view == null) {
view = LayoutInflater.from(getContext()).inflate(R.layout.adapter_pdf, parent, false);
viewHolder = new ViewHolder();
viewHolder.tv_filename = (TextView) view.findViewById(R.id.tv_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.tv_filename.setText(al_pdf.get(position).getName());
return view;
}
public class ViewHolder {
TextView tv_filename;
}

You can create the image by creating the bitmap of pdf first page. Then save the image to your app directory to be used later. You can use PdfiumCore (which is dependency of barteks PdfView) to generate the image.
You can use the following:
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.PdfiumCore;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
class PDFUtils {
static String generateAndSaveFirstPageImage(Context context, Uri uri, long bookId) {
try {
ParcelFileDescriptor fd = context.getContentResolver().openFileDescriptor(uri, "r");
int pageNum = 0;
PdfiumCore pdfiumCore = new PdfiumCore(context);
try {
PdfDocument pdfDocument = pdfiumCore.newDocument(fd);
pdfiumCore.openPage(pdfDocument, 0); // open first page for cover.
int width = pdfiumCore.getPageWidthPoint(pdfDocument, pageNum);
int height = pdfiumCore.getPageHeightPoint(pdfDocument, pageNum);
// do a fit center to 1920x1080
//double scaleBy = Math.min(1080 / (double) width, //
// 1920 / (double) height);
//width = (int) (width * scaleBy);
//height = (int) (height * scaleBy);
// ARGB_8888 - best quality, high memory usage, higher possibility of OutOfMemoryError
// RGB_565 - little worse quality, twice less memory usage
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
pdfiumCore.renderPageBitmap(pdfDocument, bitmap, pageNum, 0, 0, width, height);
//if you need to render annotations and form fields, you can use
//the same method above adding 'true' as last param
String fileName = bookId + ".jpg";
// save the file
File outputFile = new File(context.getFilesDir(), fileName);
FileOutputStream outputStream = new FileOutputStream(outputFile);
// a bit long running
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
fd.close();
pdfiumCore.closeDocument(pdfDocument); // important!
return fileName;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Then, you need to use the class by using the following:
long bookId = 2345; // your book identifier
Url yourPdfUrl; // url of pdf in your device
PdfUtils.generateAndSaveFirstPageImage(context, yourPdfUrl, bookId);
After you have saved the image, you can use the image again with something like this:
String imagePath = getFilesDir() + "/" + yourBookId + ".jpg";

Related

Blank screen when opening a pdf using 'com.github.barteksc:android-pdf-viewer:2.8.2' library

I have an issue with using this library
compile 'com.github.barteksc:android-pdf-viewer:2.8.2'
Well I have a couple of pdfs created from my app and I want to give th user an option to view them from the app.Im loading the files from a dialog and on select the selected pdf shoulld open.Here is the dialog.
public class FileExplore extends BaseActivityAlt {
private static final String TAG = "F_PATH";
private static final int DIALOG_LOAD_FILE = 1000;
ArrayList<String> str = new ArrayList<String>();
ListAdapter adapter;
private Boolean firstLvl = true;
private Item[] fileList;
private File path = new File(Environment.getExternalStorageDirectory() + "/Travelite/Saved/");
private String chosenFile;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadFileList();
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
#Override
public void onBackPressed(){
Intent intent = new Intent(this,TicketActivity.class);
startActivity(intent);
}
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(TAG, "unable to write on the sd card ");
}
// Checks whether path exists
if (path.exists()) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
// Filters based on whether the file is hidden or not
return (sel.isFile() || sel.isDirectory())
&& !sel.isHidden();
}
};
String[] fList = path.list(filter);
fileList = new Item[fList.length];
for (int i = 0; i < fList.length; i++) {
fileList[i] = new Item(fList[i], R.mipmap.pdf_icon);
// Convert into file path
File sel = new File(path, fList[i]);
// Set drawables
if (sel.isDirectory()) {
fileList[i].icon = R.drawable.company;
Log.d("DIRECTORY", fileList[i].file);
} else {
Log.d("FILE", fileList[i].file);
}
}
if (!firstLvl) {
Item temp[] = new Item[fileList.length + 1];
for (int i = 0; i < fileList.length; i++) {
temp[i + 1] = fileList[i];
}
temp[0] = new Item("Up", R.drawable.forward);
fileList = temp;
}
} else {
Log.e(TAG, "path does not exist");
}
adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = view
.findViewById(android.R.id.text1);
// put the image on the text view
textView.setCompoundDrawablesWithIntrinsicBounds(
fileList[position].icon, 0, 0, 0);
// add margin between image and text (support various screen
// densities)
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
textView.setCompoundDrawablePadding(dp5);
return view;
}
};
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
if (fileList == null) {
Log.e(TAG, "No files loaded");
dialog = builder.create();
return dialog;
}
switch (id) {
case DIALOG_LOAD_FILE:
builder.setTitle(R.string.choose_file);
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
chosenFile = fileList[which].file;
File sel = new File(path + "/" + chosenFile);
if (sel.isDirectory()) {
firstLvl = false;
// Adds chosen directory to list
str.add(chosenFile);
fileList = null;
path = new File(sel + "");
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// Checks if 'up' was clicked
else if (chosenFile.equalsIgnoreCase("up") && !sel.exists()) {
// present directory removed from list
String s = str.remove(str.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList = null;
// if there are no more directories in the list, then
// its the first level
if (str.isEmpty()) {
firstLvl = true;
}
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// File picked
else {
File file = new File(Environment.getExternalStorageDirectory(),
chosenFile);
Intent intent = new Intent(FileExplore.this,PdfViewer.class);
intent.putExtra("Filename",chosenFile);
startActivity(intent);
}
}
});
break;
}
dialog = builder.show();
return dialog;
}
private class Item {
public String file;
public int icon;
public Item(String file, Integer icon) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}}
And here is the class loaded onClicking an item in the dialog
public class PdfViewer extends BaseActivityAlt implements OnLoadCompleteListener, OnPageErrorListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pdf_viewer);
PDFView pdfView = (PDFView) findViewById(R.id.pdfView);
String filename = getIntent().getStringExtra("Filename");
File pdffile = new File(Environment.getExternalStorageDirectory(),filename);
Uri file = Uri.fromFile(pdffile);
Toast.makeText(PdfViewer.this, filename, Toast.LENGTH_LONG).show();
pdfView.fromUri(file)
.defaultPage(1)
.password(null)
.load();
}
#Override
public void loadComplete(int nbPages) {
}
#Override
public void onPageError(int page, Throwable t) {
}}
I just realised my mistake: I completely forgot to add the path.

How can I save my current imageview when onClick?

How can I save my current ImageView when I press onClick?
Im currently having the problem that the image that is next in line is being saved instead of the current actual image..
My Code for saving onLike
public class MainActivity extends Activity implements SwipeView.OnCardSwipedListener {
// Declaring variables
private final static int CARDS_MAX_ELEMENTS = 5;
private FrameLayout contentLayout;
private SwipeView mSwipeView;
private View addCardc41;
private Firebase mRef;
public ImageView imageLogo;
public ImageView imageview;
private static final String TAG = "MyActivity";
// Creating array of meals, getting them from the drawable folder
private int[] meals = {
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d,
R.drawable.e,
R.drawable.f,
R.drawable.g,
R.drawable.h,
R.drawable.i,
R.drawable.j
};
// Declaring a counter for the next method
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_view_demo);
contentLayout = (FrameLayout) findViewById(R.id.contentLayout);
imageLogo = (ImageView) findViewById(R.id.imageView3);
imageview = (ImageView) findViewById(R.id.imageView);
// Add the swipe view
mSwipeView = new SwipeView(this, R.id.imgSwipeLike, R.id.imgSwipeNope,
this);
contentLayout.addView(mSwipeView);
// Adding the cards initially with the maximum limits of cards.
for (int i = 0; i < CARDS_MAX_ELEMENTS; i++) {
addCard(i);
}
}
/**
* On clicked view.
*
* #param clickedView
* the clicked view
*/
public void onClickedView(View clickedView) {
switch (clickedView.getId()) {
case R.id.imgDisLike: {
mSwipeView.dislikeCard();
break;
}
case R.id.imgLike: {
mSwipeView.likeCard();
break;
}
}
}
#Override
public void onLikes() {
imageview.setDrawingCacheEnabled(true); //Add this line.
imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onDisLikes() {
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onSingleTap() {
}
/**
* Adds the card to the swipe.
*/
private void addCard(int position) {
final View cardView = LayoutInflater.from(this).inflate(
R.layout.item_swipe_view, null);
final ImageView imgMeal = (ImageView) cardView
.findViewById(R.id.imgMeals);
imgMeal.setImageResource(meals[count]);
count++;
if (count == meals.length) {
count = 0;
}
// Add a card to the swipe view..
mSwipeView.addCard(cardView, position);
// Create OnClickListener for the CookBookActivity
// Declare Button for the Cookbook
Button btn = (Button) findViewById(R.id.button3);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CookbookActivity.class));
}
});
// Check Authentication
mRef = new Firebase(Constants.FIREBASE_URL);
if (mRef.getAuth() == null) {
loadLoginView();
}
}
private void loadLoginView() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
The Library that i'm using for the swiping
//
// credits to IntelliJ IDEA
// (powered by Fernflower decompiler)
package com.rk.lib.view;
import android.content.Context;
import android.os.Handler;
import android.os.Build.VERSION;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.FrameLayout.LayoutParams;
public class SwipeView extends FrameLayout {
private View mFocusedView;
private View mFocusedViewLike;
private View mFocusedViewNope;
private int mFocusedViewWidth;
private float mPreviousAlpha = 0.0F;
private Integer mLikeResource = Integer.valueOf(0);
private Integer mNopeResource = Integer.valueOf(0);
private static final int MAX_ELEMENTS = 3;
private static final long DELAY_SCROLL_RUNNABLE = 1L;
private static final int SCROLL_LENGTH = 5;
private int mScrolledPixelsX;
private int mScrolledPixelsY;
private int mNeedToScrollX;
private int mNeedToScrollY;
private int mTotalScrolledX;
private int mTotalScrolledY;
private int mScrollLengthX = 5;
private int mScrollLengthY = 5;
private boolean enableTouchSwipe = true;
private Context mContext;
private SwipeView.ScrollMode mScrollModeX;
private SwipeView.ScrollMode mScrollModeY;
private SwipeView.ScrollDirection mScrollDirection;
private int[] paddingX;
private int[] paddingYTop;
private int[] paddingYBottom;
private SwipeView.OnCardSwipedListener mOnCardSwipedListener;
private Handler mScrollHandler;
private Runnable mScrollRunnable;
private final SimpleOnGestureListener simpleOnGestureListener;
public SwipeView(Context context, Integer likeResource, Integer nopeResource, SwipeView.OnCardSwipedListener cardSwipeListener) {
super(context);
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
this.paddingX = new int[]{0, 10, 20};
this.paddingYTop = new int[]{0, 10, 20};
this.paddingYBottom = new int[]{20, 10, 0};
this.mScrollHandler = new Handler();
this.mScrollRunnable = new Runnable() {
public void run() {
boolean scrollX;
boolean scrollY;
int scrollX1;
int scrollY1;
if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.OUT) {
if(SwipeView.this.mNeedToScrollX <= 0 && SwipeView.this.mNeedToScrollY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.removeView(SwipeView.this.mFocusedView);
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
SwipeView.this.mOnCardSwipedListener.onLikes();
} else if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.RIGHT) {
SwipeView.this.mOnCardSwipedListener.onDisLikes();
}
SwipeView.this.alignCardsPadding();
} else {
if(SwipeView.this.mNeedToScrollX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mNeedToScrollX;
SwipeView.this.mNeedToScrollX = 0;
} else {
SwipeView.this.mNeedToScrollX = SwipeView.this.mNeedToScrollX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mNeedToScrollY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mNeedToScrollY;
SwipeView.this.mNeedToScrollY = 0;
} else {
SwipeView.this.mNeedToScrollY = SwipeView.this.mNeedToScrollY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = -SwipeView.this.mScrollLengthX;
} else {
scrollX1 = SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
} else if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.IN) {
if(SwipeView.this.mTotalScrolledX <= 0 && SwipeView.this.mTotalScrolledY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.mScrollDirection = SwipeView.ScrollDirection.NONE;
} else {
if(SwipeView.this.mTotalScrolledX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mTotalScrolledX;
SwipeView.this.mTotalScrolledX = 0;
} else {
SwipeView.this.mTotalScrolledX = SwipeView.this.mTotalScrolledX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mTotalScrolledY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mTotalScrolledY;
SwipeView.this.mTotalScrolledY = 0;
} else {
SwipeView.this.mTotalScrolledY = SwipeView.this.mTotalScrolledY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = SwipeView.this.mScrollLengthX;
} else {
scrollX1 = -SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
}
}
};
this.simpleOnGestureListener = new SimpleOnGestureListener() {
public boolean onSingleTapConfirmed(MotionEvent e) {
SwipeView.this.mOnCardSwipedListener.onSingleTap();
return super.onSingleTapConfirmed(e);
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if(SwipeView.this.mFocusedView != null) {
SwipeView.this.mScrolledPixelsX = SwipeView.this.mScrolledPixelsX + (int)distanceX;
SwipeView.this.mScrolledPixelsY = SwipeView.this.mScrolledPixelsY + (int)distanceY;
SwipeView.this.mFocusedView.scrollBy((int)distanceX, (int)distanceY);
float alpha = (float)SwipeView.this.mScrolledPixelsX / (float)SwipeView.this.mFocusedViewWidth;
if(alpha > 0.0F) {
SwipeView.this.mFocusedViewNope.setVisibility(0);
SwipeView.this.mFocusedViewLike.setVisibility(8);
SwipeView.setAlpha(SwipeView.this.mFocusedViewNope, SwipeView.this.mPreviousAlpha, alpha);
SwipeView.this.mPreviousAlpha = alpha;
} else {
SwipeView.this.mFocusedViewNope.setVisibility(8);
SwipeView.this.mFocusedViewLike.setVisibility(0);
SwipeView.setAlpha(SwipeView.this.mFocusedViewLike, SwipeView.this.mPreviousAlpha, -alpha);
SwipeView.this.mPreviousAlpha = -alpha;
}
}
return true;
}
};
this.mContext = context;
this.mLikeResource = likeResource;
this.mNopeResource = nopeResource;
this.mOnCardSwipedListener = cardSwipeListener;
float density = this.getResources().getDisplayMetrics().density;
for(int gestureDetector = 0; gestureDetector < this.paddingX.length; ++gestureDetector) {
this.paddingX[gestureDetector] = (int)((float)this.paddingX[gestureDetector] * density);
this.paddingYTop[gestureDetector] = (int)((float)this.paddingYTop[gestureDetector] * density);
this.paddingYBottom[gestureDetector] = (int)((float)this.paddingYBottom[gestureDetector] * density);
}
final GestureDetector var7 = new GestureDetector(this.mContext, this.simpleOnGestureListener);
this.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(SwipeView.this.getChildCount() > 0) {
if(SwipeView.this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return false;
} else if(!SwipeView.this.enableTouchSwipe) {
return false;
} else {
var7.onTouchEvent(event);
switch(event.getAction()) {
case 0:
if(SwipeView.this.getChildCount() > 0) {
SwipeView.this.mFocusedView = SwipeView.this.getChildAt(SwipeView.this.getChildCount() - 1);
SwipeView.this.mFocusedViewLike = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mLikeResource.intValue());
SwipeView.this.mFocusedViewNope = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mNopeResource.intValue());
SwipeView.this.mFocusedViewWidth = SwipeView.this.mFocusedView.getWidth();
SwipeView.this.mFocusedView.setPadding(SwipeView.this.paddingX[0], 0, SwipeView.this.paddingX[0], 0);
}
SwipeView.this.resetScrollingValues();
break;
case 1:
SwipeView.this.alignCardsPadding();
if(SwipeView.this.mScrolledPixelsX < 0) {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.LEFT;
SwipeView.this.mTotalScrolledX = -SwipeView.this.mScrolledPixelsX;
} else {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
SwipeView.this.mTotalScrolledX = SwipeView.this.mScrolledPixelsX;
}
if(SwipeView.this.mScrolledPixelsY < 0) {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.BOTTOM;
SwipeView.this.mTotalScrolledY = -SwipeView.this.mScrolledPixelsY;
} else {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.TOP;
SwipeView.this.mTotalScrolledY = SwipeView.this.mScrolledPixelsY;
}
SwipeView.this.detectSwipe();
}
return true;
}
} else {
return false;
}
}
});
}
public void addCard(View view, int position) {
if(this.getChildCount() <= 3 && position < 3) {
LinearLayout viewLayout = new LinearLayout(this.mContext);
viewLayout.setLayoutParams(new LayoutParams(-1, -1));
view.setLayoutParams(new LayoutParams(-1, -1));
viewLayout.addView(view);
viewLayout.setPadding(this.paddingX[position], this.paddingYTop[position], this.paddingX[position], this.paddingYBottom[position]);
this.addView(viewLayout, 0);
}
}
public void removeFocusedCard() {
this.removeView(this.mFocusedView);
this.alignCardsPadding();
}
private void alignCardsPadding() {
int i = 0;
for(int j = this.getChildCount() - 1; j >= 0; --j) {
this.getChildAt(j).setPadding(this.paddingX[i], this.paddingYTop[i], this.paddingX[i], this.paddingYBottom[i]);
++i;
}
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
}
private void resetScrollingValues() {
this.mPreviousAlpha = 0.0F;
this.mNeedToScrollX = 0;
this.mScrolledPixelsX = 0;
this.mTotalScrolledX = 0;
this.mNeedToScrollY = 0;
this.mScrolledPixelsY = 0;
this.mTotalScrolledY = 0;
this.mScrollLengthX = 5;
this.mScrollLengthY = 5;
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
}
public void resetFocuedView() {
if(this.getChildCount() > 0) {
View mFocusedView = this.getChildAt(this.getChildCount() - 1);
View mFocusedViewLike = mFocusedView.findViewById(this.mLikeResource.intValue());
View mFocusedViewNope = mFocusedView.findViewById(this.mNopeResource.intValue());
setAlpha(mFocusedViewLike, 0.0F, 0.0F);
setAlpha(mFocusedViewNope, 0.0F, 0.0F);
mFocusedView.scrollTo(0, 0);
}
}
private void detectSwipe() {
int imageHalf = this.mFocusedView.getWidth() / 2;
this.mNeedToScrollX = this.mFocusedView.getWidth() - this.mTotalScrolledX;
if(this.mScrollDirection == SwipeView.ScrollDirection.NONE) {
if(this.mNeedToScrollX < imageHalf) {
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
} else {
this.mScrollDirection = SwipeView.ScrollDirection.IN;
setAlpha(this.mFocusedViewLike, 0.0F, 0.0F);
setAlpha(this.mFocusedViewNope, 0.0F, 0.0F);
}
}
this.mScrollHandler.post(this.mScrollRunnable);
}
public void likeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.LEFT;
this.mFocusedViewLike.setVisibility(0);
setAlpha(this.mFocusedViewLike, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void dislikeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
this.mFocusedViewNope.setVisibility(0);
setAlpha(this.mFocusedViewNope, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void setTouchable(boolean touchable) {
this.enableTouchSwipe = touchable;
}
public static void setAlpha(View view, float fromAlpha, float toAlpha) {
if(VERSION.SDK_INT < 11) {
AlphaAnimation alphaAnimation = new AlphaAnimation(fromAlpha, toAlpha);
alphaAnimation.setDuration(0L);
alphaAnimation.setFillAfter(true);
view.startAnimation(alphaAnimation);
} else {
view.setAlpha(toAlpha);
}
}
public interface OnCardSwipedListener {
void onLikes();
void onDisLikes();
void onSingleTap();
}
private static enum ScrollDirection {
IN,
OUT,
NONE;
private ScrollDirection() {
}
}
private static enum ScrollMode {
LEFT,
RIGHT,
TOP,
BOTTOM,
NONE;
private ScrollMode() {
}
}
}
ATTEMPT #3
This is the code that i've tried but I keep getting the same result (read comment below what I have done:
FrameLayout view = (FrameLayout)findViewById(R.id.contentLayout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
I believe the image you are trying to save is getting removed during the onSwipe due to the library code. I think you need to move your code to before the onLike is called.
You're also attempting to get a bitmap from the cache of the entire layout, rather than the wanted ImageView here:
bm=contentLayout.getDrawingCache();
You'll want to get your current card view as a View, then, from my understanding of your code, the ID of your actual ImageView containing the expected bitmap is R.id.imgMeals, so I the suggest replacing the line:
bm=contentLayout.getDrawingCache();
with the following:
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
Move all of the below code from where you have it, to where I have marked //HERE!! in the following part of your code (or better, move it to a new method and call the method here).
// If the imageview of like is clicked
case R.id.imgLike: {
// HERE!!
// The imageview in the contentlayout will be swiped to the right
mSwipeView.likeCard();
break;
}
This is the code to me moved including the change I mention above:
View cardView = mSwipeView.getChildAt(mSwipeView.getChildCount() - 1);
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
OutputStream fOut = null;
try {
// Save on my sd card
File root = new File(Environment.getExternalStorageDirectory()
// Making a folder name Food Inspiration
+ File.separator + "Food Inspiration" + File.separator);
root.mkdirs();
File sdImageMainDirectory = null;
// Loop for having a different name for every image
int i = 0;
do {
sdImageMainDirectory = new File(root, "pic-" + i + ".png");
i++;
} while (sdImageMainDirectory.exists());
fOut = new FileOutputStream(sdImageMainDirectory);
// Updates the gallery of your phone with the folder and the "liked" images in it
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
// If something goes wrong
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
// Compresses the actual bitmap image
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}

adapter holder on listener cannot be final

I need to add a progress listener to each element of the horizontal list view, how can I do that?
For each item I upload a file.
I wanna to do something like that but holder is not final, so I have an error.
public class UploadsViewAdapter extends BaseAdapter {
private Context mContext;
private int mLayoutResourceId;
List<Upload> listFileToUpload;
public UploadsViewAdapter(Context context, int layoutResourceId, List<Upload> data) {
this.mLayoutResourceId = layoutResourceId;
this.mContext = context;
this.listFileToUpload = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(mLayoutResourceId, parent, false);
holder = new ViewHolder();
holder.image = (ImageView) row.findViewById(R.id.upload_item_image);
holder.progressUpdate = (ProgressBar) row.findViewById(R.id.progressUpdate);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final Upload item = getItem(position);
holder.image.setImageBitmap(item.getThumbnail(160, 160));
item.setProgressListener(new ProgressListener() {
#Override
public void onProgress(int progress) {
holder.progressUpdate.setProgress(item.getProgress());
}
});
holder.progressUpdate.setProgress(item.getProgress());
return row;
}
static class ViewHolder {
ImageView image;
ProgressBar progressUpdate;
}
public void updateListFileToUpdate(List<Upload> listFileToUpload) {
this.listFileToUpload = listFileToUpload;
}
#Override
public int getCount() {
return listFileToUpload.size();
}
#Override
public Upload getItem(int location) {
return listFileToUpload.get(location);
}
#Override
public long getItemId(int position) {
return 0;
}
}
Class Update.java
public class Upload {
public String path;
public String type;
private int mProgress = 0;
private ProgressListener mListener;
public Upload(String path, String type) {
this.path = path;
this.type = type;
}
public void setProgressListener(ProgressListener listener) {
mListener = listener;
}
public void setProgress(int progress) {
mProgress = progress;
if (mListener != null) {
mListener.onProgress(progress);
}
}
public int getProgress() {
return mProgress;
}
public Bitmap getThumbnail(int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while (
(halfHeight / inSampleSize) > reqHeight &&
(halfWidth / inSampleSize) > reqWidth
) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public interface ProgressListener {
public void onProgress(int progress);
}
}
Class which updates the file:
public class TheFormFragment extends Fragment {
private AmazonS3Client mS3Client = new AmazonS3Client(
new BasicAWSCredentials(Config.AWS_ACCESS_KEY, Config.AWS_SECRET_KEY));
public static final int RESULT_PHOTO_DISK = 10;
public static final int RESULT_PHOTO_APN = 100;
public static final int RESULT_VIDEO_APN = 1000;
public static final String INTENT_PHOTO_APN_PATH = "INTENT_PHOTO_APN_PATH";
public static final String INTENT_VIDEO_APN_PATH = "INTENT_VIDEO_APN_PATH";
private List<Medias> mTheFormPictures;
private static Activity mActivity;
private static ArrayList<Upload> mQueue;
private KeyboardEventLinearLayout mLinearLayoutBackground;
private LinearLayout mLinearLayoutPublish;
private TextView mTextViewPublish;
private ImageView mImageViewPublish; // todo image du bouton
private EditText mEditTextText;
private TextView mTextViewTitle;
private CircularImageView mCircularImageViewAvatar;
private ImageButton mImageButtonClose;
private ImageButton mImageButtonCamera;
private ImageButton mImageButtonLibrary;
private Tag[] mTags = null;
private Range mAutocompleting;
private LinearLayout mAutocompleteContainer;
private HorizontalListView mUploadsList;
private UploadsViewAdapter mUploading;
/**Contains list of images, vidoe to update*/
private List<Upload> listFileToUpload;
private KeyboardEventLinearLayout.KeyboardListener mKeyboardListener = new KeyboardEventLinearLayout.KeyboardListener() {
#Override
public void onShow() {
if (mUploadsList != null) {
mUploadsList.setVisibility(View.GONE);
}
}
#Override
public void onHide() {
if (mUploadsList != null) {
mUploadsList.setVisibility(View.VISIBLE);
}
}
};
private class Range {
public int start;
public int end;
public String value;
public Range(int start, int end, String value) {
this.start = start;
this.end = end;
this.value = value;
}
}
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence text, int start, int oldCount, int newCount) {
String before = text.subSequence(0, start + newCount).toString();
Range range = findEditingTag(before);
autocompete(range);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void afterTextChanged(Editable s) {}
};
private OnClickListener mAutocompleteItemClickListener = new OnClickListener() {
#Override
public void onClick(View view) {
Editable text = mEditTextText.getText();
CharSequence tag = ((TextView) view).getText();
text.replace(mAutocompleting.start, mAutocompleting.end, tag);
}
};
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_the_form, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
mTheFormPictures = new ArrayList<Medias>();
mQueue = new ArrayList<Upload>();
mS3Client.setRegion(Region.getRegion(Config.AWS_REGION));
mLinearLayoutBackground = (KeyboardEventLinearLayout) mActivity.findViewById(R.id.linearLayoutBackground);
mLinearLayoutPublish = (LinearLayout) mActivity.findViewById(R.id.linearLayoutPublish);
mTextViewPublish = (TextView) mActivity.findViewById(R.id.textViewPublish);
mTextViewTitle = (TextView) mActivity.findViewById(R.id.textViewTitle);
mImageViewPublish = (ImageView) mActivity.findViewById(R.id.imageViewPublish);
mCircularImageViewAvatar = (CircularImageView) mActivity.findViewById(R.id.circularImageViewAvatar);
mEditTextText = (EditText) mActivity.findViewById(R.id.editTextText);
mImageButtonClose = (ImageButton) mActivity.findViewById(R.id.imageButtonClose);
mImageButtonCamera = (ImageButton) mActivity.findViewById(R.id.imageButtonCamera);
mImageButtonLibrary = (ImageButton) mActivity.findViewById(R.id.imageButtonLibrary);
mAutocompleteContainer = (LinearLayout) mActivity.findViewById(R.id.autocompleteLayout);
mUploadsList = (HorizontalListView) mActivity.findViewById(R.id.uploadsList);
listFileToUpload =new ArrayList<Upload>();
mUploading = new UploadsViewAdapter(mActivity, R.layout.upload_item, listFileToUpload);
mUploadsList.setAdapter(mUploading);
mLinearLayoutBackground.setKeyboardListener(mKeyboardListener);
configure();
super.onActivityCreated(savedInstanceState);
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void configure() {
AQuery aq = new AQuery(mActivity);
ImageOptions options = new ImageOptions();
//options.round = 180;
options.fileCache = false;
options.memCache = true;
//options.animation = AQuery.FADE_IN;
User user = Preferences.getUser(mActivity);
if (user != null) {
mTextViewTitle.setText(user.getFirst_name() + " " + user.getLast_name());
if (user.getAvatar() != null && user.getAvatar().length() > 0) {
aq.id(mCircularImageViewAvatar).image(user.getAvatar(), options);
}
}
StatusConfigTheForm configTheForm = Preferences.getConfigTheForm(mActivity);
if (configTheForm != null) {
Log.i("theform config success");
Log.d("avatar: " + user.getAvatar() + " " + configTheForm.getBorderWidth());
if (configTheForm.getColors().getBackground().length == 3) {
mLinearLayoutBackground.setBackgroundColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackground())));
}
if (configTheForm.getColors().getBackgrounPublishButton().length == 3) {
// mButtonPublish.setBackgroundColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgrounPublishButton())));
// prepare
int roundRadius = 6;
// normal state
GradientDrawable background_normal = new GradientDrawable();
background_normal.setColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgrounPublishButton())));
background_normal.setCornerRadius(roundRadius);
// pressed state
GradientDrawable bacground_pressed = new GradientDrawable();
bacground_pressed.setColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgrounPublishButton()).replace("#", "#CC"))); // opacity
bacground_pressed.setCornerRadius(roundRadius);
// states (normal and pressed)
StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed}, bacground_pressed);
states.addState(new int[] {-android.R.attr.state_pressed}, background_normal);
if (Build.VERSION.SDK_INT >= 16) {
mLinearLayoutPublish.setBackground(states);
} else {
mLinearLayoutPublish.setBackgroundDrawable(states);
}
}
if (configTheForm.getColors().getBackgroundTextView().length == 3) {
mEditTextText.setBackgroundColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgroundTextView())));
}
if (configTheForm.getColors().getBorderColorPicture().length == 3) {
mCircularImageViewAvatar.setBorderColor(Utils.getHexaColor(configTheForm.getColors().getBorderColorPicture()));
}
// add color tag here
if (configTheForm.getColors().getColorTextPublish().length == 3) {
mTextViewPublish.setTextColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getColorTextPublish())));
}
if (configTheForm.getColors().getColorTextAttachment().length == 3) {
mCircularImageViewAvatar.setBorderColor(Utils.getHexaColor(configTheForm.getColors().getColorTextAttachment()));
}
if (configTheForm.getColors().getColorTextUser().length == 3) {
mTextViewTitle.setTextColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getColorTextUser())));
}
if (configTheForm.getBorderWidth() > 0) {
mCircularImageViewAvatar.setBorderWidth(configTheForm.getBorderWidth() * Integer.valueOf(Float.valueOf(getResources().getDisplayMetrics().density).intValue()));
}
// pictures
if (configTheForm.getPictures() != null) {
String baseUrl = configTheForm.getUrlPicto() + configTheForm.getFolder() + File.separator;
String ext = Utils.setExtension(mActivity, Config.PICTURE_EXTENSION);
Pictures pics = configTheForm.getPictures();
if (configTheForm.getPictures().getPictureBack() != null) {
aq.id(mImageButtonClose).image(baseUrl + pics.getPictureBack() + ext, options);
}
if (configTheForm.getPictures().getPictureCamera() != null) {
aq.id(mImageButtonCamera).image(baseUrl + pics.getPictureCamera() + ext, options);
}
if (configTheForm.getPictures().getPictureLibrary() != null) {
aq.id(mImageButtonLibrary).image(baseUrl + pics.getPictureLibrary() + ext, options);
}
if (configTheForm.getPictures().getPicturePublish() != null) {
mImageViewPublish.setVisibility(View.VISIBLE);
aq.id(mImageViewPublish).image(baseUrl + pics.getPicturePublish() + ext, options);
} else {
mImageViewPublish.setVisibility(View.GONE);
}
}
}
mEditTextText.addTextChangedListener(textWatcher);
}
private Range findEditingTag(String text) {
Pattern pattern = Pattern.compile("#[A-z0-9_]+$");
Matcher match = pattern.matcher(text);
if (match.find()) {
String value = text.substring(match.start());
return new Range(match.start(), match.end(), value);
}
return null;
}
private void autocompete(Range range) {
mAutocompleting = range;
mAutocompleteContainer.removeAllViews();
if (range != null && mTags != null) {
String tag;
for (int i = 0; i < mTags.length; i++) {
tag = "#" + mTags[i].getName();
if (tag.startsWith(range.value) && tag.equals(range.value) == false) {
addAutocompleteItem(tag);
}
}
}
}
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
private void addAutocompleteItem(String text) {
Drawable background = mActivity.getResources().getDrawable(R.drawable.autocomplete_item);
int textColor = mActivity.getResources().getColor(R.color.autocomplete_item_text);
TextView view = new TextView(mActivity);
view.setText(text);
view.setTextColor(textColor);
view.setPadding(20, 10, 20, 10);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
params.setMargins(10, 0, 10, 0);
view.setLayoutParams(params);
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(background);
} else {
view.setBackground(background);
}
view.setClickable(true);
view.setOnClickListener(mAutocompleteItemClickListener);
mAutocompleteContainer.addView(view);
}
private void updateProgress() {
//int progress = 0;
//for (Upload file: mUploading) {
// progress += file.getProgress();
//}
//progress /= mUploading.size();
//mProgressBarFile.setProgress(progress);
//mTextViewFileProgress.setText(String.format(getString(R.string.theform_text_file_progress), Integer.valueOf(progress).toString()));
}
private class S3PutObjectTask extends AsyncTask<Upload, Integer, S3TaskResult> {
//private Dialog progressDialog;
ObjectMetadata mMetadata = new ObjectMetadata();
private String mS3Filename;
private Upload mFile;
#Override
protected void onPreExecute() {
updateProgress();
}
#Override
protected void onProgressUpdate(Integer... values) {
int progress = Integer.valueOf( (int) ((values[0] * 100) / mMetadata.getContentLength()) );
mFile.setProgress(progress);
updateProgress();
super.onProgressUpdate(values);
}
protected S3TaskResult doInBackground(Upload... files) {
if (files == null || files.length != 1 || files[0] == null) {
return null;
} else {
mFile = files[0];
}
ContentResolver resolver = mActivity.getContentResolver();
// The file location of the image selected.
Uri selectedSource = Uri.parse(mFile.path);
if (mFile.type.equals("image")) {
String size = null;
String fileSizeColumn[] = { OpenableColumns.SIZE };
Cursor cursor = resolver.query(selectedSource, fileSizeColumn, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
// If the size is unknown, the value stored is null. But since an int can't be
// null in java, the behavior is implementation-specific, which is just a fancy
// term for "unpredictable". So as a rule, check if it's null before assigning
// to an int. This will happen often: The storage API allows for remote
// files, whose size might not be locally known.
if (!cursor.isNull(sizeIndex)) {
// Technically the column stores an int, but cursor.getString will do the
// conversion automatically.
size = cursor.getString(sizeIndex);
}
cursor.close();
}
mMetadata.setContentType(resolver.getType(selectedSource));
if (size != null) {
mMetadata.setContentLength(Long.parseLong(size));
}
}
if (mMetadata.getContentType() == null) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedSource.toString(), opt);
mMetadata.setContentType(opt.outMimeType);
}
if (mMetadata.getContentLength() <= 0) {
mMetadata.setContentLength(new File(selectedSource.toString()).length());
}
selectedSource = Uri.parse("file://" + selectedSource.toString().replace("content://", ""));
S3TaskResult result = new S3TaskResult();
// Put the image data into S3.
try {
Calendar cal = Calendar.getInstance();
if (mFile.type.equals("image")) {
mS3Filename = Long.valueOf(cal.getTime().getTime()).toString() + ".jpg";
} else {
mS3Filename = Long.valueOf(cal.getTime().getTime()).toString() + ".mp4";
}
PutObjectRequest por = new PutObjectRequest(
Config.getPictureBucket(cal.getTime().getTime()), mS3Filename,
resolver.openInputStream(selectedSource), mMetadata
).withGeneralProgressListener(new ProgressListener() {
int total = 0;
#Override
public void progressChanged(ProgressEvent pv) {
total += (int) pv.getBytesTransferred();
publishProgress(total);
}
});
mS3Client.putObject(por);
result.setName(mS3Filename);
} catch (Exception exception) {
exception.printStackTrace();
result.setName(null);
result.setErrorMessage(exception.getMessage());
}
return result;
}
protected void onPostExecute(S3TaskResult result) {
//mProgressBarFile.setProgress(0);
//mTextViewFileProgress.setText("");
// AWS Error
if (result != null && result.getErrorMessage() != null && result.getName() == null) {
FastDialog.showDialog(mActivity, FastDialog.SIMPLE_DIALOG, result.getErrorMessage());
} else {
// add picture name
mTheFormPictures.add(new Medias(result.getName()));
}
}
}
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
/** close activity **/
public void close(View v) {
mActivity.finish();
}
/** select picture **/
public void selectPicture(View v) {
//Intent intent;
Intent intent = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
/*if (Build.VERSION.SDK_INT < 19) {
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
if (Build.VERSION.SDK_INT >= 18) {
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}*/
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("image/* video/*");
startActivityForResult(intent, RESULT_PHOTO_DISK);
}
/** take picture **/
public void tackePicture(View v) {
ApnActivity.show(mActivity, RESULT_PHOTO_APN);
}
/** record video **/
public void recordVideo(View v) {
RecordVideoActivity.show(mActivity, RESULT_VIDEO_APN);
}
/** publish button **/
public void publish(View v) {
// object
WebViewTheFormResult theFormResult = new WebViewTheFormResult(mEditTextText.getText().toString(), mTheFormPictures);
if (theFormResult.isEmpty()) {
FastDialog.showDialog(mActivity, FastDialog.SIMPLE_DIALOG, getString(R.string.theform_publish_error));
} else {
// intent
Intent dataIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putSerializable(WebViewActivity.INTENT_OBJECT, (Serializable) theFormResult);
dataIntent.putExtras(bundle);
mActivity.setResult(Activity.RESULT_OK, dataIntent);
mActivity.finish();
}
}
#SuppressLint("NewApi")
public static void actionOnActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_CANCELED) {
return;
}
if (requestCode != RESULT_PHOTO_APN && requestCode != RESULT_VIDEO_APN) {
requestCode = RESULT_PHOTO_DISK;
}
switch (requestCode) {
case RESULT_PHOTO_DISK:
if (Build.VERSION.SDK_INT >= 18 && data.getData() == null) {
ClipData clipdata = data.getClipData();
for (int i = 0, l = clipdata.getItemCount(); i < l; i++) {
onDiskResult(clipdata.getItemAt(i).getUri());
}
} else {
onDiskResult(data.getData());
}
break;
case RESULT_PHOTO_APN:
onApnPhotoResult(data);
break;
case RESULT_VIDEO_APN:
onApnVideoResult(data);
break;
}
}
private static void onDiskResult(Uri selectedImage) {
InputStream imageStream;
try {
File file = new File(
Environment.getExternalStorageDirectory() + File.separator +
"Android" + File.separator +
"data" + File.separator +
mActivity.getPackageName()
);
if (new File(file.getAbsolutePath()).exists() == false) {
file.mkdirs();
}
imageStream = mActivity.getContentResolver().openInputStream(selectedImage);
Bitmap goodPicture = BitmapFactory.decodeStream(imageStream);
String filePath = file.getAbsoluteFile().toString() + "/" + String.valueOf(Utils.uid()) + Config.PHOTO_TMP_NAME;
try {
//goodPicture = ThumbnailUtils.createVideoThumbnail(filePath, MediaStore.Images.Thumbnails.MINI_KIND);
FileOutputStream out = new FileOutputStream(filePath);
goodPicture = Bitmap.createScaledBitmap(goodPicture, 800, 600, false);
goodPicture.compress(Bitmap.CompressFormat.JPEG, 80, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
queueFile(filePath, "image");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return;
}
}
private static void onApnPhotoResult(Intent data) {
String filePath = data.getExtras().getString(TheFormFragment.INTENT_PHOTO_APN_PATH);
if (filePath.equals(Integer.valueOf(RESULT_VIDEO_APN).toString())) {
RecordVideoActivity.show(mActivity, RESULT_VIDEO_APN);
} else {
queueFile(filePath, "image");
}
}
private static void onApnVideoResult(Intent data) {
String filePath = data.getExtras().getString(TheFormFragment.INTENT_VIDEO_APN_PATH);
if (filePath.equals(Integer.valueOf(RESULT_PHOTO_APN).toString())) {
ApnActivity.show(mActivity, RESULT_PHOTO_APN);
} else {
queueFile(filePath, "video");
}
}
private static void queueFile(String filePath, String fileType) {
mQueue.add(new Upload(filePath, fileType));
}
#Override
public void onResume() {
fetchTags();
while (mQueue.size() > 0) {
uploadFile(mQueue.remove(mQueue.size() - 1));
}
super.onResume();
}
private void uploadFile(Upload file) {
new S3PutObjectTask().execute(file);
listFileToUpload.add(file);
mUploading.updateListFileToUpdate(listFileToUpload);
mUploading.notifyDataSetChanged();
}
private void fetchTags() {
Api.getTags(mActivity, new Api.Callback() {
#Override
public void onSuccess(String json) {
Gson gson = new Gson();
mTags = gson.fromJson(json, Tag[].class);
}
});
}
}
How can I resolve the problem?
Something like this should be enough:
...
holder.image.setImageBitmap(item.getThumbnail(160, 160));
final ViewHolder finalHolder = holder;
item.setProgressListener(new ProgressListener() {
#Override
public void onProgress(int progress) {
finalHolder.progressUpdate.setProgress(item.getProgress());
}
});
finalHolder.progressUpdate.setProgress(item.getProgress());
Think that you can remove setProgressListener() from Upload class.
Instead add a ProgressBar variable and a method setProgressBar() to Upload.
In getView():
Upload upload = getItem(position )
upload.setProgressBar(holder.progressUpdate);
In Upload: in setProgress() you can now directly address the ProgressBar variable
this is the setProgress() that in your AsyncTask is called with mFile.setProgress(progress);
Instead of removing better out comment the function and the call.
Untested. Please test. This will not be much work.
Don't make holder final. It will not help you. You also made item final in order to use it in onProgress. But that will not do either. You have to determine the right holder with getTag() and if you put position in the holder (as int variable) then you can use holder.position to get the right item again with a getItem(holder.position)
Thanks for your responses all.
I resolved the problem like this:
public class UploadsViewAdapter extends BaseAdapter {
private Context mContext;
List<Upload> listFileToUpload;
UploadsViewAdapter instanceUploadsViewAdapter;
public UploadsViewAdapter(Context context,
List<Upload> data) {
this.mContext = context;
this.listFileToUpload = data;
this.instanceUploadsViewAdapter = this;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(R.layout.upload_item, parent, false);
holder = new ViewHolder();
holder.image = (ImageView) row.findViewById(R.id.upload_item_image);
holder.play = (ImageView) row.findViewById(R.id.play);
holder.progressUpdate = (ProgressBar) row
.findViewById(R.id.progressUpdate);
holder.deleteFileUploaded = (ImageView) row.findViewById(R.id.delete_file_uploaded);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final Upload item = getItem(position);
holder.image.setImageBitmap(item.getThumbnail(160, 160));
final ViewHolder finalHolder = holder;
item.setProgressListener(new ProgressListener() {
#Override
public void onProgress(int progress) {
//item.setProgress(progress);
finalHolder.progressUpdate.setProgress(progress);
if(progress==100){
finalHolder.image.setAlpha(1.0f);
finalHolder.progressUpdate.setVisibility(View.GONE);
}
else{
finalHolder.image.setAlpha(0.5f);
finalHolder.progressUpdate.setVisibility(View.VISIBLE);
}
}
});
if(item.getProgress()==100){
finalHolder.image.setAlpha(1.0f);
finalHolder.progressUpdate.setVisibility(View.GONE);
}
else{
finalHolder.image.setAlpha(0.5f);
finalHolder.progressUpdate.setVisibility(View.VISIBLE);
}
holder.deleteFileUploaded.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
listFileToUpload.remove(position);
instanceUploadsViewAdapter.notifyDataSetChanged();
}
});
if(item.getType().equals(EnumTypeFile.IMAGE.getTypeFile())){
holder.play.setVisibility(View.GONE);
}
else{
holder.play.setVisibility(View.VISIBLE);
}
finalHolder.progressUpdate.setProgress(item.getProgress());
return row;
}
static class ViewHolder {
ImageView image;
ProgressBar progressUpdate;
ImageView deleteFileUploaded;
ImageView play;
}
public void updateListFileToUpdate(List<Upload> listFileToUpload) {
this.listFileToUpload = listFileToUpload;
}
#Override
public int getCount() {
return listFileToUpload.size();
}
#Override
public Upload getItem(int location) {
return listFileToUpload.get(location);
}
#Override
public long getItemId(int position) {
return 0;
}
}

Not able to see files while opening file browser using AndroidFileBrowser Library

I am trying to make a File browser for which I am taking help of this library.
Now according their code I am trying to implement, it's opening the desired location in the cell, however I am only able to see directories not files. As instructed I have chosen the option to choose Files only still I am not able to see Files there. Below is the code I am using
Intent fileExploreIntent = new Intent(FileBrowserActivity.INTENT_ACTION_SELECT_DIR,
null, getActivity(), FileBrowserActivity.class
);
startActivityForResult(fileExploreIntent,1);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 1) {
if(resultCode == getActivity().RESULT_OK) {
String newDir = data.getStringExtra(FileBrowserActivity.returnDirectoryParameter);
Toast.makeText( getActivity(), "Received path from file browser:"+newDir, Toast.LENGTH_LONG).show();
} else {//if(resultCode == this.RESULT_OK) {
Toast.makeText( getActivity(),"Received NO result from file browser",Toast.LENGTH_LONG).show();
}//END } else {//if(resultCode == this.RESULT_OK) {
}//if (requestCode == REQUEST_CODE_PICK_FILE_TO_SAVE_INTERNAL) {
super.onActivityResult(requestCode, resultCode, data);
}
Code for FileBrowserActivity is
public class FileBrowserActivity extends Activity {
// Intent Action Constants
public static final String INTENT_ACTION_SELECT_DIR = "com.afixi.xmppclientandroid.SELECT_DIRECTORY_ACTION";
public static final String INTENT_ACTION_SELECT_FILE = "com.afixi.xmppclientandroid.SELECT_FILE_ACTION";
// Intent parameters names constants
public static final String startDirectoryParameter = "com.afixi.xmppclientandroid.directoryPath";
public static final String returnDirectoryParameter = "com.afixi.xmppclientandroid.directoryPathRet";
public static final String returnFileParameter = "com.afixi.xmppclientandroid.filePathRet";
public static final String showCannotReadParameter = "com.afixi.xmppclientandroid.showCannotRead";
public static final String filterExtension = "com.afixi.xmppclientandroid.filterExtension";
// Stores names of traversed directories
ArrayList<String> pathDirsList = new ArrayList<String>();
// Check if the first level of the directory structure is the one showing
// private Boolean firstLvl = true;
private static final String LOGTAG = "F_PATH";
private List<Item> fileList = new ArrayList<Item>();
private File path = null;
private String chosenFile;
// private static final int DIALOG_LOAD_FILE = 1000;
ArrayAdapter<Item> adapter;
private boolean showHiddenFilesAndDirs = true;
private boolean directoryShownIsEmpty = false;
private String filterFileExtension = null;
// Action constants
private static int currentAction = -1;
private static final int SELECT_DIRECTORY = 1;
private static final int SELECT_FILE = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// In case of
// ua.com.vassiliev.androidfilebrowser.SELECT_DIRECTORY_ACTION
// Expects com.mburman.fileexplore.directoryPath parameter to
// point to the start folder.
// If empty or null, will start from SDcard root.
setContentView(R.layout.ua_com_vassiliev_filebrowser_layout);
// Set action for this activity
Intent thisInt = this.getIntent();
currentAction = SELECT_DIRECTORY;// This would be a default action in
// case not set by intent
if (thisInt.getAction().equalsIgnoreCase(INTENT_ACTION_SELECT_FILE)) {
Log.d(LOGTAG, "SELECT ACTION - SELECT FILE");
currentAction = SELECT_FILE;
}
showHiddenFilesAndDirs = thisInt.getBooleanExtra(
showCannotReadParameter, true);
filterFileExtension = thisInt.getStringExtra(filterExtension);
setInitialDirectory();
parseDirectoryPath();
loadFileList();
this.createFileListAdapter();
this.initializeButtons();
this.initializeFileListView();
updateCurrentDirectoryTextView();
Log.d(LOGTAG, path.getAbsolutePath());
}
private void setInitialDirectory() {
Intent thisInt = this.getIntent();
String requestedStartDir = thisInt
.getStringExtra(startDirectoryParameter);
if (requestedStartDir != null && requestedStartDir.length() > 0) {// if(requestedStartDir!=null
File tempFile = new File(requestedStartDir);
if (tempFile.isDirectory())
this.path = tempFile;
}// if(requestedStartDir!=null
if (this.path == null) {// No or invalid directory supplied in intent
// parameter
if (Environment.getExternalStorageDirectory().isDirectory()
&& Environment.getExternalStorageDirectory().canRead())
path = Environment.getExternalStorageDirectory();
else
path = new File("/");
}// if(this.path==null) {//No or invalid directory supplied in intent
// parameter
}// private void setInitialDirectory() {
private void parseDirectoryPath() {
pathDirsList.clear();
String pathString = path.getAbsolutePath();
String[] parts = pathString.split("/");
int i = 0;
while (i < parts.length) {
pathDirsList.add(parts[i]);
i++;
}
}
private void initializeButtons() {
Button upDirButton = (Button) this.findViewById(R.id.upDirectoryButton);
upDirButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(LOGTAG, "onclick for upDirButton");
loadDirectoryUp();
loadFileList();
adapter.notifyDataSetChanged();
updateCurrentDirectoryTextView();
}
});// upDirButton.setOnClickListener(
Button selectFolderButton = (Button) this
.findViewById(R.id.selectCurrentDirectoryButton);
if (currentAction == SELECT_DIRECTORY) {
selectFolderButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(LOGTAG, "onclick for selectFolderButton");
returnDirectoryFinishActivity();
}
});
} else {// if(currentAction == this.SELECT_DIRECTORY) {
selectFolderButton.setVisibility(View.GONE);
}// } else {//if(currentAction == this.SELECT_DIRECTORY) {
}// private void initializeButtons() {
private void loadDirectoryUp() {
// present directory removed from list
String s = pathDirsList.remove(pathDirsList.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList.clear();
}
private void updateCurrentDirectoryTextView() {
int i = 0;
String curDirString = "";
while (i < pathDirsList.size()) {
curDirString += pathDirsList.get(i) + "/";
i++;
}
if (pathDirsList.size() == 0) {
((Button) this.findViewById(R.id.upDirectoryButton))
.setEnabled(false);
curDirString = "/";
} else
((Button) this.findViewById(R.id.upDirectoryButton))
.setEnabled(true);
long freeSpace = getFreeSpace(curDirString);
String formattedSpaceString = formatBytes(freeSpace);
if (freeSpace == 0) {
Log.d(LOGTAG, "NO FREE SPACE");
File currentDir = new File(curDirString);
if(!currentDir.canWrite())
formattedSpaceString = "NON Writable";
}
((Button) this.findViewById(R.id.selectCurrentDirectoryButton))
.setText("Select\n[" + formattedSpaceString
+ "]");
((TextView) this.findViewById(R.id.currentDirectoryTextView))
.setText("Current directory: " + curDirString);
}// END private void updateCurrentDirectoryTextView() {
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
private void initializeFileListView() {
ListView lView = (ListView) this.findViewById(R.id.fileListView);
lView.setBackgroundColor(Color.LTGRAY);
LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
lParam.setMargins(15, 5, 15, 5);
lView.setAdapter(this.adapter);
lView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
chosenFile = fileList.get(position).file;
File sel = new File(path + "/" + chosenFile);
Log.d(LOGTAG, "Clicked:" + chosenFile);
if (sel.isDirectory()) {
if (sel.canRead()) {
// Adds chosen directory to list
pathDirsList.add(chosenFile);
path = new File(sel + "");
Log.d(LOGTAG, "Just reloading the list");
loadFileList();
adapter.notifyDataSetChanged();
updateCurrentDirectoryTextView();
Log.d(LOGTAG, path.getAbsolutePath());
} else {// if(sel.canRead()) {
showToast("Path does not exist or cannot be read");
}// } else {//if(sel.canRead()) {
}// if (sel.isDirectory()) {
// File picked or an empty directory message clicked
else {// if (sel.isDirectory()) {
Log.d(LOGTAG, "item clicked");
if (!directoryShownIsEmpty) {
Log.d(LOGTAG, "File selected:" + chosenFile);
returnFileFinishActivity(sel.getAbsolutePath());
}
}// else {//if (sel.isDirectory()) {
}// public void onClick(DialogInterface dialog, int which) {
});// lView.setOnClickListener(
}// private void initializeFileListView() {
private void returnDirectoryFinishActivity() {
Intent retIntent = new Intent();
retIntent.putExtra(returnDirectoryParameter, path.getAbsolutePath());
this.setResult(RESULT_OK, retIntent);
this.finish();
}// END private void returnDirectoryFinishActivity() {
private void returnFileFinishActivity(String filePath) {
Intent retIntent = new Intent();
retIntent.putExtra(returnFileParameter, filePath);
this.setResult(RESULT_OK, retIntent);
this.finish();
}// END private void returnDirectoryFinishActivity() {
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(LOGTAG, "unable to write on the sd card ");
}
fileList.clear();
if (path.exists() && path.canRead()) {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
boolean showReadableFile = showHiddenFilesAndDirs
|| sel.canRead();
// Filters based on whether the file is hidden or not
if (currentAction == SELECT_DIRECTORY) {
return (sel.isDirectory() && showReadableFile);
}
if (currentAction == SELECT_FILE) {
// If it is a file check the extension if provided
if (sel.isFile() && filterFileExtension != null) {
return (showReadableFile && sel.getName().endsWith(
filterFileExtension));
}
return (showReadableFile);
}
return true;
}// public boolean accept(File dir, String filename) {
};// FilenameFilter filter = new FilenameFilter() {
String[] fList = path.list(filter);
this.directoryShownIsEmpty = false;
for (int i = 0; i < fList.length; i++) {
// Convert into file path
File sel = new File(path, fList[i]);
Log.d(LOGTAG,
"File:" + fList[i] + " readable:"
+ (Boolean.valueOf(sel.canRead())).toString());
int drawableID = R.drawable.file_icon;
boolean canRead = sel.canRead();
// Set drawables
if (sel.isDirectory()) {
if (canRead) {
drawableID = R.drawable.folder_icon;
} else {
drawableID = R.drawable.folder_icon_light;
}
}
fileList.add(i, new Item(fList[i], drawableID, canRead));
}// for (int i = 0; i < fList.length; i++) {
if (fileList.size() == 0) {
// Log.d(LOGTAG, "This directory is empty");
this.directoryShownIsEmpty = true;
fileList.add(0, new Item("Directory is empty", -1, true));
} else {// sort non empty list
Collections.sort(fileList, new ItemFileNameComparator());
}
} else {
Log.e(LOGTAG, "path does not exist or cannot be read");
}
// Log.d(TAG, "loadFileList finished");
}// private void loadFileList() {
private void createFileListAdapter() {
adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view
.findViewById(android.R.id.text1);
// put the image on the text view
int drawableID = 0;
if (fileList.get(position).icon != -1) {
// If icon == -1, then directory is empty
drawableID = fileList.get(position).icon;
}
textView.setCompoundDrawablesWithIntrinsicBounds(drawableID, 0,
0, 0);
textView.setEllipsize(null);
// add margin between image and text (support various screen
// densities)
// int dp5 = (int) (5 *
// getResources().getDisplayMetrics().density + 0.5f);
int dp3 = (int) (3 * getResources().getDisplayMetrics().density + 0.5f);
// TODO: change next line for empty directory, so text will be
// centered
textView.setCompoundDrawablePadding(dp3);
textView.setBackgroundColor(Color.LTGRAY);
return view;
}// public View getView(int position, View convertView, ViewGroup
};// adapter = new ArrayAdapter<Item>(this,
}// private createFileListAdapter(){
private class Item {
public String file;
public int icon;
public boolean canRead;
public Item(String file, Integer icon, boolean canRead) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}// END private class Item {
private class ItemFileNameComparator implements Comparator<Item> {
public int compare(Item lhs, Item rhs) {
return lhs.file.toLowerCase().compareTo(rhs.file.toLowerCase());
}
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Log.d(LOGTAG, "ORIENTATION_LANDSCAPE");
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Log.d(LOGTAG, "ORIENTATION_PORTRAIT");
}
// Layout apparently changes itself, only have to provide good onMeasure
// in custom components
// TODO: check with keyboard
// if(newConfig.keyboard == Configuration.KEYBOARDHIDDEN_YES)
}// END public void onConfigurationChanged(Configuration newConfig) {
public static long getFreeSpace(String path) {
StatFs stat = new StatFs(path);
long availSize = (long) stat.getAvailableBlocks()
* (long) stat.getBlockSize();
return availSize;
}// END public static long getFreeSpace(String path) {
public static String formatBytes(long bytes) {
// TODO: add flag to which part is needed (e.g. GB, MB, KB or bytes)
String retStr = "";
// One binary gigabyte equals 1,073,741,824 bytes.
if (bytes > 1073741824) {// Add GB
long gbs = bytes / 1073741824;
retStr += (new Long(gbs)).toString() + "GB ";
bytes = bytes - (gbs * 1073741824);
}
// One MB - 1048576 bytes
if (bytes > 1048576) {// Add GB
long mbs = bytes / 1048576;
retStr += (new Long(mbs)).toString() + "MB ";
bytes = bytes - (mbs * 1048576);
}
if (bytes > 1024) {
long kbs = bytes / 1024;
retStr += (new Long(kbs)).toString() + "KB";
bytes = bytes - (kbs * 1024);
} else
retStr += (new Long(bytes)).toString() + " bytes";
return retStr;
}// public static String formatBytes(long bytes){
}// END public class FileBrowserActivity extends Activity {

How can I display images from a specific folder on android gallery

How can I display all images from a specific folder on android gallery like, for example, whatapp does.
I`m using MediaScannerConnectionClient
File folder = new File("/sdcard/myfolder/");
allFiles = folder.list();
SCAN_PATH=Environment.getExternalStorageDirectory().toString()+"/myfolder/"+allFiles[0];
#Override
public void onScanCompleted(String path, Uri uri) {
try {
if (uri != null) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} finally {
conn.disconnect();
conn = null;
}
}
private void startScan() {
if (conn != null) {
conn.disconnect();
}
conn = new MediaScannerConnection(this, this);
conn.connect();
}
#Override
public void onMediaScannerConnected() {
conn.scanFile(SCAN_PATH, "image/*");
}
But I`m getting a error at this point:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
Specific here:
startActivity(intent);
Fail to get type for: content://media/external/images/media/267830
No Activity found to handle Intent
On onScanCompleted my path and uri parameters are not null.
Hi you can use the code below, i hope it helps you .
package com.example.browsepicture;
import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class BrowsePicture2 extends Activity {
String SCAN_PATH;
File[] allFiles ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browse_picture);
File folder = new File(Environment.getExternalStorageDirectory().getPath()+"/aaaa/");
allFiles = folder.listFiles();
((Button) findViewById(R.id.button1))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
new SingleMediaScanner(BrowsePicture2.this, allFiles[0]);
}
});
}
public class SingleMediaScanner implements MediaScannerConnectionClient {
private MediaScannerConnection mMs;
private File mFile;
public SingleMediaScanner(Context context, File f) {
mFile = f;
mMs = new MediaScannerConnection(context, this);
mMs.connect();
}
public void onMediaScannerConnected() {
mMs.scanFile(mFile.getAbsolutePath(), null);
}
public void onScanCompleted(String path, Uri uri) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
mMs.disconnect();
}
}
}
You should add Grid view Adapter class.
public class GalleryPictureActivity extends Activity
{
private String[] FilePathStrings;
private File[] listFile;
GridView grid;
GridViewAdapter adapter;
File file;
public static Bitmap bmp = null;
ImageView imageview;
#Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_picture);
// Check for SD Card
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED))
{
Toast.makeText(this, "Error! No SDCARD Found!",
Toast.LENGTH_LONG).show();
}
else
{
// Locate the image folder in your SD Card
file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/images");
}
if (file.isDirectory())
{
listFile = file.listFiles();
FilePathStrings = new String[listFile.length];
for (int i = 0; i < listFile.length; i++)
{
FilePathStrings[i] = listFile[i].getAbsolutePath();
}
}
grid = (GridView)findViewById(R.id.gridview);
adapter = new GridViewAdapter(this, FilePathStrings);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick (AdapterView<?> parent, View view,
int position, long id)
{
imageview = (ImageView)findViewById(R.id.imageView1);
int targetWidth = 700;
int targetHeight = 500;
BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
bmpOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(FilePathStrings[position],
bmpOptions);
int currHeight = bmpOptions.outHeight;
int currWidth = bmpOptions.outWidth;
int sampleSize = 1;
if (currHeight > targetHeight || currWidth > targetWidth)
{
if (currWidth > currHeight)
sampleSize = Math.round((float)currHeight
/ (float)targetHeight);
else
sampleSize = Math.round((float)currWidth
/ (float)targetWidth);
}
bmpOptions.inSampleSize = sampleSize;
bmpOptions.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(FilePathStrings[position],
bmpOptions);
imageview.setImageBitmap(bmp);
imageview.setScaleType(ImageView.ScaleType.FIT_XY);
bmp = null;
}
});
}
}
Another Class GridView Adapter :
public class GridViewAdapter extends BaseAdapter
{
private Activity activity;
private String[] filepath;
private static LayoutInflater inflater = null;
Bitmap bmp = null;
public GridViewAdapter (Activity a, String[] fpath)
{
activity = a;
filepath = fpath;
inflater = (LayoutInflater)activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount ()
{
return filepath.length;
}
public Object getItem (int position)
{
return position;
}
public long getItemId (int position)
{
return position;
}
public View getView (int position, View convertView, ViewGroup parent)
{
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.gridview_item, null);
ImageView image = (ImageView)vi.findViewById(R.id.image);
int targetWidth = 100;
int targetHeight = 100;
BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
bmpOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filepath[position], bmpOptions);
int currHeight = bmpOptions.outHeight;
int currWidth = bmpOptions.outWidth;
int sampleSize = 1;
if (currHeight > targetHeight || currWidth > targetWidth)
{
if (currWidth > currHeight)
sampleSize = Math.round((float)currHeight
/ (float)targetHeight);
else
sampleSize = Math.round((float)currWidth
/ (float)targetWidth);
}
bmpOptions.inSampleSize = sampleSize;
bmpOptions.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(filepath[position], bmpOptions);
image.setImageBitmap(bmp);
image.setScaleType(ImageView.ScaleType.FIT_XY);
bmp = null;
return vi;
}
}
Activity:
activity_gallery_picture:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center" >
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight=".85">
</GridView>
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight=".25"
android:scaleType="fitXY"
android:src="#drawable/galleryimage" />
</LinearLayout>
Another activity Layout :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" >
<ImageView
android:id="#+id/image"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
You can use android.database.Cursor
public boolean OpenGalleryFromFolder(android.content.Context context, String folderName)
{
String filePath = android.os.Environment.getExternalStorageDirectory().getPath() + "/Pictures/" + folderName + "/";
return OpenGalleryFromPathToFolder(context, filePath);
}
// Finds the first image in the specified folder and uses it to open a the devices native gallery app with all images in that folder.
public boolean OpenGalleryFromPathToFolder(android.content.Context context, String folderPath)
{
java.io.File folder = new java.io.File(folderPath);
java.io.File[] allFiles = folder.listFiles();
if (allFiles != null && allFiles.length > 0)
{
android.net.Uri imageInFolder = getImageContentUri(context, allFiles[0]);
if (imageInFolder != null)
{
android.content.Intent intent = new android.content.Intent(android.content.Intent.ACTION_VIEW);
intent.setData(imageInFolder);
context.startActivity(intent);
return true;
}
}
return false;
}
// converts the absolute path of a file to a content path
// absolute path example: /storage/emulated/0/Pictures/folderName/Image1.jpg
// content path example: content://media/external/images/media/47560
private android.net.Uri getImageContentUri(android.content.Context context, java.io.File imageFile) {
String filePath = imageFile.getAbsolutePath();
android.database.Cursor cursor = context.getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{android.provider.MediaStore.Images.Media._ID},
android.provider.MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(android.provider.MediaStore.MediaColumns._ID));
return android.net.Uri.withAppendedPath(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id);
} else {
if (imageFile.exists()) {
android.content.ContentValues values = new android.content.ContentValues();
values.put(android.provider.MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
Answer given by #Talha works good but it tries to open image using image app options. If you want to just refresh gallery with folder in sd card you can modify code as below for SingleMediaScanner
class SingleMediaScanner implements MediaScannerConnectionClient {
private MediaScannerConnection mMs;
private File mFile;
public SingleMediaScanner(Context context, File f) {
mFile = f;
mMs = new MediaScannerConnection(context, this);
mMs.connect();
}
public void onMediaScannerConnected() {
mMs.scanFile(mFile.getAbsolutePath(), null);
}
public void onScanCompleted(String path, Uri uri) {
mMs.disconnect();
}
}
And in button click loop over each file you get from:
File folder = new File(Environment.getExternalStorageDirectory().getPath()+"/aaaa/");
allFiles = folder.listFiles();
And pass that to SingleMediaScanner one at time.
It worked in my case.
You can fetch image from specific folder on SDcard using my ways also delete the files.
MainActivity
FileAdapter fileAdapter;
RecyclerView recyclerView;
ArrayList<String> filePath = new ArrayList<>();
ArrayList<String> filename = new ArrayList<>();
private File[] listFile;
File file;
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
tv_empty = findViewById(R.id.tv_empty);
loadFiles();
fileAdapter = new FileAdapter(this, filePath, filename);
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
recyclerView.setAdapter(fileAdapter);
fileAdapter.notifyDataSetChanged();
private void loadFiles() {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Toast.makeText(getActivity(), "Error! No SDCARD Found!", Toast.LENGTH_LONG).show();
} else {
file = new File(Environment.getExternalStorageDirectory().getPath() + "/StorySaver");
if (!file.exists()) {
file.mkdirs();
}
}
filePath.clear();
filename.clear();
if (file.isDirectory()) {
listFile = file.listFiles();
for (File absolutePath : listFile) {
filePath.add(absolutePath.getAbsolutePath());
filename.add(absolutePath.getName());
}
}
if (filePath.size() == 0) {
tv_empty.setVisibility(View.VISIBLE);
} else {
tv_empty.setVisibility(View.GONE);
}
}
MyAdapter
public class FileAdapter extends RecyclerView.Adapter<FileAdapter.CustomViewHolder> {
ArrayList<String> filepath;
ArrayList<String> filename;
public Context mContext;
File file;
public class CustomViewHolder extends RecyclerView.ViewHolder {
TextView content;
ImageView imageView;
public CustomViewHolder(final View view) {
super(view);
this.content = (TextView) view.findViewById(R.id.content);
this.imageView = (ImageView) view.findViewById(R.id.image);
}
}
public FileAdapter(Context context, ArrayList<String> filepath, ArrayList<String> filename) {
this.filepath = filepath;
this.filename = filename;
this.mContext = context;
}
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
return new CustomViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_file, null));
}
public void onBindViewHolder(CustomViewHolder customViewHolder, final int i) {
file = new File(filepath.get(i));
customViewHolder.content.setText(filename.get(i));
Glide.with(this.mContext).load(filepath.get(i)).into(customViewHolder.imageView);
customViewHolder.imageView.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View view) {
Builder builder = new Builder(mContext);
builder.setMessage("Are you sure you want delete this?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int v) {
if (file.exists()) {
file.delete();
}
filepath.remove(i);
notifyDataSetChanged();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.show();
return false;
}
});
customViewHolder.imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
Uri data = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".provider", new File(filepath.get(i)));
intent.setDataAndType(data, "*/*");
try {
String substring = filename.get(i).substring(filename.get(i).lastIndexOf("."));
if (substring.equals(".jpg")) {
intent.setDataAndType(data, "image/*");
} else if (substring.equals(".mp4")) {
intent.setDataAndType(data, "video/*");
}
} catch (Exception e) {
e.printStackTrace();
}
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
mContext.startActivity(intent);
} catch (ActivityNotFoundException unused) {
Toast.makeText(mContext, "No application available", Toast.LENGTH_SHORT).show();
}
}
});
}
public int getItemCount() {
return filepath.size();
}
}
100% work
Kotlin
Fragment
class MyPhotosFragment : Fragment() {
private var _binding : FragmentMyPhotosBinding? = null
val binding get() = _binding!!
private lateinit var myPhotoAdapter : MyPhotoAdapter
var file: File? = null
var filePath: ArrayList<String> = ArrayList()
var filename: ArrayList<String> = ArrayList()
private var listFile: Array<File>? = null
#SuppressLint("NotifyDataSetChanged")
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentMyPhotosBinding.inflate(layoutInflater)
loadSpecificFile()
myPhotoAdapter = MyPhotoAdapter(requireContext(), filePath, filename)
binding.savedPhotoRecyclerView.layoutManager = GridLayoutManager(requireContext(),3)
binding.savedPhotoRecyclerView.adapter = myPhotoAdapter
myPhotoAdapter.notifyDataSetChanged()
return binding.root
}
private fun loadSpecificFile() {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Toast.makeText(requireContext(), "Error! No SDCARD Found!", Toast.LENGTH_LONG).show()
} else {
file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).path + "/PhotoEditor/")
if (!file!!.exists()){
file!!.mkdirs()
}
else{
listFile = file!!.listFiles { _, name ->
name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(
".png")
}
for (absolutePath in listFile!!) {
filePath.add(absolutePath.absolutePath)
filename.add(absolutePath.name)
}
}
}
}
}
Kotlin Adapter
class MyPhotoAdapter(var context : Context, private var myPhotosPathList: ArrayList<String>, private var myPhotosNameList: ArrayList<String>) : RecyclerView.Adapter<MyPhotoAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.saved_photo_layout, parent, false)
return ViewHolder(
view
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
var file = File(myPhotosPathList[position]);
Glide.with(context).load(file)
.into(holder.savedPhoto)
holder.savedPhoto.setOnLongClickListener {
val builder = AlertDialog.Builder(context)
builder.setMessage("Are you sure you want delete this?")
builder.setPositiveButton("YES"
) { _, _ ->
if (file.exists()) {
file.delete()
}
myPhotosPathList.removeAt(position)
notifyDataSetChanged()
}
builder.setNegativeButton("NO"
) { dialogInterface, i -> dialogInterface.cancel() }
builder.show()
false
}
holder.savedPhoto.setOnClickListener {
val intent = Intent()
intent.action = Intent.ACTION_VIEW
val data: Uri = FileProvider.getUriForFile(
context,
BuildConfig.APPLICATION_ID + ".provider",
File(myPhotosPathList[position])
)
intent.setDataAndType(data, "*/*")
try {
val substring: String =
myPhotosNameList[position].substring(myPhotosNameList[position].lastIndexOf("."))
if (substring == ".jpg" || substring == ".jpeg" || substring == ".png") {
intent.setDataAndType(data, "image/*")
}
} catch (e: Exception) {
e.printStackTrace()
}
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
try {
context.startActivity(intent)
} catch (unused: ActivityNotFoundException) {
Toast.makeText(context, "No application available", Toast.LENGTH_SHORT).show()
}
}
}
override fun getItemCount(): Int {
return myPhotosPathList.size
}
class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) {
val savedPhoto : ImageView = itemView.findViewById(R.id.savedPhoto)
}
}
Output

Categories

Resources