How to rename audio file which is in sd card programmatically? - android

Here is my code to display all music file names in a list view ,here i am taking all files in an array list then displaying in a listview,by using contextmenu performing "rename" on listitems but these changes are not effecting actual file which is in sd card ,suggest me how to do this ,i tried file operations like this.
path = "/sdcard/";
if (getIntent().hasExtra("path")) {
path = getIntent().getStringExtra("path");
}
setTitle(path);
// Read all files sorted into the values-array
values = new ArrayList();
File dir = new File(path);
if (!dir.canRead()) {
setTitle(getTitle() + " (inaccessible)");
}
final String[] list = dir.list();
if (list != null) {
for (String file : list) {
if (file.contains(".3gp")) {
values.add(file);
}
}
}
Collections.sort(values);
// Put the data into the list
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_2,
android.R.id.text1, values);
setListAdapter(adapter);
registerForContextMenu(myList);
}
final int CONTEXT_MENU_DELETE = 1;
final int CONTEXT_MENU_RENAME = 2;
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, CONTEXT_MENU_DELETE, Menu.NONE, "silmek");
menu.add(Menu.NONE, CONTEXT_MENU_RENAME, Menu.NONE, "adını değiştirmek");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
.getMenuInfo();
Long id = myList.getAdapter().getItemId(info.position);
final int number_of_item_in_listview = Integer.valueOf(id.intValue());
final int context_menu_number = item.getItemId();
switch (item.getItemId()) {
This is how i am renaming file prgrammatically using contextmenu for listview
case CONTEXT_MENU_RENAME:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("öğeyi yeniden adlandırmak");
alert.setMessage("Seçili öğe için yeni bir isim girin");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("tamam",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String value = input.getText().toString();
values.set(number_of_item_in_listview, value
+ ".3gp");
adapter.notifyDataSetChanged();
/*
* File sdcard =
* Environment.getExternalStorageDirectory(); File
* from = new File(sdcard,"from.txt"); File to = new
* File(sdcard,"to.txt"); from.renameTo(to);
*/
File f = new File(path + filename);
if (f != null && f.exists()) {
File from = new File(f, f.getName());
File to = new File(f, value);
from.renameTo(to);
}
}
});
alert.setNegativeButton("iptal",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
alert.show();
return (true);
}
return (super.onOptionsItemSelected(item));

I would recommend using File.renameTo() rather than running the mv command, since I'm fairly sure the latter isn't supported..
Have you given your application permission to write to the SD Card?
You do this by adding the following to your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If it doesn't work once the permission is added check the device log for errors when you try to rename the file (either using the adb command or in the logcat view in Eclipse).
When accessing the SD Card you shouldn't hard-code the path but instead use the Environment.getExternalStorageDirectory() method to get the directory.
The following code works for me:
File sdcard = Environment.getExternalStorageDirectory();
File from = new File(sdcard,"from.txt");
File to = new File(sdcard,"to.txt");
from.renameTo(to);

Related

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

Rename/Delete audio file from gallery in android programatically

Listed all audio files from gallery ,This is my code to rename and delete list of audio files.By using this code i can able to perform rename and delete operations on list only those are not effecting audio file,How to perform rename and delete operations on audio file in gallery based on my code ,i tried like this by using Filebut didn't work,id there any wrong in my code ,correct me plz
here is my code
Variables
ListView myList;
List values;
ArrayAdapter adapter;
MediaPlayerActivity mp = new MediaPlayerActivity();
Code to rename and delete by using contextmenu
case CONTEXT_MENU_DELETE:
Toast.makeText(
this,
"You selected item " + context_menu_number
+ " from the context menu", Toast.LENGTH_SHORT)
.show();
Toast.makeText(
this,
"You removed item " + number_of_item_in_listview
+ " from the list", Toast.LENGTH_SHORT).show();
values.remove(number_of_item_in_listview);
// myadapter.notifyDataSetChanged(); //if this does not work,
// reinitialize the adapter:
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
values);
myList.setAdapter(adapter);
File f = new File(path + filename);
if (f != null && f.exists()) {
// delete it
f.delete();
}
return (true);
case CONTEXT_MENU_RENAME:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("öğeyi yeniden adlandırmak");
alert.setMessage("Seçili öğe için yeni bir isim girin");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("tamam",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String value = input.getText().toString();
values.set(number_of_item_in_listview, value
+ ".3gp");
adapter.notifyDataSetChanged();
/*
* File sdcard =
* Environment.getExternalStorageDirectory(); File
* from = new File(sdcard,"from.txt"); File to = new
* File(sdcard,"to.txt"); from.renameTo(to);
*/
File f = new File(path + filename);
if (f != null && f.exists()) {
File from = new File(f, f.getName());
File to = new File(f, value);
from.renameTo(to);
}
}
});
alert.setNegativeButton("iptal",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
alert.show();
return (true);
}
return (super.onOptionsItemSelected(item));
}
Rename the files:
Its working fine:Put this code where you want to change the name.
File sdcard = new File(Environment.getExternalStorageDirectory(), "sample");
String fromFullPath = "/username556596268.mp3";
String toFullPath = "/username.mp3";
File from = new File(sdcard,fromFullPath);
File to = new File(sdcard,toFullPath);
from.renameTo(to);
here "sample" is my sdcard main directory name,"fromFullPath" is my filename it is in inside the sample directory, "toFullPath" is my changed name.
Delete the files:
Its working fine:Put this code where you want to delete file.
File sdcard = new File(Environment.getExternalStorageDirectory(), "sample");
String fromFullPath = "/username556596268.mp3";
File from = new File(sdcard,fromFullPath);
from.delete();
from.deleteOnExit();

