Android: Trouble with using multiple context menu's - java

What I have here real simple activity with two buttons. When you press each of them it plays a sound.
When i press and hold the first button it brings up a context menu asking the user if they want to save the sound as a ringtone or notification. This works perfectly on the first button.
The second button's sound plays when pressed. When long pressed it brings up the context menu....BUT it saves the first sound file as ringtone/notification NOT the second...
Would someone be able to shed some insight on why the second context menu isn't working properly?
package com.my.app;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.Toast;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
public class One extends Activity implements OnClickListener{
private SoundManager mSoundManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one);
mSoundManager = new SoundManager();
mSoundManager.initSounds(getBaseContext());
mSoundManager.addSound(1, R.raw.blah);
mSoundManager.addSound(2, R.raw.rofl);
//BUTTONS PLAY SOUND WHEN PRESSED
View SoundButton1 = findViewById(R.id.Sound1);
SoundButton1.setOnClickListener(this);
View SoundButton2 = findViewById(R.id.Sound2);
SoundButton2.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.Sound1:
mSoundManager.playSound(1);
break;
case R.id.Sound2:
mSoundManager.playSound(2);
break;
}
//WHEN LONG PRESSED BUTTONS BRING UP CONTEXT MENU FOR SAVE AS RINGTONE OR NOTIFICATION
Button SoundButton11 = (Button) findViewById(R.id.Sound1);
registerForContextMenu(SoundButton11);
Button SoundButton22 = (Button) findViewById(R.id.Sound2);
registerForContextMenu(SoundButton22);
}
//CONTEXT MENU FOR BUTTON 1
#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(R.raw.blah)){
// 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(R.raw.blah)){
// 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();
}
//CONTEXT MENU FOR BUTTON 2
}
public void onCreateContextMenu1(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");
}
public boolean onContextItemSelected1(MenuItem item) {
if(item.getTitle()=="Ringtone"){function11(item.getItemId());}
else if(item.getTitle()=="Notification"){function21(item.getItemId());}
else {return false;}
return true;
}
public void function11(int id){
if (savering(R.raw.rofl)){
// 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 function21(int id){
if (savenot(R.raw.rofl)){
// 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();
}
}
public boolean savering(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/ringtones/";
String filename="HahaSound"+".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, "HahaSound");
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, false);
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;
}
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="HahaSound"+".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, "HahaSoundSound");
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;
}
}
UPDATED SINCE STOLE'S RESPONSE-
//BUTTON 1
View SoundButton1 = findViewById(R.id.Sound1);
SoundButton1.setOnClickListener(this);
View SoundButton2 = findViewById(R.id.Sound2);
SoundButton2.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.Sound1:
mSoundManager.playSound(1);
break;
case R.id.Sound2:
mSoundManager.playSound(2);
break;
}
Button SoundButton11 = (Button) findViewById(R.id.Sound1);
registerForContextMenu(SoundButton11);
Button SoundButton22 = (Button) findViewById(R.id.Sound2);
registerForContextMenu(SoundButton22);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Save as...");
menu.add(0, MENU_RINGTONE, 0, "Ringtone");
menu.add(0, MENU_NOTIFICATION, 0, "Notification");
}
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
long SoundButton11 = info.id;
switch (item.getItemId()) {
case MENU_RINGTONE:
if (savering(R.raw.schwing)){
// 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();
}
break;
case MENU_NOTIFICATION:
if (savenot(R.raw.schwing)){
// 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();
}
break;
}
return false;
}
This is what 've got since reading your last response. I'm just trying to get it working on the first button before i try moving onto the next. But with your code i'm getting a warning under SoundButton11 "The local variable SoundButton11 is never read"
I'm confused because I have...
Button SoundButton11 = (Button) findViewById(R.id.Sound1);
registerForContextMenu(SoundButton11);
I also tried Sound1 and that did not work either. Any suggestions?

