APK works on Samsung but in Nexus giving 2 errors? - android

In my app, first a create a NewFolder, and then i record audios and save them inside this new folder. I also have a ArrayList to show my RecordsHere I create the NewFolder
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
String sep = File.separator; // Use this instead of hardcoding the "/"
String newFolder = "FolderName";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(extStorageDirectory + sep + newFolder);
//myNewFolder.mkdir();
myNewFolder.mkdirs();
while (fs.getfetchstatus() != true) {
mySongs = fs.findSongs(Environment.getExternalStorageDirectory());
//>>>>>>>>>>HERE IS HAVING ANY ERROR<<<<<<<<<
}
if (mySongs != null) {
dialog.dismiss();
}
mySongs = fs.getsonglist();
items = new String[mySongs.size()];
for (int i = 0; i < mySongs.size(); i++) {
items[i] = mySongs.get(i).getName().toString().replace(".3gp", "");
}
final ArrayAdapter<String> adp = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, items);
adp.notifyDataSetChanged();
lv.setAdapter(adp);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), Player.class);
intent.putExtra("pos", i);
adp.notifyDataSetChanged();
startActivity(intent);
finish();
}
});
here is my ArrayList
boolean fetchstatus=false;
ArrayList<File> songs=new ArrayList<File>();
String sep = File.separator; // Use this instead of hardcoding the "/"
String newFolder = "FolderName";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(extStorageDirectory + sep + newFolder);
//File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
FetchSongs(){
}
public ArrayList<File> findSongs(File root){
ArrayList<File> al=new ArrayList<File>();
// File[] files=root.listFiles();
//File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File file = new File(Environment.getExternalStorageDirectory(), newFolder);
File[] files = file.listFiles();
for (File singleFile : files){
if(singleFile.isDirectory() && !singleFile.isHidden()){
al.addAll(findSongs(singleFile));
//>>>>>>>ERROR HERE<<<<<<<<<<<<<<<<<<<
}
else {
if(singleFile.getName().endsWith(".mp3")){
al.add(singleFile);
}
}
}
fetchstatus=true;
songs=al;
return al;
}
I'm having these errors
java.lang.RuntimeException: Unable to start activity ComponentInfo
at org.usr.usr.musicplayer.FetchSongs.findSongs(FetchSongs.java:35)
at org.usr.usr.musicplayer.MainActivity.onCreate(MainActivity.java:124)

Maybe it's just this line the error
File file = new File(Environment.getExternalStorageDirectory(), newFolder);
Nexus not always has got an external storage, but to be more accurate you should check the trace error, most likely you'll be able to see the exactly lines that cause the runt time error

Related

How my ListView can show just my records?

My ListView is showing all my songs of the phone,I just want the records that i save.
How can i import my records in my ListView? My records are in a folder that i created "newFolder"
public class FetchSongs {
boolean fetchstatus=false;
ArrayList<File> songs=new ArrayList<File>();
FetchSongs(){
}
public ArrayList<File> findSongs(File root){
ArrayList<File> al=new ArrayList<File>();
File[] files=root.listFiles();
for (File singleFile : files){
if(singleFile.isDirectory() && !singleFile.isHidden()){
al.addAll(findSongs(singleFile));
}
else {
if(singleFile.getName().endsWith(".mp3")){
al.add(singleFile);
}
}
}
fetchstatus=true;
songs=al;
return al;
}
public boolean getfetchstatus(){
return fetchstatus;
}
public ArrayList<File> getsonglist(){
return songs;
}
}
Here I record the audio and save in this folder "newFolder"The ListView needs to show just this records.
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
String sep = File.separator; // Use this instead of hardcoding the "/"
String newFolder = "FolderName";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(extStorageDirectory + sep + newFolder);
myNewFolder.mkdir();
mFileName = Environment.getExternalStorageDirectory().toString()
+ sep + newFolder + sep + "GRAVAÇÃO-"+ts+".mp3";
You can combine getsonglist() and findSongs(File root) like so.
public class FetchSongs {
final String dir;
boolean fetchstatus;
List<File> songs=new ArrayList<File>();
FetchSongs(){
this("");
}
FetchSongs(String dir) {
this.dir = dir;
}
private List<File> getSongList(File root) {
List<File> al=new ArrayList<File>();
File[] files=root.listFiles();
for (File singleFile : files){
if(singleFile.isDirectory() && !singleFile.isHidden()){
songs.addAll(findSongs(singleFile));
}
else {
if(singleFile.getName().endsWith(".mp3")){
songs.add(singleFile);
}
}
}
}
public List<File> getSongList() {
if (songs.isEmpty()) {
File root = new File(Environment.getExternalStorageDirectory(), dir);
fetchstatus=true;
this.songs.addAll(getSongList(root));
}
return songs;
}
}
Then, you can try to make an adapter out of new FetchSongs("NewFolder").getSongList()

