Reputation: 155
I want to play an audio file when a Button clicked. But my code generate error code that says:
Cannot resolve method'create(context, int)'
So, my audio file is detected as an integer.
this is my fragment code:
package com.example.suha.belajarhurufhijaiyah;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
/**
* A simple {@link Fragment} subclass.
*/
public class Hijaiyah extends Fragment implements View.OnClickListener {
ImageButton alif;
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_hijaiyah, container, false);
alif = view.findViewById(R.id.alif_sound);
alif.setOnClickListener(this);
return view;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.alif_sound:
MediaPlayer mp = MediaPlayer.create(this, R.raw.sound_alif);
mp.start();
}
}
}
That R.raw.sound_alif
generate the error..
And it's my resource hier
Upvotes: 0
Views: 74
Reputation: 12715
All resources are represented as Integers
in the R
class that is not your problem the problem is the Context
your passing in a Fragment
change this
to getActivity
So change your line to:
MediaPlayer mp = MediaPlayer.create(getActivity, R.raw.sound_alif);
Upvotes: 1
Reputation: 3100
you are trying to create MediaPlayer in Fragment use getActivity()
or getContext()
instead of this
so use below code
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.alif_sound:
MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.sound_alif);
mp.start();
}
Upvotes: 1