Hi I'm trying to get files in my res/raw folder of my android application to be copied onto the phone's sdcard so they can be set as ringtones. Here is what I have so far on my application:
package com.wochstudios.ringtonetest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.*;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.res.*;
import android.app.Activity;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class setRingtone extends Activity {
Button setBtn;
TextView result;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setBtn = (Button) findViewById(R.id.button1);
result = (TextView) findViewById(R.id.textView1);
setBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Attempt to make file out on raw element
setRing();
}
});
}
public void setRing(){
File newSoundFile = new File("/sdcard/media/ringtone", "fortkickass.mp3");
Uri mUri = Uri.parse("android.resource://com.wochstudios.ringtonetest/R.raw.fortkickass");
ContentResolver mCr = getContentResolver();
AssetFileDescriptor soundFile;
try {
soundFile= mCr.openAssetFileDescriptor(mUri, "r");
} catch (FileNotFoundException e) {
soundFile=null;
}
try {
byte[] readData = new byte[1024];
FileInputStream fis = soundFile.createInputStream();
FileOutputStream fos = new FileOutputStream(newSoundFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
}
}
this crashes once it hits the second try catch of the setRing method, i got this code from a question posted earlier but i can't find the link anymore any help would be great
EDIT
i fooled around and discovered that the Assetfiledescriptor soundFile is null so that what causes the crash so now i need to figure out why it is null.
The first try/catch block does:
soundFile=null;
if the read fails.
Then, in the second, you use soundfile in:
FileInputStream fis = soundFile.createInputStream();
You are reading null because the first try failed
Use this instead
InputStream ins = context.getResources().openRawResource (R.raw.FILENAME)
byte[] buffer = new byte[ins.available()];
ins.read(buffer);
ins.close();
String filename = Environment.getExternalStorageDirectory().toString()+File.separator+FILENAME;
FileOutputStream fos = new FileOutputStream(filename);
fos.write(buffer);
fos.close();