Getting Media Title from a File - java

I used import java.io.File; to import all music files from my sdcard,
Now i want the Title's of the files using Mediastore but how do I do that?
This is the code I Use now.
public class ListFiles extends ListActivity {
private List<String> directoryEntries = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getIntent();
File directory = new File(i.getStringExtra("directory"));
if (directory.isDirectory()){
File[] files = directory.listFiles();
Arrays.sort(files, new Comparator<File>(){
public int compare(File f1, File f2) {
return -Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
}
});
this.directoryEntries.clear();
for (File file : files) {
this.directoryEntries.add(file.getName());
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,R.layout.file_row, this.directoryEntries);
this.setListAdapter(directoryList);
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
File clickedFile = new File(this.directoryEntries.get(position));
Intent i = getIntent();
i.putExtra("clickedFile", clickedFile.toString());
setResult(RESULT_OK, i);
finish();
}
}
Thanks.

I have done that for Video files using MediaStore : Class Overview - The Media provider contains meta data for all available media on both internal and external storage devices.
You can refer these two example to understand the use of MediaStore
List Video and List Audio

Related

Load a txt file -> open failed: ENOENT (No such file or directory). I'm pretty sure the problem is not the path, but i can't find the mistake

I'm trying to load a file and save what's wrote in it but I always get "open failed: ENOENT". The file is in the same folder of java files. Rest of code works nice, and if I run separately also the method read().
public class MainActivity extends AppCompatActivity {
ListView list;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(this, Second_activity.class);
list = (ListView) findViewById(R.id.listView);
System.out.println(read());
String [] dati = {};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dati);
list.setAdapter(adapter);
list.setOnItemClickListener(listener);
}
private AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
String itemValue = (String) list.getItemAtPosition(position);
intent.putExtra("listValue", itemValue);
startActivity(intent);
}
};
public String read(){
String data = null;
try {
File myObj = new File("com/example/myapplication2/calendario.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
data = myReader.nextLine();
}
myReader.close();
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return data;
}
}
Your file is on your android studio project path, and then you need put it in the right place raw folder, second get it the right way. File("....") is for file in device path.
Get Started.
You need move your file to resource/raw folder, for create this folder just right click on res folder, select New> Directory, then studio will open a dialog box and it will ask you to enter the name.
and write “raw” and click OK. Open res folder and you will find your raw folder under it.
Then you can put your files like .txt, .mp3 in this folder, and to get one you can use this code or similar.
InputStreamReader inputStream = new InputStreamReader(getResources().openRawResource(R.raw.calendario))
BufferedReader reader = new BufferedReader();
String line = reader.readLine();
while (line != null) { ... }

App crashes when trying to create a list of files from a directory

[I'm new here]
Hi, I'm trying to create a voice recorder app. I've already figured out how to record audio and play audio. Right now, I just want my app to display a list of all the files contained in a specific directory (for instance, "/Documents/MyApp"). So I can see the file I've just created. For now, I'm just trying to list any file coming from the external storage. The problem is, the app crashes on startup. When I remove the lines about reading external storage, it works perfectly.
I've tried a lot of differents methods online, all pretty similar. But they all leads to the same result : The app crashes on startup. Here's the code:
public class FileAndDirectoryActivity extends AppCompatActivity {
private ArrayList<String> mNames = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_and_directory);
File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
File[] arrayFiles = directory.listFiles();
for (File file : arrayFiles){
mNames.add(file.getName());
}
initRecyclerView();
}
private void initRecyclerView() {
RecyclerView recyclerView = findViewById(R.id.recyclerview);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(mNames, this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
I expect the app to list, with the recycler view, the names of all the files contained in a directory. For that, I've created an arrayList called "mNames" getting all the names of the files before getting sent to my RecyclerViewAdapter. But the app crashes on startup...
Your app is probably crashing because it can't complete onCreate (which MUST complete per the Activity lifecycle) because you are not requesting permissions to view the storage.
You need to surround your code with a check that sees if the user has permission to user external storage. You also need to handle cases where the user does not grant permission. More documentation is here. Your code should be modified to look like this:
public class FileAndDirectoryActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST = 1000;
private ArrayList<String> mNames = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_and_directory);
//Check if we have the permission to read storage
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//We dont have the permission, so request it.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
PERMISSION_REQUEST);
}
//We already have permission
else{
permissionExists();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PERMISSION_REQUEST){
if(resultCode == RESULT_OK){
permissionExists();
}
else{
//handle error
}
}
}
private void initRecyclerView() {
RecyclerView recyclerView = findViewById(R.id.recyclerview);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(mNames, this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
private void permissionExists(){
File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
File[] arrayFiles = directory.listFiles();
for (File file : arrayFiles) {
mNames.add(file.getName());
}
initRecyclerView();
}
}
Change your constructor like this ;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_and_directory);
File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
File[] arrayFiles = directory.listFiles();
for (File file : arrayFiles){
mNames.add(file.getName());
}
mNames = arrayFiles== null
? new ArrayList<File>()
: new ArrayList<File>(Arrays.asList(arrayFiles));
initRecyclerView();
}
I'm not sure about that it is going to solve your problem. Because we need to see logcat firstly. If your permissions are ok to see files, you need to initialize your ArrayList like this. I think this is your main problem. Hope this helps

Android: Get integer value of images in SD storage?