2 Things about your code....
1) There's no function called onCreateContextMenu1 so you're not overriding it...So the first onCreateContextMenu is called.
2)
menu.add(0, v.getId(), 0, "Ringtone");
menu.add(0, v.getId(), 0, "Notification");
You're assigning both menu item (Context) the same id...they ideally have to be different. how else would you identify them. I'm suprised its actually working for you, using titles.
here's what you should be doing...
final int MENU_RINGTONE = 0;
final int MENU_NOTIFICATION = 1;
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, MENU_RINGTONE, 0, "Ringtone");
menu.add(0, MENU_NOTIFICATION, 0, "Notification");
}
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
long buttonId = info.id;
switch (item.getItemId()) {
case MENU_RINGTONE:
function1(buttonId);
break;
case MENU_NOTIFICATION:
function2(buttonId);
break;
}
}
you don't need the additional function12,funtion11,function21,function22...you can generalize them...but i leave that upto you.

Check the comments, i left below...
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
long SoundButton11 = info.id; //THIS IS THE UNUSED VARIABLE!
switch (item.getItemId()) {
case MENU_RINGTONE:
if (savering(R.raw.schwing)){ //this should change based on what button was pressed...
// 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();
}
break;
case MENU_NOTIFICATION:
if (savenot(R.raw.schwing)){ //this should change based on what button was pressed...
// 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();
}
break;
}
return false;
}
I suppose this is something on the lines that you want...before you do this make sure SoundButton1(& 2) are Instance Variables so they can be accessible in all the functions of your Activity.
//UNTESTED CODE!
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
long SoundButton11 = info.id; //THIS IS THE UNUSED VARIABLE!
int resId = (SoundButton11 == SoundButton1.getId() )? R.raw.schwing : R.raw.rolf;
switch (item.getItemId()) {
case MENU_RINGTONE:
if (savering(resId)){ //use resId instead...
// Code if successful
Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show();
}
else
.....

Related

Listen any key pressed on edittext

I am having a question, how to handle EditText when I press any key from mobile, then a Toast will appear with its content: "Key is pressed".
I used:
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
while(event.getCharacters()!=null )
........
}
});
but it is not ok.
Can anybody help me?
Try the following ---
edittext.setOnKeyListener(new EditText.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction()==KeyEvent.ACTION_DOWN)
{
//Do anything with editTextContent
String editTextContent = edittext.getText().toString();
Toast.makeText(getApplicationContext(),
editTextContent +": Key is pressed", Toast.LENGTH_LONG).show();
}
});
This is my function on my application,when i entered a text in edittext field and entered,then Toast will appear with the entered content:
private Bitmap ProcessingBitmap(){
Bitmap bm1 = null;
Bitmap newBitmap = null;
try {
bm1 = BitmapFactory.decodeStream(
getContentResolver().openInputStream(selectedImage));
Config config = bm1.getConfig();
if(config == null){
config = Bitmap.Config.ARGB_8888;
}
newBitmap = Bitmap.createBitmap(bm1.getWidth(), bm1.getHeight(), config);
Canvas newCanvas = new Canvas(newBitmap);
newCanvas.drawBitmap(bm1, 0, 0, null);
String captionString = editTextCaption.getText().toString();
editTextCaption.getText().clear();
if(captionString != null){
Paint paintText = new Paint(Paint.ANTI_ALIAS_FLAG);
paintText.setColor(Color.GREEN);
paintText.setTextSize(50);
paintText.setStyle(Style.FILL);
paintText.setShadowLayer(10f, 10f, 10f, Color.BLACK);
Rect rectText = new Rect();
paintText.getTextBounds(captionString, 0, captionString.length(), rectText);
newCanvas.drawText(captionString, 0, rectText.height(), paintText);
Toast.makeText(getApplicationContext(), "drawText: " + captionString, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "caption empty!", Toast.LENGTH_LONG).show();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newBitmap;
}
OR use it on this way hope it's help:
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
while(event.getCharacters()!=null )
String captionString = edittext.getText().toString();
Toast.makeText(getApplicationContext(), "drawText: " + captionString, Toast.LENGTH_LONG).show();
}
});
i put the comments but it's not show,i don't know why,ok try this hope it's worked,also it's working fine on my side.
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
while(event.getCharacters()!=null )
String captionString = edittext.getText().toString();
if(captionString != null){
Toast.makeText(getApplicationContext(), "drawText: " + captionString, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "caption empty!", Toast.LENGTH_LONG).show();
}
}
});

boolean issue on copy to SD, need some help to correct

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");.

Copy fileto SD Card from Raw folder after context-menu selection?

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" />

Android: Record video and play mp3 simultaneously?

