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

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

Related

Android saving audio/mp3 file to external storage

I have question about saving audio/mp3
file to external storage
after saving the file it show in external storage
but when I open any android music player the file not showing there
I try to change the folder to "/storage/emulated/0/Music/" still not showing
even on download folder nothing.
the app is for download music from YouTube using API
public class DownloadedActivity extends AppCompatActivity implements AdapterMusicDownloaded.ClickCallBack, View.OnClickListener {
private RecyclerView lvManager;
private AdapterMusicDownloaded adapterMusicSearch;
private ArrayList<ItemMusicDownloaded> arrayList = new ArrayList<>();
private LinearLayout llEmptyFile;
private static final String AUTHORITY = "com.free.music.downloader" + ".fileprovider";
public static final String PATH = Environment.getExternalStorageDirectory().toString() + "/FreeMusic/";
public static final String UPDATE_MUSIC = "update_music";
private ImageView imgBackSearch;
private InterstitialAd mInterstitialAd;
private AdView adView;
private ProgressBar loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_downloaded_songs);
initViews();
}
private void initViews() {
loading = findViewById(R.id.loading);
adView = findViewById(R.id.adView);
initAdsFull();
MobileAds.initialize(this, getResources().getString(R.string.mobile_id));
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
llEmptyFile = findViewById(R.id.ll_empty_file);
imgBackSearch = findViewById(R.id.img_back_downloaded);
imgBackSearch.setOnClickListener(this);
lvManager = findViewById(R.id.lv_main);
LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setOrientation(LinearLayoutManager.VERTICAL);
adapterMusicSearch = new AdapterMusicDownloaded(arrayList, this);
adapterMusicSearch.setCallBack(this);
lvManager.setLayoutManager(manager);
lvManager.setAdapter(adapterMusicSearch);
LoadAsync loadAsync = new LoadAsync();
loadAsync.execute();
}
#Override
public void clickItemMusic(int position) {
Intent playIntent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
final File photoFile = new File(arrayList.get(position).getLink());
Uri photoURI = FileProvider.getUriForFile(this, AUTHORITY, photoFile);
playIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
playIntent.setDataAndType(photoURI, "audio/*");
} else {
playIntent.setDataAndType(Uri.parse(arrayList.get(position).getLink()), "audio/*");
}
startActivity(playIntent);
}
#Override
public void clickOptionItemMusic(final int postion, View view) {
PopupMenu popupMenu = new PopupMenu(this, view);
popupMenu.inflate(R.menu.menu_option_main);
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete:
File file = new File(arrayList.get(postion).getLink());
boolean deleted = file.delete();
if (deleted) {
Toast.makeText(DownloadedActivity.this, getResources().getString(R.string.delete_finish), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(DownloadedActivity.this, getResources().getString(R.string.delete_error), Toast.LENGTH_SHORT).show();
}
arrayList.remove(postion);
adapterMusicSearch.notifyDataSetChanged();
break;
case R.id.menu_share_main:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
final File photoFile = new File(arrayList.get(postion).getLink());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri photoURI = FileProvider.getUriForFile(DownloadedActivity.this, AUTHORITY, photoFile);
shareIntent.putExtra(Intent.EXTRA_STREAM, photoURI);
} else {
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(photoFile));
}
shareIntent.setType("audio/*");
startActivity(Intent.createChooser(shareIntent, "Share music"));
break;
default:
break;
}
return false;
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.img_back_downloaded) {
onBackPressed();
}
}
#Override
public void onBackPressed() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
finish();
}
}
private class LoadAsync extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
llEmptyFile.setVisibility(View.GONE);
loading.setVisibility(View.VISIBLE);
}
#SuppressLint("WrongThread")
#Override
protected String doInBackground(Void... voids) {
arrayList.clear();
File f = new File(PATH);
File[] files = f.listFiles();
if (f.exists()) {
if (files.length <= 0) {
Log.d("sizearrList", "0");
return "OK";
} else {
Log.d("sizearrList", "2");
arrayList.clear();
Arrays.sort(files, new Comparator() {
public int compare(Object o1, Object o2) {
if (((File) o1).lastModified() > ((File) o2).lastModified()) {
return -1;
} else if (((File) o1).lastModified() < ((File) o2).lastModified()) {
return +1;
} else {
return 0;
}
}
});
for (File aFile : files) {
if (!aFile.isDirectory()) {
String name = aFile.getName();
String path = aFile.getPath();
getTimeVideo(aFile.getAbsolutePath());
Date lastModified = getFileLastModified(path);
arrayList.add(new ItemMusicDownloaded(name, path, lastModified, getTimeVideo(aFile.getAbsolutePath())))
;
} else {
Log.d("myLog", "Do not add");
}
}
Log.d("sizeArrsss", arrayList.size() + "");
for (int i = 0; i < arrayList.size(); i++) {
Log.d("sizeArr", arrayList.get(i).getTitle());
}
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (arrayList.size() == 0) {
llEmptyFile.setVisibility(View.VISIBLE);
} else {
llEmptyFile.setVisibility(View.GONE);
}
loading.setVisibility(View.GONE);
adapterMusicSearch.notifyDataSetChanged();
}
}
public static Date getFileLastModified(String pathFile) {
File file = new File(pathFile);
return new Date(file.lastModified());
}
private void initAdsFull() {
mInterstitialAd = new InterstitialAd(this);
MobileAds.initialize(this,
getResources().getString(R.string.mobile_id));
mInterstitialAd.setAdUnitId(getResources().getString(R.string.ads_full));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
finish();
}
});
}
public long getTimeVideo(String pathFile) {
try {
MediaPlayer mp = MediaPlayer.create(this, Uri.parse(pathFile));
int duration = mp.getDuration();
mp.release();
return duration;
} catch (Exception e) {
return 0;
}
}
}
public class DownloadVideoAsyn extends AsyncTask<String, Integer, String> {
private String title;
private int check;
private NotificationCompat.Builder builder;
private NotificationManager manager;
private String CHANNEL_ID = "download_video_tiktok_auto";
private String pathVideo = title + ".mp3";
private int id = 1232;
private Context mContext;
private NotificationChannel mChannel;
Notification noti;
public DownloadVideoAsyn(String title, int check, Context context) {
this.title = title;
this.check = check;
this.mContext = context;
}
public static final String PATH = Environment.getExternalStorageDirectory().toString() + "/FreeMusic/";
private EventDownloadVideoCallBack callBack;
public void setCallBack(EventDownloadVideoCallBack callBack) {
this.callBack = callBack;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (check == 2) {
manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(mContext, CHANNEL_ID);
Intent iCancel = new Intent();
id = id + 1;
iCancel.putExtra("id", id);
iCancel.putExtra("pathVideo", pathVideo);
iCancel.setAction("CANCEL_ACTION");
PendingIntent PICancel = PendingIntent.getBroadcast(mContext, 0, iCancel, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setSmallIcon(R.drawable.ic_download)
.setContentTitle(title.replace("'", "") + ".mp3")
.setContentText(mContext.getString(R.string.download))
.setChannelId(CHANNEL_ID)
.setPriority(Notification.PRIORITY_MAX)
.addAction(R.drawable.ic_cancel, "Cancel", PICancel)
.setAutoCancel(true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
mChannel = new NotificationChannel(CHANNEL_ID, "channel-name", importance);
mChannel.setSound(null, null);
manager.createNotificationChannel(mChannel);
}
}
}
#Override
protected String doInBackground(String... strings) {
String link = strings[0];
try {
URL url = new URL(link);
// check folder exist
File folder = new File(PATH);
if (!folder.exists()) {
folder.mkdir();
}
String path = PATH + title.replace("'", "") + ".mp3";
File file = new File(path);
long total = 0;
FileOutputStream fileOutputStream = new FileOutputStream(file);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
int fileLength = connection.getContentLength();
//=============================
byte[] b = new byte[1024];
int count = inputStream.read(b);
while (count != -1) {
total += count;
fileOutputStream.write(b, 0, count);
count = inputStream.read(b);
int progress = (int) (total * 100 / fileLength);
publishProgress(progress);
if (check == 2) {
builder.setProgress(100, progress, false);
builder.setContentText(mContext.getString(R.string.download) + " " + progress + "%");
noti = builder.build();
noti.flags = Notification.FLAG_ONLY_ALERT_ONCE;
manager.notify(id, noti);
if (progress == 100) {
manager.cancel(id);
}
}
}
inputStream.close();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
try {
URL url = new URL(link);
// check folder exist
File folder = new File(PATH);
if (!folder.exists()) {
folder.mkdir();
}
Date currentTime = Calendar.getInstance().getTime();
title = currentTime.getTime() + "";
String path = PATH + title + ".mp3";
File file = new File(path);
long total = 0;
FileOutputStream fileOutputStream = new FileOutputStream(file);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
int fileLength = connection.getContentLength();
//=============================
byte[] b = new byte[1024];
int count = inputStream.read(b);
while (count != -1) {
total += count;
fileOutputStream.write(b, 0, count);
count = inputStream.read(b);
int progress = (int) (total * 100 / fileLength);
publishProgress(progress);
if (check == 2) {
builder.setProgress(100, progress, false);
builder.setContentText(mContext.getString(R.string.download) + " " + progress + "%");
noti = builder.build();
noti.flags = Notification.FLAG_ONLY_ALERT_ONCE;
manager.notify(id, noti);
if (progress == 100) {
manager.cancel(id);
}
}
}
inputStream.close();
fileOutputStream.close();
} catch (Exception ex) {
return null;
}
}
return PATH + title + ".mp3";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
Uri uri = Uri.parse("file://" + "/storage/emulated/0/FreeMusic/" + s);
Intent scanFileIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
mContext.sendBroadcast(scanFileIntent);
callBack.downloadVideoFinish(s);
}
else {
callBack.downloadVideoFail("Error");
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (check == 1) {
if (callBack != null) {
callBack.updateProgress(values[0]);
}
}
}
public interface EventDownloadVideoCallBack {
void downloadVideoFinish(String s);
void updateProgress(int pro);
void downloadVideoFail(String fail);
}
}

Unable to pick file on Oreo

On Android Nougat and below, I can simply get some file on my storage using this code :
Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("*/*.jpg");
chooseFile = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(chooseFile, 111);
And get the file path using :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 111 && resultCode == RESULT_OK && data.getData() != null)
String path = data.getData().getPath();
}
But on Android Oreo, this is not working. The file picker is showing up, but I cannot even pick the file using the default file picker. At first, I thought that this is related to permission. But after I add the permission to READ and WRITE external storage on runtime, and granted, this problem still occurred.
Since the default file picker on OREO is troublesome, currently I'm using a custom class to pick file or directory. Another solution is you can use ES File Explorer, etc, but not all of your user has it and the main problem still occurred.
public class FileChooser {
private Activity activity;
private Item[] fileList;
private File path;
private boolean rootDir = true; //check if the current directory is rootDir
private boolean pickFile = true; //flag to get directory or file
private String title = "";
private String upTitle = "Up";
private String positiveTitle = "Choose Path";
private String negativeTitle = "Cancel";
private ListAdapter adapter;
private ArrayList<String> str = new ArrayList<>(); //Stores names of traversed directories, to detect rootDir
private Listener listener;
/**
* #param pickFile true for file picker and false for directory picker
* */
public FileChooser(Activity activity, boolean pickFile, Listener fileChooserListener) {
this.activity = activity;
this.pickFile = pickFile;
this.listener = fileChooserListener;
title = pickFile ? "Choose File" : "Choose Directory";
path = new File(String.valueOf(Environment.getExternalStorageDirectory()));
}
/**
* The view of your file picker
* */
public void openDirectory() {
loadFileList();
AlertDialog.Builder builder = new AlertDialog.Builder(activity, AlertDialog.THEME_DEVICE_DEFAULT_DARK);
if (fileList == null)
builder.create();
builder.setTitle(title + "\n" + path.toString());
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int position) {
String chosenFile = fileList[position].file;
File selectedFile = new File(path + File.separator + chosenFile);
if (selectedFile.isDirectory()) { // user click on folder
rootDir = false;
str.add(chosenFile); // Adds chosen directory to list
path = selectedFile;
openDirectory();
}
else if (chosenFile.equalsIgnoreCase(upTitle) && !selectedFile.exists()) { // 'up' was clicked
String s = str.remove(str.size() - 1); // present directory
path = new File(
path.toString().substring(0, path.toString().lastIndexOf(s))); // exclude present directory
if (str.isEmpty()) // no more directories in the list, rootDir
rootDir = true;
openDirectory();
}
else if (listener != null && pickFile)
listener.onSelectedPath(selectedFile.getAbsolutePath());
}
});
if (!pickFile) {
builder.setPositiveButton(positiveTitle, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (listener != null)
listener.onSelectedPath(path.getPath());
}
});
}
builder.setNegativeButton(negativeTitle, null);
builder.show();
}
/**
* Setup your file picker data
* */
private void loadFileList() {
fileList = null;
if (path.exists()) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File file = new File(dir, filename);
// Filters based on whether the file is hidden or not
return ((pickFile && file.isFile()) || file.isDirectory()) && !file.isHidden();
}
};
String[] fList = path.list(filter); //set filter
if (fList != null) {
fileList = new Item[fList.length];
for (int i = 0; i < fList.length; i++)
fileList[i] = new Item(fList[i], new File(path, fList[i]).isDirectory() ?
R.drawable.ic_folder : R.drawable.ic_file); //set icon, directory or file
if (!rootDir) {
Item temp[] = new Item[fileList.length + 1];
System.arraycopy(fileList, 0, temp, 1, fileList.length);
temp[0] = new Item(upTitle, R.drawable.ic_undo);
fileList = temp;
}
}
} else
path = new File(String.valueOf(Environment.getExternalStorageDirectory()));
try {
adapter = new ArrayAdapter<Item>(activity,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = view.findViewById(android.R.id.text1);
textView.setTextColor(Color.WHITE);
// 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 * activity.getResources().getDisplayMetrics().density + 0.5f);
textView.setCompoundDrawablePadding(dp5);
return view;
}
};
} catch (Exception e) {
e.printStackTrace();
}
}
private class Item {
public String file;
public int icon;
private Item(String file, Integer icon) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}
public interface Listener {
void onSelectedPath(String path);
}
}

Show pic cover pdf in Listview

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";

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.

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;
}
}

Categories

Resources