I'm looking to add images from my SD card storage into an Interger array list.
At the moment I can display images from my drawable folder because they are (somehow) in int format, for example: Log.d("MyTag", R.drawable.ic_launcher_background)); currently returns me 2131230825.
I can access my SD card images in a way to return me: /storage/emulated/0/Android/data/com.hangr.hangr/files/Pictures/Hangr_20181119__153130.jpg (String format). And I can also make bitmaps out of them with "Bitmap myBitmap = BitmapFactory.decodeFile(f.get(i));" (Bitmap format).
Any idea on how I can pass these string/bitmap forms into an int object?
package com.myapp.myapp;
imports ...
public class test extends Activity {
public ArrayList<Integer> mThumbIds = new ArrayList<>();
File[] listFile;
ArrayList<String> f = new ArrayList<String>();// list of file paths
ArrayList<Bitmap> myBitmapArrayList = new ArrayList<Bitmap>();// list of bitmaps
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
getFromSdcard();
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
// Test: adding drawable items to my interger list
mThumbIds.add(R.drawable.logo);
}
//************** important function that calls from my SD card
public void getFromSdcard(){
File file = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if (file.isDirectory()) {
listFile = file.listFiles();
for (int i = 0; i < listFile.length; i++)
{
f.add(listFile[i].getAbsolutePath());
Bitmap myBitmap = BitmapFactory.decodeFile(f.get(i));
fml.add(myBitmap);
}
}
//************** TESTING THE VALUE OF MY VARIABLES
Log.d("MyTag", "File file " + file); ///storage/emulated/0/Android/data/com.myapp.myapp/files/Pictures
Log.d("MyTag", "File length " + file.isDirectory()); //true
Log.d("MyTag", "First element in f: " + f.get(0)); ///storage/emulated/0/Android/data/com.myapp.myapp/files/Pictures/20181119__153130.jpg
Log.d("MyTag", "All the Bitmaps? " + myBitmapArrayList); //returns huge list of bitmaps, i.e. android.graphics.Bitmap#39bd71a
Log.d("MyTag", "Drawables? " + (R.drawable.ic_launcher_background)); //returns me 2131230825
}
public class ImageAdapter extends BaseAdapter {
//************** code to zoom in on images, from https://www.androidbegin.com/tutorial/android-gridview-zoom-images-animation-tutorial/
public View getView(final int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds.get(position));
// imageView.setImageListener(bottoms_Listener);
imageView.setTag(mThumbIds.get(position));
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
int id = (Integer) arg0.getTag();
zoomImageFromThumb(arg0, id);
}
});
return imageView;
}
private void zoomImageFromThumb...
}
Before you get mad at me for not "trying", I have. The hardest part was pulling from the device storage and accessing the photos in there. I just dont get why drawable images are ints and why there's no seemingly straightforward way I can turn my images into ints for similar use.
You can't get their integer references, because they don't have any.
R.whatever (R.drawable, R.string, R.xml, etc) are classes generated by Android Studio that hold integer fields whose names correspond to your resources. When you use something like getDrawable(), Android uses the integer you passed to find the corresponding resource and load it as an image. This is all done because the resources are compiled and stored in the APK itself, and aren't accessible with paths.
However, images on internal storage or your SD card aren't resources. They have directly accessible paths, and aren't inside any APKs. Android doesn't give them integers IDs because they don't need them, and it's just not how it works.
To get images from storage, you need to use paths.

Eclipse Video Intent video

I'm quite new to this, I have checked for an answer at the forums here but I didn't find any answer that can really help me out. I'm trying to play a video from the res/raw folder. I have set up this code so far:
MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videoview);
ListView l1 = (ListView) findViewById(R.id.listview);
l1.setAdapter(new EfficientAdapter(this));
l1.setOnItemClickListener(new OnItemClickListener() {
//Starts up a new activity, based on what listitem you press.
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Intent intent = new Intent(VideoButtonActivity.this, com.example.norskattrack.VideoActivity.class);
if(position==0){
System.out.println("Item 0");
intent.putExtra("video", 1);
startActivity(intent);
}
if(position==1){
System.out.println("Item 1");
intent.putExtra("video", 2);
startActivity(intent);
}
}
});
}
Uri video = Uri.parse("android.resource://com.package.app/raw/videoname");
That should let you play the video from the raw folder !
have a look at :
How to play videos in android from assets folder or raw folder?
Play Video From Raw Folder
Trying to play video from raw folder (VideoView)
All have excellent answers !

Reading a text file dynamically on user selection in Android

I am building an android application that reads text files.
Now,i have multiple text files in the sdcard .
Location of files is /sdcard/textfile/
filenames: abc.txt
def.txt
ghi.txt
i want that when users select any one of the file,the selected file should be read.
i know the code to read a single file
i.e
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,pathtofile);
BufferedReader br = new BufferedReader(new FileReader(file));
pathtofile stores the path to file abc.txt that is defined .
Is there any way i can pass the filepath to file object for the file that user selected
currently,it works for abc.txt as i have defined its path in pathtofile
You can also make a list of all the items in your textfile folder and save it in a list where the user can choose from.
public class DirectoryBrowser extends ListActivity {
private List<String> items = null;
private File currentDirectory;
private ArrayAdapter<String> fileList;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
currentDirectory = new File("/sdcard/textfile");
getFiles(currentDirectory.listFiles());
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
int selectedRow = (int)id;
currentDirectory = new File(items.get(selectedRow));
if(currentDirectory.isDirectory()){
getFiles(currentDirectory.listFiles());
}else{
//if the selected file is not a directory. get the filename
currentDirectory.getPath();
}
}
private void getFiles(File[] files){
items = new ArrayList<String>();
for(File file : files){
items.add(file.getPath());
}
fileList = new ArrayAdapter<String>(this,R.layout.list_text, items);
setListAdapter(fileList);
}
}
You can use a AlertDialog with a list.
final CharSequence[] items = {"abc.txt", "def.txt", "ghi.txt"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a file");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,items[item]);
BufferedReader br = new BufferedReader(new FileReader(file));
}
});
AlertDialog alert = builder.create();

Categories

Resources