I'm (slowly) making an app which displays a list of tones and lets the user "long press" a certain one which then brings up a context menu asking if you'd like to copy it to SD card.
Only problem is that last part, I need help. Basically the tones are stored in the Raw folder, and I need it that it copies the selected tone file to the SD card, preferably in the notifications folder.
Just wondering if someone could give me an example of how I would go about this because I'm absolutely lost?
Here's my code
import java.util.ArrayList;
import android.app.ListActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private ArrayList<Sound> mSounds = null;
private SoundAdapter mAdapter = null;
static MediaPlayer mMediaPlayer = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerForContextMenu(getListView());
this.getListView().setSelector(R.drawable.selector);
//create a simple list
mSounds = new ArrayList<Sound>();
Sound s = new Sound();
s.setDescription("Anjels");
s.setSoundResourceId(R.raw.anjels);
mSounds.add(s);
s = new Sound();
s.setDescription("Fizz");
s.setSoundResourceId(R.raw.fizz);
mSounds.add(s);
s = new Sound();
s.setDescription("Flipper");
s.setSoundResourceId(R.raw.flipper);
mSounds.add(s);
s = new Sound();
s.setDescription("Glass Key");
s.setSoundResourceId(R.raw.glasskey);
mSounds.add(s);
s = new Sound();
s.setDescription("Halo");
s.setSoundResourceId(R.raw.halo);
mSounds.add(s);
mAdapter = new SoundAdapter(this, R.layout.list_row, mSounds);
setListAdapter(mAdapter);
}
#Override
public void onListItemClick(ListView parent, View v, int position, long id){
Sound s = (Sound) mSounds.get(position);
MediaPlayer mp = MediaPlayer.create(this, s.getSoundResourceId());
mp.start();
}#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int length = mSounds.size(); // get the length of mSounds object
String[] names = new String[length]; // creates a fixed array with strings
for(int i = 0; i < length; i++) {
// add sound name to string array
names[i] = mSounds.get(i).getDescription(); // returns the string name
}
switch(item.getItemId()) {
case R.id.copytosd:
Toast.makeText(this, "Applying " + getResources().getString(R.string.copy) +
" for " + names[(int)info.id],
Toast.LENGTH_SHORT).show();
return true;
default:
return super.onContextItemSelected(item);
}
}}
Refer the below links. It will help you..
Copying raw file into SDCard?
Move Raw file to SD card in Android
Copy file from raw dir to SDcard
public boolean saveas(int ressound, String fName){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path="/sdcard/music/[my_package_name]/";
String filename=fName+".ogg";
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String completePath = baseDir + File.separator + "music" + File.separator + "my_package" + File.separator + filename;
boolean exists = (new File(completePath)).exists();
if (!exists){new File(completePath).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(completePath);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "exampletitle");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, true);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
}
try this instead of the one you have
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
Sound sound = getListAdapter().getItem(info.position);
int length = mSounds.size(); // get the length of mSounds object
String[] names = new String[length]; // creates a fixed array with strings
for(int i = 0; i < length; i++) {
// add sound name to string array
names[i] = mSounds.get(i).getDescription(); // returns the string name
}
switch(item.getItemId()) {
case R.id.copytosd:
Toast.makeText(this, "Applying " + getResources().getString(R.string.copy) +
" for " + names[(int)info.id],
Toast.LENGTH_SHORT).show();
boolean saved = saveas(sound.getSoundResourceId(),"filename");
return true;
default:
return super.onContextItemSelected(item);
}
}}
Try this. Call it by:
writeToSD("MyNotes.txt","Some text");
...
public void wrtieToSD(String sFileName, String sBody)
{
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
importError = e.getMessage();
iError();
}
}
Modify this to suit your needs.
Also you need the permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Related
I have created a file chooser within the ListActivity, which lists and allows you to select a file within the TravelLogs directory within the internal storage of my device.
The Objective:
I am looking to display text from the .txt file I chose from my file chooser within a TextView, from within dispText within the activity_list.xml file.
Any suggestions or resources? I have been through every tutorial on the topic and must be misunderstanding.
Updated to the most current code as of Nov27 #1226pm pst
public class ListActivity extends AppCompatActivity {
TextView dispText;
Button buttonOpenDialog;
TextView textFolder;
String KEY_TEXTPSS = "TEXTPSS";
static final int CUSTOM_DIALOG_ID = 0;
ListView dialog_ListView;
File root;
File curFolder;
private List<String> fileList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
buttonOpenDialog = (Button) findViewById(R.id.opendialog);
buttonOpenDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(CUSTOM_DIALOG_ID);
}
});
root = new File(Environment.getExternalStorageDirectory(), "TravelLogs");
curFolder = root;
dispText = (TextView) findViewById(R.id.text_file_data);
}
public String getTextFileData(String fileName) {
StringBuilder text = new StringBuilder();
Log.d("jason", "fileName: " + fileName );
try {
FileInputStream fIS = new FileInputStream(fileName);
InputStreamReader isr = new InputStreamReader(fIS, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
text.append(line + '\n');
}
br.close();
} catch (IOException e) {
text.append("IOException: " + e.getMessage() + "\n");
Log.e("Error!", "Error occured while reading text file from Internal Storage!");
}
return text.toString();
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case CUSTOM_DIALOG_ID:
dialog = new Dialog(ListActivity.this);
dialog.setContentView(R.layout.dialoglayout);
dialog.setTitle("Select Log");
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
textFolder = (TextView) dialog.findViewById(R.id.folder);
dialog_ListView = (ListView) dialog.findViewById(R.id.dialoglist);
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("jason", "fileName: " + fileName );
File selected = new File(fileList.get(position));
if(selected.isDirectory()) {
ListDir(selected);
} else {
Toast.makeText(ListActivity.this, selected.toString() + " selected",
Toast.LENGTH_LONG).show();
dismissDialog(CUSTOM_DIALOG_ID);
String text = getTextFileData(selected.getAbsolutePath());
Toast.makeText(ListActivity.this, text.toString() + " line",
Toast.LENGTH_LONG).show();
}
}
});
break;
}
return dialog;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
switch (id) {
case CUSTOM_DIALOG_ID:
ListDir(curFolder);
break;
}
}
void ListDir(File f) {
curFolder = f;
textFolder.setText(f.getPath());
File[] files = f.listFiles();
fileList.clear();
for(File file : files) {
fileList.add(file.getPath());
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, fileList);
dialog_ListView.setAdapter(directoryList);
}
#Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(ListActivity.this, MainActivity.class));
finish();
}
#Override
public boolean onSupportNavigateUp(){
startActivity(new Intent(ListActivity.this, MainActivity.class));
finish();
return true;
}
}
FileInputStream fIS = getApplicationContext().openFileInput(fileName);
Change to
FileInputStream fIS = new FileInputStream(fileName);
Further i consider this post solved.
For further detail questions make another post to solve them.
I am beginner android developer and trying to implement one function for overflow menu.
My menu code is like this
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==android.R.id.home) {
finish();
}else if (id == R.id.image) {
takeScreenshot(); // getting error like The method takeScreenshot(Context, View) in the type QuoteViewActivity is not applicable for the arguments ()
return true;
}
and
function code is like
public static void takeScreenshot(Context context, View view) {
String path = Environment.getExternalStorageDirectory().toString()
+ "/" + "test.png";
View v = view.findViewById(android.R.id.content).getRootView();
v.setDrawingCacheEnabled(true);
v.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
OutputStream out = null;
File imageFile = new File(path);
try {
out = new FileOutputStream(imageFile);
// choose JPEG format
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
} catch (FileNotFoundException e) {
// manage exception
} catch (IOException e) {
// manage exception
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception exc) {
}
}
// onPauseVideo();
Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
share.setType("image/png");
((Activity) context).startActivityForResult(
Intent.createChooser(share, "Share Drawing"), 111);
}
How can I call it on menu click ?
Sorry for stupid question for developer
Thanks
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}
don't forget this
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
The way you handle the click on a Menu Item is like this:
First, setup your Options Menu:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mnuInflater = getSupportMenuInflater();
mnuInflater.inflate(R.menu.your_menu_xml, menu);
return true;
}
Handle the clicks here:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
// EITHER CALL THE METHOD HERE OR DO THE FUNCTION DIRECTLY
yourMethod();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
And do the function in the yourMethod() here:
private void yourMethod() {
// TODO Auto-generated method stub
}
From what I see, it should be the following:
takeScreenshot(this, findViewById(R.id.your_root_layout));
However, you can call takeScreenshot(); if takeScreenshot is not static and inside your activity.
I have a listview which display a list of files (without filename extension) stored in the internal memory of the phone.
Then I have implement the OnItemLongClickListener that allow the user to delete a file.
OnItemLongClickListener works with the "switch" statement.
because position of the items in the list view will change every time a file will be deleted, I would like to implement a rule that check if the name of the file match the related file, no matter if name of the file is moved in case 0, case 1 and so on.
To be clear:
Initial Listview:
switch Listview items related file to delete
case 0; A A.map
case 1; B B.map
case 2; C C.map
case 3; D D.map
Listview after B has been deleted:
switch Listview items related file to delete
case 0; A A.map
case 1; C C.map
case 2; D
Now, if before I wrote a rule at case 1 which was to delete B.map, it works fine.
But now item C have the same rule of case 1 , and rule does not match.
Because I am new to android, I don't know how to dove this problem.
Can somebody help me?
This is the Activity
public class MainActivity extends Activity {
ListView lv;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/osmdroid/tiles/");
File[] filelist = dir.listFiles();
String[] theNamesOfFiles = new String[filelist.length];
for (int i = 0; i < theNamesOfFiles.length; i++) {
String temp = filelist[i].getName();
theNamesOfFiles[i] = temp.substring(0, temp.lastIndexOf('.'));
}
Arrays.sort(theNamesOfFiles);
adapter = new ArrayAdapter<String>(this, R.layout.list_row, theNamesOfFiles);
lv.setAdapter(adapter);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
// setting onItemLongClickListener and passing the position to the function
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
switch(position){
case 0:{
}
break;
case 1:{
}
break;
case 2:{
}
break;
case 3:{
}
break;
case 4:{
}
break;
}
return true;
}
});
}
public void doDeleteFile(int position){
File fileToDelete = new File(Environment.getExternalStorageDirectory().getPath() + "/osmdroid/tiles/", "A.map");
if(!fileToDelete.isDirectory()){
try{
if(fileToDelete.delete()){
System.out.println("File delete operation success");
}
else{
System.out.println("File delete operation failed");
}
}catch(Exception ex){
System.out.println("Exception :"+ex.getMessage());
}
}else{
System.out.println("It is not a file");
}
}
}
when you deleted your item remove it from array also and then call notifyDataSetChange() on adapter after updating the array item
No need to check for name.You can do it by position
I would do it like this:
First I will have a data structure about the items.
public class MyFile {
File file;
String fileName;
public MyFile(File file)
{
this.file = file;
this.fileName = file.getName();
fileName = fileName.substring(0, fileName.lastIndexOf('.'));
}
#Override
public String toString() {
return this.fileName;
}
}
toString() method is important. That method gives the text in the ListView in the ArrayAdapter.
Then I would initialize the adapter like this.
adapter = new ArrayAdapter<MyFile>(this, R.layout.list_row, arrayOfMyFileObjects);
And lastly in onItemLongClick() function you can get the respective MyFile object like this
MyFile item = adapter.getItem(position);
And then you can delete using deleteFile(item.file);
I think the below code should do it.
public class MainActivity extends Activity {
ListView lv;
ArrayAdapter<MyFile> adapter;
public void list() {
lv = (ListView) findViewById(R.id.listView1);
File dir = new File(Environment.getExternalStorageDirectory().getPath()
+ "/osmdroid/tiles/");
File[] filelist = dir.listFiles();
ArrayList<MyFile> theNamesOfFiles = new ArrayList<MyFile>();
for (File temp : filelist) {
theNamesOfFiles.add(new MyFile(temp));
}
Collections.sort(theNamesOfFiles, new Comparator<MyFile>() {
#Override
public int compare(MyFile lhs, MyFile rhs) {
return lhs.toString().compareToIgnoreCase(rhs.toString());
}
});
adapter = new ArrayAdapter<MyFile>(this, R.layout.list_row,
theNamesOfFiles);
lv.setAdapter(adapter);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
list();
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
// setting onItemLongClickListener and passing the position to the
// function
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
doDeleteFile(adapter.getItem(position).file);
return true;
}
});
}
public void doDeleteFile(File fileToDelete) {
if (!fileToDelete.isDirectory()) {
try {
if (fileToDelete.delete()) {
System.out.println("File delete operation success");
}
else {
System.out.println("File delete operation failed");
}
} catch (Exception ex) {
System.out.println("Exception :" + ex.getMessage());
}
} else {
System.out.println("It is not a file");
}
}
public class MyFile {
File file;
String fileName;
public MyFile(File file)
{
this.file = file;
this.fileName = file.getName();
fileName = fileName.substring(0, fileName.lastIndexOf('.'));
}
#Override
public String toString() {
return this.fileName;
}
}
}
I am trying to copy a file that is in a list of files. I want to copy the selected file when the user long clicks on the item in the list.
public class MainActivity extends ListActivity {
private File file;
private List<String> myList;
String rootsd = Environment.getExternalStorageDirectory().toString();
String old = "/Android/data/co.vine.android/cache/videos";
String dirNameSlash = "/videos/";
String path = Environment.getExternalStorageDirectory() + dirNameSlash;
String newDir = "/Saved";
String olddir2 = new String( rootsd + old );
String newdir2 = new String( rootsd + newDir);
File temp_dir = new File(newDir);
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ListView lv = getListView();
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int row, long arg3) {
String item = (String) getListAdapter().getItem(row);
// CopyFile
Toast.makeText(getApplicationContext(), "File has been copied", Toast.LENGTH_LONG).show();
return true;
}
});
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Log.d("MyApp", "No SDCARD");
} else {
File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"Saved");
directory.mkdirs();
}
myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File( root_sd + "/videos" ) ;
File list[] = file.listFiles();
for( int i=0; i< list.length; i++)
{
myList.add( list[i].getName() );
}
setListAdapter(new ArrayAdapter<String>(this,
R.layout.row, myList ));
}
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
String item = (String) getListAdapter().getItem(position);
Intent intentToPlayVideo = new Intent(Intent.ACTION_VIEW);
intentToPlayVideo.setDataAndType(Uri.parse(path + item), "video/*");
startActivity(intentToPlayVideo);
}
#Override
public void onBackPressed() {
MainActivity.this.finish();
}
Any help would be great. All the files that the user selects will be saved to the same directory. I need help identifying what file the user selects, and then copy that. Thanks!
I recommend you use a FileChanel, is more efficient and fast. Example:
try {
String root_sd = Environment.getExternalStorageDirectory().toString();
String theFile = root_sd + "/" + (String) getListAdapter().getItem(row);
File file = new File(theFile);
FileInputStream source= new FileInputStream(file);
String targetDirectory = Environment.getExternalStorageDirectory().toString();
FileOutputStream destination = new FileOutputStream(targetDirectory + "/videos/" + file.getName);
FileChannel sourceFileChannel = source.getChannel();
FileChannel destinationFileChannel = destination.getChannel();
long size = sourceFileChannel.size();
sourceFileChannel.transferTo(0, size, destinationFileChannel);
} catch (Exception ex) {
Logger.getLogger(Borrar.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
}
catch(FileNotFoundException ex)
{
//print in logcat
}
catch(IOException e)
{
//print in logcat
}
With a lot of help (on here) I've managed to nearly get my app up and running but I've got a problem. I'm basically a beginner in Java so this is a little deep for me, but I would still like some help. Basically the app displays a list of tones and lets you play them, if you touch and hold it inflates a context menu with an option to copy that selected tone to SD card.
The issue I know lies on the fourth-to-last line: boolean saved = saveas(sound.getSoundResourceId(),"filename"); because the variablesaved is not used.
I'm not too sure how to fix this,or what i should put in place of saved, just wondering if anyone on here has a clue?
Here's the full code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerForContextMenu(getListView());
this.getListView().setSelector(R.drawable.selector);
//create a simple list
mSounds = new ArrayList<Sound>();
Sound s = new Sound();
s.setDescription("Affirmative");
s.setSoundResourceId(R.raw.affirmative);
mSounds.add(s);
s = new Sound();
s.setDescription("Anjels");
s.setSoundResourceId(R.raw.anjels);
mSounds.add(s);
s = new Sound();
s.setDescription("Aggro");
s.setSoundResourceId(R.raw.aggro);
mSounds.add(s);
mSounds.add(s);
mAdapter = new SoundAdapter(this, R.layout.list_row, mSounds);
setListAdapter(mAdapter);
}
#Override
public void onListItemClick(ListView parent, View v, int position, long id){
Sound s = (Sound) mSounds.get(position);
MediaPlayer mp = MediaPlayer.create(this, s.getSoundResourceId());
mp.start();
}#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
public boolean saveas(int ressound, String fName){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path="notifications/halon/";
String filename=fName+".ogg";
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String completePath = baseDir + File.separator + "music" + File.separator + "halon" + File.separator + filename;
boolean exists = (new File(completePath)).exists();
if (!exists){new File(completePath).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(completePath);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "exampletitle");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
Sound sound = (Sound) getListAdapter().getItem(info.position);
int length = mSounds.size(); // get the length of mSounds object
String[] names = new String[length]; // creates a fixed array with strings
for(int i = 0; i < length; i++) {
// add sound name to string array
names[i] = mSounds.get(i).getDescription(); // returns the string name
}
switch(item.getItemId()) {
case R.id.copytosd:
Toast.makeText(this, "Applying " + getResources().getString(R.string.copy) +
" for " + names[(int)info.id],
Toast.LENGTH_SHORT).show();
boolean saved = saveas(sound.getSoundResourceId(),"filename");
return true;
default:
return super.onContextItemSelected(item);
}
}}
If you are not going to use saved, delete the boolean saved = from that statement and just have saveas(sound.getSoundResourceId(),"filename");.