Is there a way to play a mp3 (or other) audio file while the camera is recording a video (without sound) on Android 4.x?
Has anybody ever tried to achieve this?
I've tried to play sound while recording sound and it was working, so I'm quite sure it is possible when recording video as well. You just need to have separate threads for video recording and sound playing.
package com.technologies.mash.MySounds.Music;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.CamcorderProfile;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.technologies.mash.CameraPreview;
import com.technologies.mash.PlayVideo;
import com.technologies.mash.R;
import com.technologies.mash.Sound;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class AlbumDetailVideo extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
private MediaRecorder mediaRecorder;
private Button capture, switchCamera;
private Context myContext;
private RelativeLayout cameraPreview;
AudioManager audioManager;
private boolean cameraFront = false;
// private ArrayList<Sound> mSounds = null;
int z = 0;
Sound s1;
MediaPlayer mPlayer;
int sound;
String urls;
String audio, root, video, video_new, output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_album_detail_video);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// getting songpath from server
Intent i = getIntent();
urls = i.getStringExtra("songpath");
// String urls = getIntent().getExtras().getString("songpath");
Toast.makeText(AlbumDetailVideo.this, "Sound id" + urls, Toast.LENGTH_SHORT).show();
Log.e("url", urls);
// mSounds = new ArrayList<Sound>();
myContext = this;
initialize();
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
cameraId = i;
cameraFront = true;
break;
}
}
return cameraId;
}
private String readTxt() {
InputStream inputStream = getResources().openRawResource(z);//getting the .txt file
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
private int findBackFacingCamera() {
int cameraId = -1;
// Search for the back facing camera
// get the number of cameras
int numberOfCameras = Camera.getNumberOfCameras();
// for every camera check
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
cameraFront = false;
break;
}
}
return cameraId;
}
public void onResume() {
super.onResume();
if (!hasCamera(myContext)) {
Toast toast = Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG);
toast.show();
finish();
}
if (mCamera == null) {
// if the front facing camera does not exist
if (findFrontFacingCamera() < 0) {
Toast.makeText(this, "No front facing camera found.", Toast.LENGTH_LONG).show();
switchCamera.setVisibility(View.GONE);
}
mCamera = Camera.open(findBackFacingCamera());
mCamera.setDisplayOrientation(90);
mPreview.refreshCamera(mCamera);
}
}
public void initialize() {
cameraPreview = (RelativeLayout) findViewById(R.id.camera_preview);
mPreview = new CameraPreview(myContext, mCamera);
cameraPreview.addView(mPreview);
capture = (Button) findViewById(R.id.button_capture);
capture.setOnClickListener(captrureListener);
switchCamera = (Button) findViewById(R.id.button_ChangeCamera);
switchCamera.setOnClickListener(switchCameraListener);
}
View.OnClickListener switchCameraListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// get the number of cameras
if (!recording) {
int camerasNumber = Camera.getNumberOfCameras();
if (camerasNumber > 1) {
// release the old camera instance
// switch camera, from the front and the back and vice versa
releaseCamera();
chooseCamera();
} else {
Toast toast = Toast.makeText(myContext, "Sorry, your phone has only one camera!", Toast.LENGTH_LONG);
toast.show();
}
}
}
};
public void chooseCamera() {
// if the camera preview is the front
if (cameraFront) {
int cameraId = findBackFacingCamera();
if (cameraId >= 0) {
// open the backFacingCamera
// set a picture callback
// refresh the preview
mCamera = Camera.open(cameraId);
mCamera.setDisplayOrientation(90);
// mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
} else {
int cameraId = findFrontFacingCamera();
if (cameraId >= 0) {
// open the backFacingCamera
// set a picture callback
// refresh the preview
mCamera = Camera.open(cameraId);
mCamera.setDisplayOrientation(90);
// mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
}
}
#Override
protected void onPause() {
super.onPause();
// when on Pause, release camera in order to be used from other
// applications
releaseCamera();
}
private boolean hasCamera(Context context) {
// check if the device has camera
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}
boolean recording = false;
View.OnClickListener captrureListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(AlbumDetailVideo.this, "Playing.." + urls, Toast.LENGTH_SHORT).show();
if (recording) {
// stop recording and release camera
mediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
mPlayer.stop();
Intent intent = new Intent(getApplicationContext(), PlayVideo.class);
startActivity(intent);
finish();
Toast.makeText(AlbumDetailVideo.this, "Video captured!", Toast.LENGTH_LONG).show();
recording = false;
} else {
if (!prepareMediaRecorder()) {
Toast.makeText(AlbumDetailVideo.this, "Fail in prepareMediaRecorder()!\n - Ended -", Toast.LENGTH_LONG).show();
finish();
}
// work on UiThread for better performance
runOnUiThread(new Runnable() {
public void run() {
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(urls);
} catch (IllegalArgumentException e) {
Toast.makeText(AlbumDetailVideo.this, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(AlbumDetailVideo.this, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(AlbumDetailVideo.this, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(AlbumDetailVideo.this, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(AlbumDetailVideo.this, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
mediaRecorder.start();
mPlayer.start();
}
});
recording = true;
}
}
};
private void releaseMediaRecorder() {
if (mediaRecorder != null) {
mediaRecorder.reset(); // clear recorder configuration
mediaRecorder.release(); // release the recorder object
mediaRecorder = null;
mCamera.lock(); // lock camera for later use
}
}
private boolean prepareMediaRecorder() {
mediaRecorder = new MediaRecorder();
// CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
mCamera.unlock();
mediaRecorder.setCamera(mCamera);
// mediaRecorder.setAudioSource(MediaRecorder.AudioEncoder.AAC_ELD);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
/* mediaRecorder.setOutputFormat(profile.fileFormat);
mediaRecorder.setVideoEncoder(profile.videoCodec);
mediaRecorder.setVideoEncodingBitRate(profile.videoBitRate);
mediaRecorder.setVideoFrameRate(profile.videoFrameRate);
mediaRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);*/
mediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
try {
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW));
} catch (Exception e) {
}
mediaRecorder.setOutputFile("/sdcard/rohit.mp4");
mediaRecorder.setMaxDuration(600000); // Set max duration 60 sec.
mediaRecorder.setMaxFileSize(50000000); // Set max file size 50M
try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
releaseMediaRecorder();
return false;
} catch (IOException e) {
releaseMediaRecorder();
return false;
}
return true;
}
/* private boolean prepareMediaRecorder() {
mediaRecorder = new MediaRecorder();
mCamera.unlock();
mediaRecorder.setCamera(mCamera);
//mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
try {
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
}catch (Exception e){
}
mediaRecorder.setOutputFile("/sdcard/myvideo.mp4");
mediaRecorder.setMaxDuration(600000); // Set max duration 60 sec.
mediaRecorder.setMaxFileSize(50000000); // Set max file size 50M
try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
releaseMediaRecorder();
return false;
} catch (IOException e) {
releaseMediaRecorder();
return false;
}
return true;
}*/
private void releaseCamera() {
// stop and release camera
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
}

Android Java soundboard code only setting first button as ringtone/etc

I've been playing around with this code and I'm obviously trying to make a soundboard that will save ringtones on longclicks and etc.
Though, this is the basic code for one button. I've been duplicating the same code on top of each other, trying to make arrays, just everything.. I can't get this code to work the way I want it to.
When they are multiple buttons and more codes.
I can get the sounds to all play for the buttons. I can get the menu to pop up for each button. Tho, the first button is always the one that gets saved, and the rest just fall off the map.
I assume that my data flow on the following code is not getting cut off and being picked up by the other sound buttons. Either way, it doesn't work. Please help me.
public class Soundboard extends Activity {
private SoundManager mSoundManager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSoundManager = new SoundManager();
mSoundManager.initSounds(getBaseContext());
mSoundManager.addSound(1, R.raw.sound1);
Button SB = (Button)findViewById(R.id.sound1);
SB.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mSoundManager.playSound(1);
}
});
Button btn = (Button) findViewById(R.id.sound1);
registerForContextMenu(btn);
}
#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(R.raw.sound1)) {
// 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(R.raw.sound1)) {
// 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'm just learning Android programming myself, but it seems like this is why you're always saving the first sound:
savering(R.raw.sound1)
and
savenot(R.raw.sound1)
Both of those are explicitly saving the first sound. Unless you've written a separate function1 and function2 for each button. But there's got to be a better way to manage saving than that.

Categories

Resources