Android - Configurable directory?

One of the steps in building my app is to let the user select a folder in which some files are stored. How can i make this configurable, without hardcoding the directory. Is there any 3rd party library that i can use to do this ?
#Vikram's link provides a dialog that you can use. You can then save the directory the user chose using Shared Preferences.
Here is a simple example on how to use Shared Preferences.
Another tutorial can be found here.
UPDATE: A switch suddenly turned on inside me to do something like this. Credits still go to schwiz in this answer for the base code used. :)
//global variables
private File[] fileList;
private String[] filenameList;
private File[] loadFileList(String directory) {
File path = new File(directory);
if(path.exists()) {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
//add some filters here, for now return true to see all files
//File file = new File(dir, filename);
//return filename.contains(".txt") || file.isDirectory();
return true;
}
};
//if null return an empty array instead
File[] list = path.listFiles(filter);
return list == null ? new File[0] : list;
} else {
return new File[0];
}
}
public void showFileListDialog(final String directory, final Context context) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(context);
File[] tempFileList = loadFileList(directory);
//if directory is root, no need to up one directory
if(directory.equals("/")) {
fileList = new File[tempFileList.length];
filenameList = new String[tempFileList.length];
//iterate over tempFileList
for(int i = 0; i < tempFileList.length; i++) {
fileList[i] = tempFileList[i];
filenameList[i] = tempFileList[i].getName();
}
} else {
fileList = new File[tempFileList.length+1];
filenameList = new String[tempFileList.length+1];
//add an "up" option as first item
fileList[0] = new File(upOneDirectory(directory));
filenameList[0] = "..";
//iterate over tempFileList
for(int i = 0; i < tempFileList.length; i++) {
fileList[i+1] = tempFileList[i];
filenameList[i+1] = tempFileList[i].getName();
}
}
builder.setTitle("Choose your file: " + directory);
builder.setItems(filenameList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
File chosenFile = fileList[which];
if(chosenFile.isDirectory()) {
showFileListDialog(chosenFile.getAbsolutePath(), context);
}
}
});
builder.setNegativeButton("Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
public String upOneDirectory(String directory) {
String[] dirs = directory.split(File.separator);
StringBuilder stringBuilder = new StringBuilder("");
for(int i = 0; i < dirs.length-1; i++) {
stringBuilder.append(dirs[i]).append(File.separator);
}
return stringBuilder.toString();
}
The code above acts like a mini file explorer that lists the files and folders of the Android File System. You use it like:
showFileListDialog(Environment.getExternalStorageDirectory().toString(),
MainActivity.this);
Answering your question:
Add global key variables
//package name goes here.
public static final String PACKAGE_NAME = "com.example.app";
public static final String KEY_DIRECTORY_SELECTED =
PACKAGE_NAME + ".DIRECTORY_SELECTED";
private SharedPreferences prefs;
initialize your SharedPreferences somewhere on onCreate before you use it:
prefs = getSharedPreferences(PACKAGE_NAME, Context.MODE_PRIVATE);
and then you can add a positive button to the dialog
builder.setPositiveButton("Save Directory", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
prefs.edit().putString(KEY_DIRECTORY_SELECTED, directory).commit();
}
});
In your activity, instead of using the SDCard default directory you can
//if no saved directory yet, use SDCard directory as default
String oldChosenDirectory = prefs.getString(KEY_DIRECTORY_SELECTED,
Environment.getExternalStorageDirectory().toString());
showFileListDialog(oldChosenDirectory, MainActivity.this);
As Vikram pointed out. you also need to do this in your FileNameFilter so that the dialog will display directories ONLY.
Update: As noted in this SO answer, the parameters dir and filename does not refer to the same file. The dir parameter is the directory containing the file, while filename is the filename of the file itself. To determine whether the filte itself is a directory, we need to create a new file from the parameters like so:
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
File file = new File(dir.getAbsolutePath() + File.separator + filename);
return file.isDirectory();
}
};

Null pointer exception trying to remove from listview

