views:

182

answers:

2

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?

+1  A: 

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.

st0le
This is also why @Override is so useful - it clearly tells you that you're not overriding something even though you may think you are.
EboMike
the v.getId() was passed so the button that was pressed can be identified. The method you provide is much neater :)
stealthcopter
Thank you so much for taking a look at this for me, sorry im just now getting around to trying to fix this issue. Anyway, I was trying out the code you recommended but I ran into a small issue. Any Idea what I did wrong?
brybam
A: 

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  
.....
st0le