0

I have mediaplayer in a class, but it doesn't work without a context. Can you help me with this problem?

package org.altervista.xsparter.www.app01;

import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;

public class actionview extends Activity {
    private static Context context;

    public static void setContext(Context mcontext) {
        if (context == null)
            context = mcontext;
    }
    public void getSound(String nota){
        //Se la nota è docentrale
        MediaPlayer mp1 = MediaPlayer.create(context, findViewById(context.getResources().getIdentifier(nota, "id", BuildConfig.APPLICATION_ID)));
    }
}
EugZol
  • 6,476
  • 22
  • 41
Animal
  • 1

1 Answers1

1

You are extending Activity which means your Context is the activity itself.

You can use keyword this to use context of the activity you are in.

There is no need to create methods like setContext() especially if you need just context of your current activity.

Additional info on what context is : http://developer.android.com/reference/android/content/Context.html

What is 'Context' on Android?

Community
  • 1
  • 1
poss
  • 1,759
  • 1
  • 12
  • 27
  • If your problem is solved feel free to accept the answer to get the question out of 'unanswered' queue. – poss Aug 08 '15 at 17:57
  • I cannot tell where is the nullpointerexception without seeing any code. However we solved the context problem which was the point of this question. With new problem you should open new question with relevant information. – poss Aug 08 '15 at 18:32
  • Main Main = new Main(); //Se la nota è docentrale Resources res = this.getResources(); int soundId = res.getIdentifier(nota, "raw", this.getPackageName()); MediaPlayer mp1 = MediaPlayer.create(this,soundId); – Animal Aug 08 '15 at 18:40
  • Again - with question unrelated to this one you should open new question and post all the relevant information there. Without logcat, whole code etc. comment section are not a way to solve it. – poss Aug 08 '15 at 18:44