I get a null pointer exception in the deleteIt method in the filelist.notifyDataSetChanged();
I need some help trying to remove the file, please be kind. It took me a couple of hours how to add the longclick method. This could could be used by someone but I need to help with the removing item from list.
public class AndroidExplorer extends ListActivity
{
private List<String> item = null;
private List<String> path = null;
private TextView myPath;
ArrayAdapter filelist = null;
File myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/GV-Skynet");
String root2 = myFile.getAbsolutePath();;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myPath = (TextView)findViewById(R.id.path);
getDir(root2);
ListView list = getListView();
list.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id)
{
File file = new File(path.get(position));
deleteIt("Do you want to Delete", file.getName(), file );
return true;
}
});
}
private void showToast(String msg)
{
Toast error = Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG);
error.show();
}
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(root2))
{
item.add("Return to GV-Skynet Directory");
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.row, item);
setListAdapter(fileList);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
File file = new File(path.get(position));
if (file.isDirectory())
{
if(file.canRead())
getDir(path.get(position));
else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
else
{
String fileName = file.getName();
String fname="";
String ext="";
int mid= fileName.lastIndexOf(".");
fname=fileName.substring(0,mid);
ext=fileName.substring(mid+1,fileName.length());
if(ext.equals("jpg"))
{
Intent intent = new Intent("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromFile(file);
intent.setDataAndType (uri, "image/*");
this.startActivity(intent);
}
if(ext.equals("3gp"))
{
Intent intent = new Intent("android.intent.action.VIEW");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra ("oneshot", 0);
intent.putExtra ("configchange", 0);
Uri uri = Uri.fromFile(file);
intent.setDataAndType (uri, "video/*");
this.startActivity(intent);
}
}
}
public void deleteIt( String title, String name, File file )
{
final String name1 = name;
final File tmFile = file;
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(name1)
.setPositiveButton("YES", new DialogInterface.OnClickListener() // OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//item = new ArrayList<String>();
item.remove(tmFile.getName()); // remove the item
filelist.notifyDataSetChanged(); // let the adapter know to update
showToast("File Deleted: " + tmFile.getName() );
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() // OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1) {
// do stuff onclick of CANCEL
showToast("CANCELLING DELETE");
}
}).show();
}
}
just try this change your statement
ArrayAdapter filelist = null;
with
ArrayAdapter<String> filelist = null;
and also you are re-declaring filelist in your getDir method so change it to
filelist = new ArrayAdapter<String>(this,R.layout.row, item);
setListAdapter(filelist);
onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
File file = new File(path.get(position));
if (file.exists()) {
deleteIt("Do you want to Delete", file.getName(), file);
} else {
Toast.makeText(this, "File not Exist", Toast.LENGTH_SHORT).show();
}
}

Android - getting back to menu from filepicker/browsing screen

I found this file picker online, which the developer said that people could use if they wanted to.
Since I thought the code was easy to understand - I decided to use it and change it a bit for my application.
All credit goes to the original developer (https://github.com/mburman/Android-File-Explore)
loadFileList();
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
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() {
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.drawable.file_icon);
// Convert into file path
File sel = new File(path, fList[i]);
// Set drawables
if (sel.isDirectory()) {
fileList[i].icon = R.drawable.directory_icon;
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.directory_up);
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 = (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;
}
};
}
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;
}
}
#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("Choose your file");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
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 {
chosenFile = fileList[which].file;
File test = new File(path + "/" + chosenFile);
sendback(test);
}
}
});
break;
}
dialog = builder.show();
return dialog;
}
Sorry, if it's a bit too long. But that's the entire file picker which is in the onCreate().
I open it by using this code:
Bundle b = new Bundle();
b.putInt("tallet", 1);
Intent i = new Intent(getApplicationContext(), FileExplore.class);
i.putExtras(b);
startActivityForResult(i, 0);
The code works perfectly. But when I press "back" (onBackPressed), it gives me blank (black) screen if I say finish(); .
Right now I'm using this code:
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent backIntent = new Intent(FileExplore.this, AndroidTabLayoutActivity.class);
startActivity(backIntent);
}
Which actually works, but it gives me black screen if I press back once, and then the menu, when I hit the back button again. EDIT: it goes INTO the onBackPressed code on second back-press, not the first.
Here's my onActivityResult code in PhotosActivity (it's a tablayout - photosactivity is just one of the screens):
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
// Bundle b = getIntent().getExtras();
if (resultCode == -1)
{
Bundle b = data.getBundleExtra("FiletoPhoto");
int knappen = b.getInt("number");
String titlen = b.getString("title");
{
Listofsounds los = new Listofsounds();
String shortname = los.puttextonit(titlen, knappen);
putnameinit(shortname,knappen);
}
}
else if (resultCode == 0)
{
//If I press "back" i've made the resultCode to be 0 in the onBackPressed. What should I do here then?
}
}
What should I do so I could just press it once and get back to the menu?
The issue is that when you use this code:
Intent backIntent = new Intent(FileExplore.this, AndroidTabLayoutActivity.class);
startActivity(backIntent);
You are basically creating and starting a new activity of AndroidTabLayoutActivity which already exists, so now there will be two copies of this activity running simultaneously. However, the original activity will be expecting a result as you've called startActivityForResult(). I think the solution to your problem is probably to do a check if the resultCode you are getting back as a onActivityResult is RESULT_OK or whatever successful resultCode you are setting in setResult(...) in FileExplore.
This is really strange because in all of my apps I don't override onBackPressed and yet, I am able to finish the activity without causing any weird side effects.

Categories

Resources