Displaying folders only containing files with certain file type

I have set up code to display all folders that are on the SD card but now I am trying to figure out how to only display folders which contain MP3 files.
How can I filter out the folders that don't contain .MP3 files? thanks.
class:
public class FragmentFolders extends ListFragment {
private File file;
private List<String> myList;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File(root_sd);
File list[] = file.listFiles();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
}
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, myList));
}
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
File temp_file = new File(file, myList.get(position));
if (!temp_file.isFile()) {
file = new File(file, myList.get(position));
File list[] = file.listFiles();
myList.clear();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
}
Toast.makeText(getActivity(), file.toString(), Toast.LENGTH_LONG)
.show();
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, myList));
}
return;
}
}
You can check if the files within a directory are mp3 files before adding to your list view's dataset
Modify your code as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File(root_sd);
//list content of root sd
File list[] = file.listFiles();
for (int i = 0; i < list.length; i++) {
//check the contents of each folder before adding to list
File mFile = new File(file, list[i].getName());
File dirList[] = mFile.listFiles();
if(dirList == null) continue;
for (int j = 0; j < dirList.length; j++) {
if(dirList[j].getName().toLowerCase(Locale.getDefault()).endsWith(".mp3")){
myList.add(list[i].getName());
break;
}
}
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myList));
}
I tested this and it works. Only caveat is, it doesn't check for sub-directories.
So in:
sdcard/Music/mistletoe.mp3
sdcard/Media/Tracks/mistletoe.mp3
only the Music folder will be listed.
Also, you may want to use an asyncTask to eschew hogging the UI thread
You can user a fileNameFilter and filter out the folders/files you don't want.
File baseDirectory = new File("/mnt/sdcard/"); //Your base dir here
File[] files = baseDirectory.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String fileName) {
File possibleMp3Folder = new File(dir, fileName);
if (possibleMp3Folder.isDirectory()) {
File[] files1 = possibleMp3Folder.listFiles();
for (File file : files1) {
if (file.getName().toLowerCase().endsWith(".mp3")) {
return true;
}
}
}
return false;
}
});
If you are looking for all folders contains mp3 files (both on Internal storage and SD Card) and available storages contains media:
Initialize two Sets for media storage paths and mp3 folders paths:
private HashSet<String> storageSet = new HashSet<>();
private HashSet<String> folderSet = new HashSet<>();
Get both in one method (you can return value if you need only one):
private void getMediaFolders() {
ContentResolver resolver = getContentResolver();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
String[] projection = { MediaStore.Audio.Media.DATA };
Cursor cursor = resolver.query(uri, projection, selection, null, null);
if(cursor != null && cursor.getCount() > 0) {
int dataIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
while(cursor.moveToNext()) {
String data = cursor.getString(dataIndex);
int i = 0;
for (int slashCount = 0; i < data.length(); i++) {
if (data.charAt(i) == '/' && ++slashCount == 3) {
storageSet.add(data.substring(0, i));
break;
}
}
if (data.toLowerCase().endsWith("mp3")) {
int lastSlashIndex = data.lastIndexOf('/');
while (i < lastSlashIndex) {
data = data.substring(0, lastSlashIndex);
folderSet.add(data);
lastSlashIndex = data.lastIndexOf('/');
}
}
}
}
if (cursor != null) { cursor.close(); }
}
Filter folders (with Annimonstream):
private ArrayList<File> getFilteredFolders(#NonNull String path, HashSet<String> folderSet) {
File[] filesList = new File(path).listFiles();
if (filesList == null) { return new ArrayList<>(); } // Or handle error as you wish
return Stream.of(filesList)
.filter(File::isDirectory)
.filter(f -> folderSet.contains(f.getAbsolutePath()))
.collect(Collectors.toCollection(ArrayList::new));
}
Show storages (if needed).
Uri,Projection,
MediaStore.Video.Media.DATA
+ " like " + "'%.mp4%'"
+ " AND "
+ MediaStore.Video.Media.DATA
+ " like " + "'%" + getResources().
getString(R.string.string_store_video_folder)
+"%'", null,
MediaStore.Video.Media.DATE_MODIFIED
this will give mp4 files in a specific folder

Android: how to list files from SD card

I want to list all the files on the SD card. I use a this code for it:
myList = new ArrayList();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File( "storage/" + root_sd ) ;
Log.e(myLog, file.getName());
File list[] = file.listFiles();
for( int i=0; i< list.length; i++)
{
myList.add( list[i].getName() );
Log.e(myLog, list[i].getName() + " : " + list[i].getTotalSpace());
}
And I get a nullPointerException for it after I log the name. I tried an other file also:
file = new File( root_sd ) ;
Ended with the same result.
So, how can I list the files properly? Thx for help!
...//initing the variables
String fileName = Environment.getExternalStorageDirectory().toString();
title.setText(fileName);
ArrayList<String> FilesInFolder = GetFiles(fileName);
mList.setAdapter(new ArrayAdapter<String>(getActivity() , android.R.layout.simple_list_item_1 , FilesInFolder));
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Clicking on items
}
});
and the function
public ArrayList<String> GetFiles(String DirectoryPath) {
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0)
return null;
else {
for (int i=0; i<files.length; i++)
MyFiles.add(files[i].getName());
}
return MyFiles;
}
If you want a different layout make an own ArrayAdapter

