Question

I have a problem, I want to set a ringtone inside my main acivity, I read this tutorial: http://androidgenuine.com/?tag=set-as-ringtone-android , but function save is not working, to be more specific I can't create a file, function is returning false. I write again only a part with creating new File but even this part is not working, here is the code, what's wrong (it;s returning false and non file was created) ?

    public boolean save2(int ressound){

    String path="/sdcard/sounds/";
    String filename="ring.mp3";
    byte[] buffer = null;
    FileOutputStream save;
    InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
    int size=0;
    try {
        size=fIn.available();
        buffer = new byte[size];
        fIn.read(buffer);
        fIn.close();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        save = new FileOutputStream(path+filename);
        save.write(buffer);
        save.flush();
        save.close();
        return true;
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
}

Thanks for your help

Was it helpful?

Solution

I can only guess that directory you specified might not exist or that you do not have the appropriate permission set in your manifest.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

You should be constructing it with the following from documentation found at

http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory()

File path = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");

// Make sure the Pictures directory exists.
path.mkdirs();

You also must check if the external storage is even mounted.

String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        mExternalStorageAvailable = mExternalStorageWriteable = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        mExternalStorageAvailable = true;
        mExternalStorageWriteable = false;
    } else {
        mExternalStorageAvailable = mExternalStorageWriteable = false;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top