I wonder is there any way to set ringtones that get from url path when user long click on ringtones name in Activity.
Bellow code i tried to change filnal path from R.raw.sound1 to URL path, but still can't.
Anyone can give me a clue of how to set ringtone getting file from URL?
Here is my code
final MediaPlayer ring01 = MediaPlayer.create(this, R.raw.sound1);
// play sound files on clicks
Button s01 = (Button) findViewById(R.id.btnring01);
s01.setText(this.getString(R.string.title01));
s01.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try
{
ring01.prepare();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
ring01.start();
}
});
registerForContextMenu(s01);
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Save as...");
menu.add(0, v.getId(), 0, "Tab Here To Save As Ringtone");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle()=="Tab Here To Save As Ringtone"){function1(item.getItemId());}
else {return false;}
return true;
}
public boolean function1(int ressound){
String soundname = "";
switch(ressound)
{
case R.id.btnring01:
ressound=R.raw.aftermath;
soundname = (this.getString(R.string.title01));
break;
}
//and so on and so on.....
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/media/audio/ringtones/";
String filename=soundname+".ogg";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
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;
}
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, soundname);
values.put(MediaStore.MediaColumns.SIZE, 215454);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "Sokun Kanha");
values.put(MediaStore.Audio.Media.DURATION, 230);
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
//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, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
Related
I can rake pictures from this code but i am not able to save the pictures into custom directory Uri uriTarget = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
and i think this is probably the line where i have to change my code
want to make a custom directory and save my image there
Camera.ShutterCallback myShutterCallback = new Camera.ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
Camera.PictureCallback myPictureCallback_RAW = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
Camera.PictureCallback myPictureCallback_JPG = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
Uri uriTarget = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(MainActivity.this,
"waH kiAa selfie hAi :D ",
//+ uriTarget.toString(),
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
}};
Try this approach...
private void saveImage(byte[] arg0) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "YOUR_CUSTOM_FOLDER";
File myDir = new File(root);
myDir.mkdirs();
String fname = "YOUR_IMAGE_NAME" + ".jpg";
file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
Bitmap bitmap1 = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
FileOutputStream out;
try {
out = new FileOutputStream(file);
bitmap1.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
MediaStore.Images.Media.insertImage(activity.getContentResolver(), bitmap1, "", "");
}
i almost finished my app, im working on menu items now,
The problem is to set a bitmap as wallpaper and save it on sdcard from menu item.
i tried to things, 1st was to create a second intent which was taking -again- same data from previous activity , -I have failed-
2nd was using the same intent -i ve failed-
here is my code.
thank you
public class Fullpic extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// menu
getMenuInflater().inflate(R.layout.menu_pics, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_set:
// setting as wallpaper
return true;
case R.id.menu_save:
// save the image on sdcard
return true;
case R.id.menu_back:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//menu end
// XML node keys
static final String KEY_THUMB_URL = "source";
static final String HEIGHT_MAX = "600";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_pic);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent dude
String bid = in.getStringExtra(KEY_THUMB_URL);
int hoppa= Integer.parseInt(in.getStringExtra(HEIGHT_MAX));
// Displaying all values on the screen
ImageView balls = (ImageView) findViewById(R.id.bals_label);
balls.getLayoutParams().height = hoppa-30;
URL url = null;
try {
url = new URL(bid);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
balls.setImageBitmap(bmp);
}
public Object fetch(String address) throws MalformedURLException,
IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
private Drawable ImageOperations(Context ctx, String url) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(is, "source");
return d;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
}
new Thread(new Runnable(){
#Override
public void run(){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/blabla");
myDir.mkdirs();
String fname = "name_here.jpg";
File file = new File (myDir, fname);
if (file.exists ())
file.delete ();
try {
FileOutputStream out = new FileOutputStream(file); //create stream to output the contents of the image
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out); //compress and write bitmap data to output file stream
out.flush();
out.close(); //closes stream important to avoid memory leaks
} catch (Exception e) {
//exception handling
}
}}).start();
This should help you write the bitmap file to where you need it to be on the SD card of the device, and done in a thread to keep heavy actions off the main UI Thread. Cheers.
Hello I have this code(pasted below) which reads and displays the phone contacts in a ListView. Apart from this it should also have one more functionality and that is it should be able to write the contacts as they are being read onto to a xml file. I want to store that xml in my SD card.Please check the code below.
public class ContactsListActivity extends Activity implements
OnItemClickListener
{
private ListView listView;
private List<ContactBean> list = new ArrayList<ContactBean>();
XmlSerializer serializer = Xml.newSerializer();
File newxmlfile = new File(Environment.getExternalStorageDirectory()+"/new.xml");
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
try{
newxmlfile.createNewFile();
}catch(IOException e){
Log.e("IOException", "exception in createNewFile() method");
}
//we have to bind the new file with a FileOutputStream
FileOutputStream fileos = null;
try{
fileos = new FileOutputStream(newxmlfile);
}catch(FileNotFoundException e){
Log.e("FileNotFoundException", "can't create FileOutputStream");
}
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
//we set the FileOutputStream as output for the serializer, using UTF-8 encoding
try {
serializer.setOutput(fileos, "UTF-8");
//Write <?xml declaration with encoding (if encoding not null) and standalone flag (if standalone not null)
serializer.startDocument(null, Boolean.valueOf(true));
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (phones.moveToNext()) {
String name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ContactBean objContact = new ContactBean();
objContact.setName(name);
objContact.setPhoneNo(phoneNumber);
list.add(objContact);
//create a new file called "new.xml" in the SD card
//we create a XmlSerializer in order to write xml data
try {
//set indentation option
// serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
//start a tag called "root"
serializer.startTag(null, name);
//i indent code just to have a view similar to xml-tree
serializer.startTag(null, "name");
serializer.text(name);
serializer.endTag(null, "name");
serializer.startTag(null, "phonenumber");
serializer.text(phoneNumber);
serializer.endTag(null, "phonenumber");
serializer.endTag(null, name);
//write xml data into the FileOutputStream
serializer.flush();
//finally we close the file stream
fileos.close();
} catch (Exception e) {
Log.e("Exception","error occurred while creating xml file");
}
try {
//write xml data into the FileOutputStream
// serializer.flush();
//finally we close the file stream
// fileos.close();
serializer.endDocument();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
phones.close();
ContactAdapter objAdapter = new ContactAdapter(
ContactsListActivity.this, R.layout.alluser_row, list);
listView.setAdapter(objAdapter);
if (null != list && list.size() != 0) {
Collections.sort(list, new Comparator<ContactBean>() {
#Override
public int compare(ContactBean lhs, ContactBean rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
AlertDialog alert = new AlertDialog.Builder(
ContactsListActivity.this).create();
alert.setTitle("");
alert.setMessage(list.size() + " Contact Found!!!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
} else {
showToast("No Contact Found!!!");
}
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onItemClick(AdapterView<?> listview, View v, int position,
long id) {
ContactBean bean = (ContactBean) listview.getItemAtPosition(position);
showCallDialog(bean.getName(), bean.getPhoneNo());
}
#SuppressWarnings("deprecation")
private void showCallDialog(String name, final String phoneNo) {
AlertDialog alert = new AlertDialog.Builder(ContactsListActivity.this)
.create();
alert.setTitle("Call?");
alert.setMessage("Are you sure want to call " + name + " ?");
alert.setButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.setButton2("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String phoneNumber = "tel:" + phoneNo;
Intent intent = new Intent(Intent.ACTION_CALL, Uri
.parse(phoneNumber));
startActivity(intent);
}
});
alert.show();
}
}
I got this code off the internet and it has a flaw. Only the last read contact is getting added to the xml file on my sd card. When i debugged the code, It shows proper traversing of the code and all contacts.
I would like to add all the read contacts onto the xml file am storing. Any help or correction in this code is very much appreciated. Thanks in advance.
I need to save the barcode with timestamp and save that in a .csv file and send it to another device via Bluetooth. I am taking the barcode through SerialMagic Gear Keyboard option which take the barcode as an input
Problem: When the application run and i enter data, when the file is received by another device the file only contains the last entry.
I am sure that I am making some mistake in the structure of the program. If so kindly indicate where.
And sorry for the long code.
package com.android.app;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Timestamp for file name e.g. Data_7-19-2012
SimpleDateFormat s1 = new SimpleDateFormat("MM-dd-yyyy_hh:mm:ss");
final String format1 = s1.format(new Date());
//Creating file name
final String FileName = "Data_"+format1+".csv";
final EditText addbarcode = (EditText) findViewById(R.id.editText1);
//getting file directory
final File dir = getFilesDir();
final File shareFile = new File(dir, FileName);
addbarcode.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
switch (keyCode)
{
//case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
//to get Timestamp
SimpleDateFormat s = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
String format = s.format(new Date());
//get barcode in a variable
Editable barcode = addbarcode.getText();
final String DATASTRING = new String(""+barcode+","+format+"\n");
FileOutputStream fOut = null;
try {
fOut = openFileOutput(FileName , MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
try {
osw.write(DATASTRING);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
osw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
osw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* ensure that everything is
* really written out and close */
//For showing data recived on screen
FileInputStream fIn = null;
try {
fIn = openFileInput(FileName);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStreamReader isr = new InputStreamReader(fIn);
//Prepare a char-Array that will
//* hold the chars we read back in.
char[] inputBuffer = new char[DATASTRING.length()];
// Fill the Buffer with data from the file
try {
isr.read(inputBuffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Transform the chars to a String
String readString = new String(inputBuffer);
TextView etData= (TextView)findViewById(R.id.textView3);
etData.setText(readString);
//Clear the editview for new entries
addbarcode.setText("");
return true;
default:
break;
}
}
return false;
}
});
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Uri u1 = null;
u1 = Uri.fromFile(shareFile);
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Person Details");
sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
sendIntent.setType("text/csv");
startActivity(sendIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
You need to use the MODE_APPEND flag in openFileOutput, otherwise the old file contents gets overwritten by default.
I have a soundboard and I am trying to save sounds as a ringtone or notification but it is saving the same sound each time which I think is being pulled from " here can anyone shed some light? Thinking it needs to change R.raw.sound1 so it pulls in the sound of which ever button is clicked to bring up the context menu.
I've added the loop and integrs code which makes the buttons work just in case.
EDIT FULL CODE - Error: selectedSoundId cannot be resolved
:- for each three bits of code that say selectedSoundId
Not sure if I have done this bit:
Where and how do I add this?
The "int selectedSoundId" should be declared as a class field, to make it accessible in every class method.
public class Soundboard extends Activity {
private SoundManager mSoundManager;
/** Called when the activity is first created. */
int selectedSoundId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.soundboard);
final MediaPlayer player = new MediaPlayer();
final Resources res = getResources();
//just keep them in the same order, e.g. button01 is tied to backtoyou
final int[] buttonIds = { R.id.backdoors etc};
final int[] soundIds = { R.raw.back_doors etc };
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
//find the index that matches the button's ID, and then reset
//the MediaPlayer instance, set the data source to the corresponding
//sound effect, prepare it, and start it playing.
for(int i = 0; i < buttonIds.length; i++) {
if(v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
break;
}
}
}
};
//set the same listener for every button ID, no need
//to keep a reference to every button
for(int i = 0; i < buttonIds.length; i++) {
Button soundButton = (Button)findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Save as...");
menu.add(0, v.getId(), 0, "Ringtone");
menu.add(0, v.getId(), 0, "Notification");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle()=="Ringtone"){function1(item.getItemId());}
else if(item.getTitle()=="Notification"){function2(item.getItemId());}
else {return false;}
return true;
}
public void function1(int id){
if
(savering(selectedSoundId)){
// Code if successful
Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show();
}
else
{
// Code if unsuccessful
Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
}
}
public void function2(int id){
if
(savenot(selectedSoundId)){
// Code if successful
Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show();
}
else
{
// Code if unsuccessful
Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
}
}
//Save into Ring tone Folder
public boolean savering(int ressound){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=50;
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/media/audio/ringtones/";
String filename="ohhh"+".ogg";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
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, "Ohhh Ringtone");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "weee");
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, false);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
}
//Save in Notification Folder
public boolean savenot(int ressound){
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/media/audio/notifications/";
String filename="ohhh"+".ogg";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
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, "Ohhh Notification");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "weee");
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, false);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
}
}
I don't see where you are replacing the content of
R.raw.sound1
which you are passing as an argument, thus, as I can observe in your code, you are saving the same sound every time you call the saving methods.
EDIT:
Create int variable which will hold the info about last selected sound:
int selectedSoundId;
In onClickListener set the selectedSoundId to sound id connected with current button:
if(v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
//rest of the code
}
Pass the selectedSoundId to savering and savenot methods:
savering(selectedSoundId);
savenot(selectedSoundId);
Hope this helps.
EDIT 2: I'm pasting your code with my corrections.
Ad.2. This is the part when you need to save the info about current sound id.
final int[] buttonIds = { R.raw.sound1 "etc all buttons here"};
final int[] soundIds = {R.raw.sound1 "etc all sounds here"};
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
//find the index that matches the button's ID, and then reset
//the MediaPlayer instance, set the data source to the corresponding
//sound effect, prepare it, and start it playing.
for(int i = 0; i < buttonIds.length; i++) {
if(v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
break;
}
}
}
};
Ad.3. This is the part of calling the savering and savenot methods.
if
(savering(selectedSoundId)){
// Code if successful
Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show();
}
else
{
// Code if unsuccessful
Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
}
}
public void function2(int id){
if
(savenot(selectedSoundId)){
// Code if successful
Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show();
}
else
{
// Code if unsuccessful
Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
}
}