How to increase cellsize of ListView

I am using a ListView the size of each cell is very small. I thought to increase size of text so that cell size will adjust automatically. but this didnt work.
My java code is as follows:
View v= findViewById(R.id.rowtext);
myPath = (TextView)findViewById(R.id.path);
root = Environment.getExternalStorageDirectory().getPath();
getDir(root);
}
public void bt_Quit(View v)
{
finish();
}
public void back(View v)
{
getDir(pos);
}
public void home(View v)
{
getDir(root);
}
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();
pos=f.getParent();
if(!dirPath.equals(root))
{
}
for(int i=0; i < files.length; i++)
{
File file = files[i];
if(!file.isHidden() && file.canRead()){
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.row, item);
setListAdapter(fileList);
}
The cellsize of List view is too small. What i want is to know how to adjust cellsize of listView?
change in your xml of listview
android:layout_width="20dp"
android:layout_height="30dp"
Change numbers according to ur need

How to save a multidimensional JSON array to a CSV file on Android?

I want to store large JSON array data into a CSV file. How can I do this?
I have following code which do not save any data into "test1.csv" file created in my android "test" folder.
Here is the code.
JSONArray outerArray = [{"value":true,"Id":0,"name":"214"}, {"value":true,"Id":0,"name":"215"},{"value":true,"Id":0,"name":"216"}]
public void saveCsv(JSONArray outerArray) throws IOException, JSONException {
String rootPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/test/";
File dir = new File(rootPath);
if (!dir.exists()) {
dir.mkdir();
}
File file;
EditText editText = (EditText) findViewById(R.id.editText1);
if (!editText.getText().toString().equals("")) {
file = new File(rootPath, editText.getText().toString() + ".csv");
} else {
editText.setError("Defualt csv file name will be used");
Toast.makeText(this, "CSV name is empty", 5000).show();
file = new File(rootPath, "test1.csv");
}
file.createNewFile();
if (file.exists()) {
CSVWriter writer = new CSVWriter(new FileWriter(file), ',');
String[][] arrayOfArrays = new String[outerArray.length()][];
for (int i = 0; i < outerArray.length(); i++) {
JSONObject innerJsonArray = (JSONObject) outerArray.get(i);
String[] stringArray1 = new String[innerJsonArray.length()];
for (int j = 0; j < innerJsonArray.length(); j++) {
stringArray1[j] = (String) innerJsonArray.get("value");
}
arrayOfArrays[i] = stringArray1;
writer.writeNext(arrayOfArrays[i]);
}
writer.close();
}
}
I have used opencsv-2.3.jar from here http://sourceforge.net/projects/opencsv/. Documented here http://sourceforge.net/projects/opencsv/
I have following JSON with Boolean values which throws Boolean cant cast to string value
JSONArray outerArray = [{"value":true,"Id":0,"name":"214"}, {"value":true,"Id":0,"name":"215"},{"value":true,"Id":0,"name":"216"}]
i have changed json.get() to json.getString(). following code works fine now :)
public void saveCsv(JSONArray outerArray) throws IOException, JSONException {
String rootPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/test/";
File dir = new File(rootPath);
if (!dir.exists()) {
dir.mkdir();
}
File file;
EditText editText = (EditText) findViewById(R.id.editText1);
if (!editText.getText().toString().equals("")) {
file = new File(rootPath, editText.getText().toString() + ".csv");
} else {
editText.setError("Defualt csv file name will be used");
Toast.makeText(this, "CSV name is empty", 5000).show();
file = new File(rootPath, "test1.csv");
}
if(!file.exists()){
file.createNewFile();
}
if (file.exists()) {
CSVWriter writer = new CSVWriter(new FileWriter(file), ',');
String[][] arrayOfArrays = new String[outerArray.length()][];
for (int i = 0; i < outerArray.length(); i++) {
JSONObject innerJsonArray = (JSONObject) outerArray.get(i);
String[] stringArray1 = new String[innerJsonArray.length()];
stringArray1[0]= (String) innerJsonArray.getString("Id");
stringArray1[1]= (String) innerJsonArray.getString("value");
stringArray1[2]= (String) innerJsonArray.getString("name");
arrayOfArrays[i] = stringArray1;
writer.writeNext(arrayOfArrays[i]);
}
writer.close();
}
}

Categories

Resources