I have to fetch all the videos from "/SDCard/Folder/SubFolder" and display them in a GridView.
I am able to save the videos into the desired subfolder created by me and can see them directly from the folder. But I want to show them into a GridView but when I am running my code, It displays nothing but only a black blank screen. Here is my code, please tell me that what mistake I am doing here..
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview_main);
// 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()
+ File.separator + "/SDCard/Picture/MyCameraVideo");
// Create a new folder if no folder named SDImageTutorial exist
file.mkdirs();
}
if (file.isDirectory()) {
listFile = file.listFiles();
// Create a String array for FilePathStrings
FilePathStrings = new String[listFile.length];
// Create a String array for FileNameStrings
FileNameStrings = new String[listFile.length];
for (int i = 0; i < listFile.length; i++) {
// Get the path of the image file
FilePathStrings[i] = listFile[i].getAbsolutePath();
// Get the name image file
FileNameStrings[i] = listFile[i].getName();
}
}
// Locate the GridView in gridview_main.xml
grid = (GridView) findViewById(R.id.gridview);
// Pass String arrays to LazyAdapter Class
adapter = new GridViewAdapter(this, FilePathStrings, FileNameStrings);
// Set the LazyAdapter to the GridView
grid.setAdapter(adapter);
// Capture gridview item click
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(ViewActivity.this, ViewImage.class);
i.putExtra("filepath", FilePathStrings);
i.putExtra("filename", FileNameStrings);
i.putExtra("position", position);
startActivity(i);
}
});
}
}
Related
I want to add the downloads folder to my code,
this is my helper class (File Paths):
//"storage/emulated/0" = Environment.getExternalStorageDirectory().getPath().
public String ROOT_DIR = Environment.getExternalStorageDirectory().getPath();
public String PICTURES = ROOT_DIR + "/Pictures";
public String CAMERA = ROOT_DIR + "/DCIM/camera";
public String DOWNLOADS = ROOT_DIR + "/Download";
and this my class where I use this paths
private void init(){
FilePaths filePaths = new FilePaths();
//check for other folders indide "/storage/emulated/0/pictures"
if(FileSearch.getDirectoryPaths(filePaths.PICTURES) != null){
directories = FileSearch.getDirectoryPaths(filePaths.PICTURES);
}
ArrayList<String> directoryNames = new ArrayList<>();
for(int i = 0; i < directories.size(); i++){
int index = directories.get(i).lastIndexOf("/");
String string = directories.get(i).substring(index);
directoryNames.add(string);
}
directories.add(filePaths.CAMERA);
directories.add(filePaths.DOWNLOADS);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, directories); // WARUM
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
directorySpinner.setAdapter(adapter);
directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected: " + directories.get(position));
//setup image grid for the directory chosen
setupGridView(directories.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
If I cut the downloads part out, I get all the files of the other paths but if the downloads part is inside my code, I got an Exception because the downloads files arent added to the arrayList later.
I need the correct path for the downloads.
I found this:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
but this returns me a file and I need a String in my helper class.
EDIT:
Sorry, it was my fault. I got the Exception because I didnt had any pictures in my other directories. After I inserted one, my Downloads Folder was showed. I solved this error with try and catch now.
You can get String path from File like this
String path = file.toURI().toString();
I have a Gridview in my App...
The Gridview shows all the available files in a particular folder, lets say 'Sample Folder'...
What I am trying is to pass the ACTION_VIEW Intent on item click but I am not able to set its Data and Type...
Most of the files are either image or videos...
Here's the code for Activity -
public class Downloaded extends AppCompatActivity {
// Declare variables
private String[] FilePathStrings;
private String[] FileNameStrings;
private File[] listFile;
GridView grid;
GridViewAdapter adapter;
File file;
TextView empty;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
// Check for SD Card
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Toast.makeText(Downloaded.this, "Error! No SDCARD Found!", Toast.LENGTH_LONG)
.show();
} else {
// Locate the image folder in your SD Card
file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Sample");
file.mkdirs();
}
if (file.isDirectory()) {
listFile = file.listFiles();
// Create a String array for FilePathStrings
FilePathStrings = new String[listFile.length];
// Create a String array for FileNameStrings
FileNameStrings = new String[listFile.length];
for (int i = 0; i < listFile.length; i++) {
// Get the path of the image file
FilePathStrings[i] = listFile[i].getAbsolutePath();
// Get the name image file
FileNameStrings[i] = listFile[i].getName();
}
}
// Locate the GridView in gridview_main.xml
grid = (GridView) findViewById(R.id.gridview);
empty = (TextView) findViewById(R.id.empty);
empty.setText("You haven't saved any Pic yet...!");
grid.setEmptyView(empty);
// Pass String arrays to LazyAdapter Class
adapter = new GridViewAdapter(Downloaded.this, FilePathStrings, FileNameStrings);
// Set the LazyAdapter to the GridView
grid.setAdapter(adapter);
// Capture gridview item click
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(android.content.Intent.ACTION_VIEW);
//Don't Know what to Do Here :(
File n = new File(Environment.getExternalStorageDirectory()+ File.separator + "Sample/" + FileNameStrings);
i.setDataAndType(Uri.fromFile(n), "*/*");
startActivity(Intent.createChooser(i, "Choose an App"));
}
});
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()){
case android.R.id.home:
onBackPressed();
break;
}
return true;
}
}
And here's the Adapter -
public class GridViewAdapter extends BaseAdapter {
// Declare variables
private Activity activity;
String[] filepath;
String[] filename;
Context mContext;
private static LayoutInflater inflater = null;
public GridViewAdapter( Context c ) {
mContext = c ;
}
public GridViewAdapter(Activity a, String[] fpath, String[] fname) {
activity = a;
this.filepath = fpath;
filename = fname;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return this.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);
// Locate the ImageView in gridview_item.xml
ImageView img = (ImageView) vi.findViewById(R.id.image);
// Set file name to the TextView followed by the position
TextView txt = (TextView) vi.findViewById(R.id.name);
// Decode the filepath with BitmapFactory followed by the position
// Set the decoded bitmap into ImageView
Glide.with(activity)
.load(filepath[position])
.into(img);
txt.setText(filename[position]);
return vi;
}
}
Any help would be appreciated... :)
Try like this
Intent i = new Intent(android.content.Intent.ACTION_VIEW);
// No need to set both Type & Data. if you set one itself enough
File n = new File(Environment.getExternalStorageDirectory()+ File.separator + "Sample/" + FileNameStrings);
i.setType(MimeTypeMap.getFileExtensionFromUrl(n.getAbsolutePath()));
startActivity(Intent.createChooser(i, "Choose an App"));
Updated
Try this for open file
MimeTypeMap myMime = MimeTypeMap.getSingleton();
Intent newIntent = new Intent(Intent.ACTION_VIEW);
String mimeType = myMime.getMimeTypeFromExtension(fileExt(file).substring(1));
newIntent.setDataAndType(Uri.fromFile(file),mimeType);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(newIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No handler for this type of file.", Toast.LENGTH_LONG).show();
}
private String fileExt(String url) {
if (url.indexOf("?") > -1) {
url = url.substring(0, url.indexOf("?"));
}
if (url.lastIndexOf(".") == -1) {
return null;
} else {
String ext = url.substring(url.lastIndexOf(".") + 1);
if (ext.indexOf("%") > -1) {
ext = ext.substring(0, ext.indexOf("%"));
}
if (ext.indexOf("/") > -1) {
ext = ext.substring(0, ext.indexOf("/"));
}
return ext.toLowerCase();
}
}
I can get into my custom directory by this code which displays me the list of images in my directory now what i want is to open those image when i click on a image list .
private void getDir(String dirPath) {
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if (!dirPath.equals(root)) {
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for (int i = 0; i < files.length; i++) {
File file = files[i];
path.add(file.getPath());
if (file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
ArrayAdapter<String> fileList = new ArrayAdapter<String>(this, R.layout.explorernew, item);
setListAdapter(fileList);
}
File file;
#Override
protected void onListItemClick( ListView l, View v, int position, long id) {
File imgFile = new File(root+"/20150424_173923.jpg");
// TextView stxt = (TextView) findViewById(R.id.textView2);
// stxt.setText(List.get(position));
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
}
}
I have hard-code my imgfile as my image name which is displaying the image . I want to dynamically change the image on my selection
the position parameter in the protected void onListItemClick( ListView l, View v, int position, long id) {...} function shows the position of the element in your listView which is selected, so you could get the name of your selected image by String name =(String) l.getItemAtPosition(position); or you can do another thing without using the position parameter and it's to use String name = ((TextView) view).getText();
And then you could easily use the name variable in your line File imgFile = new File(root+name);
I have a grid view on onCreate I am creating a grid view getting image url the from local database But when that activity is loading it showing a white screen.
How to remove that white screen I don't know where to move this gredview.A am attachig the full code please tell me what should I do.Try to click the sync button that sync button will first clear the local database then it get all xml value from server and put that into local database after that this activity will be restarted then this onCreat method will be called and blank white screen will be shown.
CODE URL http://www.fileconvoy.com/dfl.php?id=g2561f0a6e7dcc50b9992656609078e5c6d63c814c
My code follows
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridview = (GridView) findViewById(R.id.gridview);
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
String pdfPath = Environment.getExternalStorageDirectory().toString() + "/ICA Faculty/";
Toast.makeText(getApplicationContext(),pdfPath+((TextView) v.findViewById(R.id.hiddenPdfUrl)).getText(), Toast.LENGTH_SHORT).show();
try {
File file = new File(pdfPath+((TextView) v.findViewById(R.id.hiddenPdfUrl)).getText());
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Sorry no PDF reader found.", Toast.LENGTH_SHORT).show();
}
}
});
File folder = new File(Environment.getExternalStorageDirectory() + "/ICA Faculty");
db.open();
c = db.getAllRecords();
//If data exist in local database AND "ICA Faculty" folder exist
//Getting the sd card file name from local database
if (c.moveToFirst() && folder.exists() && folder.listFiles() != null)
{
//This array list will help to create image
imgUrl = new ArrayList<String>();
pdfUrl = new ArrayList<String>();
do
imgUrl.add(c.getString(3));
pdfUrl.add(c.getString(2));
} while (c.moveToNext());
ImageAdapter adapter = new ImageAdapter(MainActivity.this);
gridview.setAdapter(adapter);
}
else
{
Toast.makeText(getApplicationContext(), "You need to sync to create your library.", Toast.LENGTH_LONG).show();
}
db.close();
}
The GridView, as subclass of AdapterView, can use an empty view to show when there is no data by the setEmptyView() method.
For examples look at this question Correct use of setEmtpyView in AdapterView
I have a gallery that is displaying thumbnail images in custom directories. The gallery displays fine, but I am unable to open the full image by clicking the thumbnail. My [non functioning] click listener is below
try {
if (LoadImageFiles() == true) {
GridView imgGallery = (GridView) findViewById(R.id.gallery);
final ImageAdapter ia = new ImageAdapter(PersonMedia.this);
imgGallery.setAdapter(ia);
// Set up a click listener
imgGallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String imgPath = paths.get(position);
Intent intent = new Intent(getApplicationContext(), ViewImage.class);
intent.putExtra("filename", imgPath);
startActivity(intent);
}
});
}
} catch (Exception ex) {
Log.e("PersonMedia.LoadPictures", ex.getMessage());
}
Here is how the gallery is populated
//Declare a module level hashtable
private Hashtable<Integer, String> paths;
private boolean LoadImageFiles() {
try{
mySDCardImages = new Vector<ImageView>();
paths = new Hashtable<Integer, String>();
fileCount = 0;
sdDir = new File(imageDirectory);
sdDir.mkdir();
if (sdDir.listFiles() != null)
{
File[] sdDirFiles = sdDir.listFiles();
if (sdDirFiles.length > 0)
{
for (File singleFile : sdDirFiles)
{
Bitmap bmap = decodeFile(singleFile);
BitmapDrawable pic = new BitmapDrawable(bmap);
ImageView myImageView = new ImageView(PersonMedia.this);
myImageView.setImageDrawable(pic);
myImageView.setId(mediaCount);
paths.put(fileCount, singleFile.getAbsolutePath());
mySDCardImages.add(myImageView);
mediaCount++;
fileCount ++;
}
}
}
}
catch(Exception ex){ Log.e("LoadImageFiles", ex.getMessage()); }
return (fileCount > 0);
}
I was able to resolve this by using a hashtable to store the position and path of the images when the thumbnails are loaded. Below are the 2 pertinent code snippets
//Where the gallery is populated and the onclick is defined
private void PopulateGallery() {
try {
if (LoadImageFiles() == true) {
GridView imgGallery = (GridView) findViewById(R.id.gallery);
imgGallery.setAdapter(new ImageAdapter(PersonMedia.this));
// Set up a click listener
imgGallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String imgPath = paths.get(position);
Intent intent = new Intent(getApplicationContext(), ViewImage.class);
intent.putExtra("filename", imgPath);
startActivity(intent);
}
});
}
} catch (Exception ex) {
Log.e("PersonMedia.LoadPictures", ex.getMessage());
}
}
//Where the images are loaded. You'll need to create a module level hashtable
private Hashtable<Integer, String> paths;
private boolean LoadImageFiles() {
try{
mySDCardImages = new Vector<ImageView>();
paths = new Hashtable<Integer, String>();
fileCount = 0;
sdDir = new File(imageDirectory);
sdDir.mkdir();
if (sdDir.listFiles() != null)
{
File[] sdDirFiles = sdDir.listFiles();
if (sdDirFiles.length > 0)
{
for (File singleFile : sdDirFiles)
{
Bitmap bmap = decodeFile(singleFile);
BitmapDrawable pic = new BitmapDrawable(bmap);
ImageView myImageView = new ImageView(PersonMedia.this);
myImageView.setImageDrawable(pic);
myImageView.setId(mediaCount);
paths.put(fileCount, singleFile.getAbsolutePath());
mySDCardImages.add(myImageView);
mediaCount++;
fileCount ++;
}
}
}
}
catch(Exception ex){ Log.e("LoadImageFiles", ex.getMessage()); }
return (fileCount > 0);
}
Do your images have extensions, such as .jpg or .png? I'm not quite sure but it looks like you are looking for an image that is string version of your personId, without any file extension.
Please correct me if I'm wrong.
Also please post more details, such as the errors you are getting.
Updated answer below.
Use View.setTag(Object), when you are adding items to your ListView (I am guessing). You can call something like the following.
view.setTag("imgFile.jpg");
And then from inside of your onClickListener, just do this:
String img = (String) getTag();