Getting null object error on Service object. This method is not initializing
private ServiceConnection musicConnection = new ServiceConnection()
Its containg tab host then this Fragment.
public class PrimaryFragment extends Fragment {
RecyclerView rv;
LazyAdapter adapter;
ListView listView;
View rootView;
private MusicService serviceMusic;
ArrayList<AudioListModel> songsList;
private Intent playIntent;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.primary_layout, container, false);
songsList = SongsManager.GetSongs();
adapter = new LazyAdapter(getActivity(), songsList.toArray(new AudioListModel[songsList.size()]));
//rv = (RecyclerView) rootView.findViewById(R.id.songs_recycleview);
listView = (ListView) rootView.findViewById(R.id.SongList);
LazyAdapter ad = new LazyAdapter(getActivity(), songsList.toArray(new AudioListModel[songsList.size()]));
listView.setItemsCanFocus(false);
listView.setAdapter(ad);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getActivity(), position + "this is on click event", Toast.LENGTH_SHORT).show();
serviceMusic.setSelectedSong(position, MusicService.NOTIFICATION_ID); // getting error here......
Intent i = new Intent(getActivity(), PlaySongActivity.class);
startActivity(i);
}
});
return rootView;
}
// This method is not initializing.
private ServiceConnection musicConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.PlayerBinder binder = (MusicService.PlayerBinder) service;
//get servic1
serviceMusic = binder.getService();
serviceMusic.setSongList(songsList);
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
};
#Override
public void onStart() {
super.onStart();
//Start service
//Toast.makeText(getActivity(), "before onStart", Toast.LENGTH_SHORT).show();
if (playIntent == null) {
//Toast.makeText(getActivity(), "after onStart", Toast.LENGTH_SHORT).show();
playIntent = new Intent(getActivity(), MusicService.class);
getActivity().bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
getActivity().startService(playIntent);
}
}
}
here is music service class
public class MusicService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
private MediaPlayer mPlayer;
private Uri mSongUri;
private ArrayList<ListModel> mListSongs;
private int SONG_POS = 0;
private final IBinder musicBind = new PlayerBinder();
private Notification.Builder notificationBuilder;
private Notification mNotification;
public class PlayerBinder extends Binder {//Service connection to play in background
public MusicService getService() {
Log.d("test", "getService()");
return MusicService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
Log.d("test", "onBind Called ");
return musicBind;
}
i had not registed MusicService in "AndroidManifest.xml". so i include this line and it started working.
"< service android:name=".MusicService" />"
we need to register services in manifest..
Related
In my onBindViewholder, I am passing onclickListener to itemview in recycler view. Itemview consists of an array with image and text;
Main Activity
public class MainActivity extends AppCompatActivity {
private AdView mAdView;
private AdView mAdView2;
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView firstrecyclerView;
private RecyclerView thirdrecyclerView;
ArrayList<itemModel> items;
String[] iconName = {"ABP Sanjha","Breaking News Punjab","Republic Bharat", "Al Jazeera","DW News","Sky News","Indus Live","CNA","RT News"};
//cannel icons and names
private String[] channelnames={"PTC Punjabi","Chakde TV","T-Series Punjabi", "9X Tashan", "Zee Punjabi" };
private int[] channelimages={R.drawable.ptcpunjabi, R.drawable.chakde, R.drawable.tseries, R.drawable.ninex, R.drawable.zeepunjabi};
private String[] channelID={"UCHJW1_0oPzYZl89wX_jhrgA","UCaT-WGdJLyEDnxZPAKRTbqQ","UCJMSoNjSKRARSIJM3GymRjQ","UCrET5fR2NAUTO2Xp12G0l8A", "UCYF_LfBBxkFBEgaSCNrqW3w"};
private List<channel> channelList=new ArrayList<>();
//youtube player fragment
private YouTubePlayerSupportFragmentX youTubePlayerFragment;
private ArrayList<String> youtubeVideoArrayList;
private YouTubePlayer youTubePlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
generateDummyVideoList();
initializeYoutubePlayer();
setUpRecyclerView();
populateRecyclerView();
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView2 = findViewById(R.id.adView2);
AdRequest adRequest2 = new AdRequest.Builder().build();
mAdView2.loadAd(adRequest2);
}
/**
* initialize youtube player via Fragment and get instance of YoutubePlayer
*/
private void initializeYoutubePlayer() {
youTubePlayerFragment = (YouTubePlayerSupportFragmentX) getSupportFragmentManager().findFragmentById(R.id.youtube_player_fragment);
if (youTubePlayerFragment == null)
return;
youTubePlayerFragment.initialize(Constants.DEVELOPER_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
youTubePlayer = player;
//set the player style default
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
//cue the 1st video by default
youTubePlayer.cueVideo(youtubeVideoArrayList.get(0));
youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) {
//print or show error if initialization failed
Log.e(TAG, "Youtube Player View initialization failed");
}
});
}
// setup the recycler view here
private void setUpRecyclerView() {
firstrecyclerView = findViewById(R.id.first_recycler_view);
firstrecyclerView.setHasFixedSize(true);
items = new ArrayList<>();
//Horizontal direction recycler view
LinearLayoutManager firstlinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
firstrecyclerView.setLayoutManager(firstlinearLayoutManager);
firstrecyclerView.setItemAnimator(new DefaultItemAnimator());
for (int i = 0; i < iconName.length; i++) {
itemModel itemModel = new itemModel(iconName[i], youtubeVideoArrayList.get(i));
items.add(itemModel);
}
thirdrecyclerView=findViewById(R.id.third_recycler_view);
thirdrecyclerView.setHasFixedSize(true);
channelList=new ArrayList<>();
LinearLayoutManager thirdlinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
thirdrecyclerView.setLayoutManager(thirdlinearLayoutManager);
for (int i=0;i < channelnames.length;i++){
channel channel=new channel(channelnames[i],channelimages[i]);
channelList.add(channel);
}
}
//populate the recycler view and implement the click event here
private void populateRecyclerView() {
final CustomAdapter adapterf = new CustomAdapter(this, items);
firstrecyclerView.setAdapter(adapterf);
//set click event
firstrecyclerView.addOnItemTouchListener(new RecyclerViewOnClickListener(this, new RecyclerViewOnClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
if (youTubePlayerFragment != null && youTubePlayer != null) {
//update selected position
adapterf.setSelectedPosition(position);
//load selected video
youTubePlayer.cueVideo(youtubeVideoArrayList.get(position));
}
}
}));
channeladpater channeladpater=new channeladpater(channelList);
thirdrecyclerView.setAdapter(channeladpater);
}
//method to generate dummy array list of videos
private void generateDummyVideoList() {
youtubeVideoArrayList = new ArrayList<>();
//get the video id array from strings.xml
String[] videoIDArray = getResources().getStringArray(R.array.video_id_array);
//add all videos to array list
Collections.addAll(youtubeVideoArrayList, videoIDArray);
}
}
Now I tried to open another activity when itemview is clicked in this way;
channeladapter class;
public class channeladpater extends RecyclerView.Adapter<channeladpater.Channelviewholder> {
private List<channel> channelList;
Context ctx;
public channeladpater(List<channel> channelList) {
this.channelList=channelList;
}
#NonNull
#Override
public Channelviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view,parent,false);
return new Channelviewholder(view);
}
#Override
public void onBindViewHolder(#NonNull Channelviewholder holder, int position)
{
final channel channel=channelList.get(position);
holder.channelname.setText(channel.getChannelname());
holder.channelimage.setImageResource(channel.getChannelimage());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClickListener(View v, int position) {
final String[] channelID={"UCHJW1_0oPzYZl89wX_jhrgA","UCaT-WGdJLyEDnxZPAKRTbqQ","UCJMSoNjSKRARSIJM3GymRjQ","UCrET5fR2NAUTO2Xp12G0l8A", "UCYF_LfBBxkFBEgaSCNrqW3w"};
Intent intent=MainActivity2.newIntent(v.getContext(), channelID);
v.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return channelList.size();
}
public static class Channelviewholder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView channelname;
public CircleImageView channelimage;
ItemClickListener itemClickListener;
Channelviewholder(#NonNull View itemView) {
super(itemView);
this.channelname=itemView.findViewById(R.id.profile_name);
this.channelimage=itemView.findViewById(R.id.profile_image);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
this.itemClickListener.onItemClickListener(v,getLayoutPosition());
}
public void setItemClickListener(ItemClickListener ic){
this.itemClickListener=ic;
}
}
}
}
the new activity start is basically the list of videos fetched using youtube data api;
MainActivity2
public class MainActivity2 extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<VideoDetails> videoDetailsoArrayList;
public static String CHANNEL_ID_EXTRA = "channel_id_extra";
public static Intent newIntent(Context context, String[] channelID) {
return new Intent(context, MainActivity2.class).putExtra(CHANNEL_ID_EXTRA, channelID);
}
String API_Key = "AIzaSyA1_spJ4XGWOCekBLCsSAgWderHHl_46m0";
private String[] channelID={"UCHJW1_0oPzYZl89wX_jhrgA","UCaT-WGdJLyEDnxZPAKRTbqQ","UCJMSoNjSKRARSIJM3GymRjQ","UCrET5fR2NAUTO2Xp12G0l8A", "UCYF_LfBBxkFBEgaSCNrqW3w"};
String url="https://www.googleapis.com/youtube/v3/search?part=snippet&channelId="+ Arrays.toString(channelID) +"&maxResults=50&sort=date&key=AIzaSyA1_spJ4XGWOCekBLCsSAgWderHHl_46m0";
adapter adapter;
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
final String channelID = getIntent().getStringExtra(CHANNEL_ID_EXTRA);
recyclerView=findViewById(R.id.listView);
videoDetailsoArrayList= new ArrayList<>();
adapter=new adapter(MainActivity2.this,videoDetailsoArrayList);
displayVideos();
}
private void displayVideos ()
{
RequestQueue requestQueue= Volley.newRequestQueue(this);
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (jsonObject1.has("id")){
JSONObject jsonVideoId=jsonObject1.getJSONObject("id");
if (jsonVideoId.has("kind")){
if(jsonVideoId.getString("kind").equals("youtube#video")) {
JSONObject jsonObjectSnippet = jsonObject1.getJSONObject("snippet");
JSONObject jsonObjectDefault = jsonObjectSnippet.getJSONObject("thumbnails").getJSONObject("medium");
String video_id = jsonVideoId.getString("videoId");
VideoDetails vd = new VideoDetails();
vd.setVideoId(video_id);
vd.setTitle(jsonObjectSnippet.getString("title"));
vd.setDescription(jsonObjectSnippet.getString("description"));
vd.setUrl(jsonObjectDefault.getString("url"));
videoDetailsoArrayList.add(vd);
}
}
}
}
}catch (JSONException e) {
e.printStackTrace();
}
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapter= new adapter(getApplicationContext(),videoDetailsoArrayList);
recyclerView.setAdapter(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.getMessage(), LENGTH_LONG).show();
}
});
requestQueue.add(stringRequest);
}
Now I am trying to change the channelID from the String url of MainActivity2 such that when itemview with String channelnames "PTC Punjabi" is clicked, the MainActivity is loaded with channelID "UCHJW1_0oPzYZl89wX_jhrgA", when channelnames "Chakde Tv" is clicked, the MainActivity2 is loaded with
channelID "UCaT-WGdJLyEDnxZPAKRTbqQ" and so on. but I dont understand how to pass the list of channelId to MainActivity2?
Should I declare channelId array in MainActivity?. Please somebody guide me in this step. I know the solution is small as I have seen tutorials on button activities but I cant understand passing url to other activity.
channel model class
public class channel {
String channelname;
int channelimage;
public channel(String channelname, int channelimage) {
this.channelname = channelname;
this.channelimage = channelimage;
}
public String getChannelname() {
return channelname;
}
public int getChannelimage() {
return channelimage;
}
}
First of all: it's not a good practice to create Intent somewhere else then Activity of which intent your are creating.
So you need to add static method in your MainActivity2:
public static String CHANNEL_ID_EXTRA = "channel_id_extra";
public static Intent newIntent(Context context, String channelID) {
return new Intent(context, MainActivity2.class).putExtra(CHANNEL_ID_EXTRA, channelID);
}
After that you can get this ID in onCreate() method by :
final String channelId = getIntent().getStringExtra(CHANNEL_ID_EXTRA);
And now in Holder: EDITED HERE
#Override
public void onBindViewHolder(#NonNull Channelviewholder holder, int position) {
final channel channel=channelList.get(position);
holder.channelname.setText(channel.getChannelname());
holder.channelimage.setImageResource(channel.getChannelimage());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClickListener(View v, int position) {
final String channelID= channelList.get(position);
Intent intent=MainActivity2.newIntent(v.getContext(), channelID);
v.getContext().startActivity(intent);
}
});
}
I'm making an app that play mp3 file from phone storage using service. I have an activity that has a small view to interact with the songs and a fragment that contains a full media function to interact with the songs will be added in if I tap on the small view told. The problem is I cannot get data from service to pass in the fragment to display data or interact between fragment and service.
Here's my main activity 1st photo
Here's my fragment after touch the field on 1st photo fragment
My code in MainActivity
public class MainActivity extends AppCompatActivity {
private List<AudioModel> mainList;
private ListView mainListView;
private MusicAdapter adapter;
private int REQUEST_CODE_PERMISSION = 2703;
private MusicPlayerService musicPlayerService;
public static Intent intentService;
private boolean boundService = false;
public static TextView txtMainTen, txtMainTacGia;
private ImageButton btnMainPlay, btnMainNext;
private int vitri = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainList = new ArrayList<>();
if(intentService == null){
intentService = new Intent(this, MusicPlayerService.class);
bindService(intentService, serviceConnection, Context.BIND_AUTO_CREATE);
startService(intentService);
}
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_PERMISSION);
mainListView = findViewById(R.id.listSong);
adapter = new MusicAdapter(MainActivity.this, R.layout.item_song, mainList);
mainListView.setAdapter(adapter);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MainAudioCreate(position);
vitri = position;
}
});
txtMainTen = findViewById(R.id.txtPlaying);
txtMainTacGia = findViewById(R.id.txtAuthor);
btnMainPlay = findViewById(R.id.btnPlayBottom);
btnMainNext = findViewById(R.id.btnNextBottom);
btnMainPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (musicPlayerService.mediaPlayer.isPlaying()){
musicPlayerService.pause();
btnMainPlay.setImageResource(R.drawable.button_play);
}
else{
musicPlayerService.resume();
btnMainPlay.setImageResource(R.drawable.button_pause);
}
}
});
btnMainNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
vitri++;
if (vitri > mainList.size() - 1){
vitri = 0;
}
MainAudioCreate(vitri);
}
});
}
private void MainAudioCreate(int position){
musicPlayerService.setVitri(position);
musicPlayerService.play();
btnMainPlay.setImageResource(R.drawable.button_pause);
txtMainTen.setText(musicPlayerService.serviceList.get(position).getName());
txtMainTacGia.setText(musicPlayerService.serviceList.get(position).getArtist());
}
public void AddFragment(View view){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = null;
int container = 0;
String tag = "";
switch (view.getId()) {
case R.id.layoutClose:
fragment = new FragmentClose();
container = R.id.frameContent;
tag = "fragClose";
break;
case R.id.layoutList:
fragment = new FragmentPlaylist();
container = R.id.frameContent;
tag = "fragList";
break;
case R.id.bottomPlayerTouchable:
fragment = new FragmentPlayer();
container = R.id.mainFrame;
tag = "fragPlayer";
break;
}
fragmentTransaction.add(container, fragment, tag);
fragmentTransaction.addToBackStack("fragment");
fragmentTransaction.commit();
}
public void GetSongFromStorage(Context context, List<AudioModel> list){
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
String[] projection = {MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.TITLE,};
Cursor c = context.getContentResolver().query(uri, projection, null, null, MediaStore.Audio.Media.TITLE + " ASC");
if (c != null){
while (c.moveToNext()) {
AudioModel audioModel = new AudioModel();
String path = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
mmr.setDataSource(path);
String album = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
String artist = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
String name = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
byte[] image = mmr.getEmbeddedPicture();
String displayName = path.substring(path.lastIndexOf("/") + 1);
audioModel.setName(name);
audioModel.setAlbum(album);
audioModel.setArtist(artist);
audioModel.setPath(path);
audioModel.setDisplayname(displayName);
if (image != null) audioModel.setImgPath(image);
list.add(audioModel);
}
adapter.notifyDataSetChanged();
c.close();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_PERMISSION){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
mainList.clear();
GetSongFromStorage(MainActivity.this, mainList);
}
else{
Toast.makeText(this, "Chưa cho phép", Toast.LENGTH_SHORT).show();
}
}
}
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicPlayerService.MusicBinder binder = (MusicPlayerService.MusicBinder) service;
musicPlayerService = binder.getService();
musicPlayerService.setList(mainList);
boundService = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
boundService = false;
}
};
}
My Service code
public class MusicPlayerService extends Service {
MediaPlayer mediaPlayer;
List<AudioModel> serviceList;
int vitri;
private final IBinder musicBind = new MusicBinder();
public class MusicBinder extends Binder {
MusicPlayerService getService(){
return MusicPlayerService.this;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
#Override
public boolean onUnbind(Intent intent) {
mediaPlayer.stop();
mediaPlayer.release();
return false;
}
public void initMusicPlayer(){
mediaPlayer.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
#Override
public void onCreate() {
super.onCreate();
vitri = 0;
mediaPlayer = new MediaPlayer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void setList(List<AudioModel> mp3List){
serviceList = mp3List;
}
public void play(){
mediaPlayer.reset();
createSong();
}
public void pause(){
mediaPlayer.pause();
}
public void resume(){
mediaPlayer.start();
}
public void createSong(){
mediaPlayer = MediaPlayer.create(this, Uri.parse(serviceList.get(vitri).getPath()));
mediaPlayer.start();
}
public void setVitri(int pos){
vitri = pos;
}
}
My Fragment that will be added in code
public class FragmentPlayer extends Fragment {
ImageButton btnBackPlayer;
TextView txtTitlePlayer, txtTimeCurrent, txtTimeTotal;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_player, container, false);
btnBackPlayer = view.findViewById(R.id.btnBackPlayer);
txtTitlePlayer = view.findViewById(R.id.txtTitlePlayer);
txtTimeCurrent = view.findViewById(R.id.txt_timeCurrent);
txtTimeTotal = view.findViewById(R.id.txt_timeTotal);
view.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
btnBackPlayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().popBackStack();
}
});
return view;
}
}
You can use a broadcast in your service and set broadcast listener in your fragment.
I have been searching the internet the whole day but couldn't find the solution. I have a music player service class that plays songs in the background as a service. The problem is I can't get the fragment to bind to this service. No error is being shown in logcat nor the app crashes. When I click on one of the songs nothing happens. This is my code below:
ServiceClass:
public class MediaPlayerService extends Service implements MediaPlayer.OnCompletionListener,
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnSeekCompleteListener,
MediaPlayer.OnInfoListener, MediaPlayer.OnBufferingUpdateListener,
AudioManager.OnAudioFocusChangeListener {
private final IBinder iBinder = new LocalBinder();
private static MediaPlayer mediaPlayer = new MediaPlayer();
private String mediaFile;
private int resumePosition;
private AudioManager audioManager;
//Handle incoming phone calls
private boolean ongoingCall = false;
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
private ArrayList<SongInfoModel> songsServiceList = new ArrayList<>();
private int songPosn;
private int currentIndex ;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return iBinder;
}
private void initMediaPlayer() {
//Set up MediaPlayer event listeners
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
//Reset so that the MediaPlayer is not pointing to another data source
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
#Override
public void onCreate() {
super.onCreate();
songPosn=0;
initMediaPlayer();
}
public void setList(ArrayList<SongInfoModel> theSongs){
songsServiceList=theSongs;
}
public void setSong(int songIndex){
songPosn=songIndex;
}
public void playSong(){
//play a song
mediaPlayer.reset();
//get song
SongInfoModel playSong = songsServiceList.get(songPosn);
//get id
long currSong = playSong.getSongID();
//set uri
Uri trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
currSong);
try{
mediaPlayer.setDataSource(getApplicationContext(), trackUri);
}
catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
mediaPlayer.prepareAsync();
MainActivity.handleSeekbar(mediaPlayer);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.reset();
songPosn++;
if(songPosn>=songsServiceList.size()) songPosn=0;
playSong();
}
#Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
return false;
}
#Override
public boolean onInfo(MediaPlayer mediaPlayer, int i, int i1) {
return false;
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.reset();
} else {
mediaPlayer.start();
MainActivity.Handler(mediaPlayer);
}
}
public class LocalBinder extends Binder {
public MediaPlayerService getService() {
return MediaPlayerService.this;
}
}
FragmentClass:
public class Songs extends Fragment {
public static final String TAG = "Songs";
RecyclerView recyclerView;
private ArrayList<SongInfoModel> SongList = new ArrayList<SongInfoModel>();
SongAdapter songAdapter;
ScaleInAnimationAdapter alphaAdapter;
private MediaPlayerService player2;
boolean serviceBound2 = false;
private Intent playIntent2;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.songs_activity, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(linearLayoutManager);
songAdapter = new SongAdapter(getContext(), SongList, new SongAdapter.RecyclerItemClickListener() {
#Override
public void onClickListener(SongInfoModel song, int position) {
Toast.makeText(getContext(), song.getSongName(), Toast.LENGTH_SHORT).show();
MainActivity.setsongText(song);
MainActivity.ButtonPlay();
MainActivity.PauseImage();
if(serviceBound2 == true) {
player2.setSong(position);
player2.playSong();
}
}
#Override
public void onLongClickListener(SongInfoModel song, int position) {
Toast.makeText(getContext(), "You long clicked me, thank you!", Toast.LENGTH_SHORT).show();
}
});
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";
Cursor cursor = getActivity().getContentResolver().query(uri, null, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
Long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
Long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, albumId);
SongInfoModel s = new SongInfoModel(id, name, artist, null, null, null, duration, data,albumArtUri, albumId);
SongList.add(s);
} while (cursor.moveToNext());
}
cursor.close();
Collections.sort(SongList, new Comparator<SongInfoModel>() {
#Override
public int compare(SongInfoModel lhs, SongInfoModel rhs) {
return lhs.getSongName().compareTo(rhs.getSongName());
}
});
}
alphaAdapter = new ScaleInAnimationAdapter(songAdapter);
alphaAdapter.setDuration(1000);
alphaAdapter.setInterpolator(new OvershootInterpolator());
alphaAdapter.setFirstOnly(false);
recyclerView.setAdapter(alphaAdapter);
songAdapter.notifyDataSetChanged();
return view;
}
//Binding this Client to the AudioPlayer Service
private ServiceConnection serviceConnection2 = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
player2 = binder.getService();
player2.setList(SongList);
serviceBound2 = true;
Toast.makeText(getContext(), "Service Bound", Toast.LENGTH_SHORT).show();
}
#Override
public void onServiceDisconnected(ComponentName name) {
serviceBound2 = false;
}
};
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(playIntent2==null && serviceBound2==true){
playIntent2 = new Intent(getActivity(), MediaPlayerService.class);
getActivity().bindService(playIntent2, serviceConnection2, Context.BIND_AUTO_CREATE);
getActivity().startService(playIntent2);
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to parse an rss feed and since i'm a beginner in android i cannot find a way to do this through a fragment..
This is the activity i want to convert into a fragment
public class Clients extends Activity {
private Clients local;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
local = this;
GetRSSDataTask task = new GetRSSDataTask();
task.execute("http://www.itcuties.com/feed/");
Log.d("ITCRssReader", Thread.currentThread().getName());
}
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(String... urls) {
Log.d("ITCRssReader", Thread.currentThread().getName());
try {
RssReader rssReader = new RssReader(urls[0]);
return rssReader.getItems();
} catch (Exception e) {
Log.e("ITCRssReader", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
ListView itcItems = (ListView) findViewById(R.id.listView);
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(local,android.R.layout.simple_list_item_1,result);
itcItems.setAdapter(adapter);
itcItems.setOnItemClickListener(new ListListener(result, local));
}
}
}
I already have tried to convert it but the onItemClick is getting some errors.
public void onItemClick(AdapterView parent, View view, int pos, long id) {
Intent intent = new Intent(activity, Clients.class);
intent.putExtra("description", listItems.get(pos).getLink());
activity.startActivity(intent);
}
Can someone please help me???
You should call the fragment without ui. It is needed to add ui, but not to make it visible.
public class MyFragmet extends Fragment {
public static final String TAG = "MyFragmet";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.MY_FRAGMENT_NULL_VIEW,
container, false);
local = this;
GetRSSDataTask task = new GetRSSDataTask();
task.execute("http://www.itcuties.com/feed/");
Log.d("ITCRssReader", Thread.currentThread().getName());
return view;
}
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(String... urls) {
Log.d("ITCRssReader", Thread.currentThread().getName());
try {
RssReader rssReader = new RssReader(urls[0]);
return rssReader.getItems();
} catch (Exception e) {
Log.e("ITCRssReader", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
Intent intent = new Intent();
intent.setAction(TAG ); // also here you can add other information
sendBroadcast(intent);
}
}
}
and add this to activity
private BroadcastReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ListView itcItems = (ListView) findViewById(R.id.listView);
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(local,android.R.layout.simple_list_item_1,result);
itcItems.setAdapter(adapter);
itcItems.setOnItemClickListener(new ListListener(result, local));
}
};
registerReceiver(receiver, new IntentFilter(MyFragmet.TAG));
FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentByTag(MyFragmet.TAG);
if (fragment == null) {
getFragmentManager()
.beginTransaction()
.add(R.id.fragment, new MyFragmet(),MyFragmet.TAG)
.commit();
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
Ok, here's my attempt:
I've replaced your ArrayAdapter with a baseadapter (finer tuned control over what happens with your items) - define a layout similiar to the list item you have in your ArrayAdapter, point the BaseAdapter at it, and set up the views within the onCreateView block.
Other than that, I think it should drop in pretty well.
public class Clients extends Fragment implents ListView.OnItemClickListener {
private Clients local;
private ListView itcItems;
private RssItemBaseAdapter adapter;
private ArrayList<Rssitem> itemList = new ArrayList<RssItem>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
local = this;
GetRSSDataTask task = new GetRSSDataTask();
task.execute("http://www.itcuties.com/feed/");
Log.d("ITCRssReader", Thread.currentThread().getName());
}
#Override
public void onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
view rootView = infalter.inflate(R.layout.activity_my,container,false);
itcItems = (ListView)findViewById(R.id.listView);
itcItems.setOnItemClickListener(this);
adapter = new RssItemBaseAdapter(getActivity(),itemList);
itcItems.setAdapter(adapter);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i , long l){
RssItem item = adapter.getItem(i);
<Handle your Intent code here>
}
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(String... urls) {
Log.d("ITCRssReader", Thread.currentThread().getName());
try {
RssReader rssReader = new RssReader(urls[0]);
return rssReader.getItems();
} catch (Exception e) {
Log.e("ITCRssReader", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
itemList = result;
adapter.swapList(itemList);
adapter.notifyDataSetChanged();
}
}
private class RssItemBaseAdapter extends BaseAdapter(){
private Context mContext;
private ArrayList<RssItem> mRssList;
public RssItemBaseAdapter(Context context, ArrayList<RssItem> obj){
mContext = context;
mRssList = obj;
}
#Override
public int getCount() {return mRssList.size(); }
#Override
public RssItem getItem(int i) {return mRssList.get(i); }
#Override
public long getItemId(int i) { return i }
#Override
public view getView(int i, View convertView, ViewGroup parent){
View rootView = convertView;
if (rootView == null){
View rootView = Inflater.from(mContext).inflate(R.layout.YOUR_SIMPLE_LAYOUT_HERE,parent,false);
}
<do your view setting here>
return rootView;
}
public ArrayList<RssItem> swapList (ArrayList<RssItem> newList){
ArrayList<RssItem> oldList = mRssList;
mRssList = newList;
return oldList;
}
}
}
I am creating a music player app for android. I have a fragment in a ViewPager that displays a list of all songs on the device. I have implemented an onClick listener on the list item to start a service called PlayerService that will play the clicked music. However, I am getting a
NullPointerException
at the line
playerSrv.setList(songArray);
in the following code.
I can pass the songArray ArrayList to the listview adapter without any problem but when I try to pass it to the service, I get the error. Is there any reason why the songArray could be null? The service starts without any problem without the line that gives error.
The setList() method in the Service class is
public void setList(ArrayList<Song> theSongs) {
songs=theSongs; //where songs is a private variable of type ArrayList<Song>
}
public class AllSongsFragment extends Fragment {
private ArrayList<Song> songArray;
private ListView songListView;
private PlayerService playerSrv;
private Intent playIntent;
private boolean serviceBound=false;
//connect to the player service
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
ServiceBinder binder = (ServiceBinder)service;
//get service
playerSrv = binder.getService();
serviceBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
serviceBound = false;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
} // onCreate()
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
songListView = (ListView)getView().findViewById(R.id.all_songs_list);
songArray = new ArrayList<Song>();
getSongList();
// Sort the songs
Collections.sort(songArray, new Comparator<Song>() {
public int compare(Song a, Song b) {
// For case-insensitive sorting
String a1 = a.getTitle().toString().toLowerCase();
String b1 = b.getTitle().toString().toLowerCase();
return a1.compareTo(b1);
}
});
AllSongsAdapter songAdt = new AllSongsAdapter(getActivity(), songArray);
songListView.setAdapter(songAdt);
songListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(playIntent==null) {
playIntent = new Intent(getActivity(), PlayerService.class);
getActivity().bindService(playIntent, serviceConnection, Context.BIND_AUTO_CREATE);
getActivity().startService(playIntent);
}
//pass list
playerSrv.setList(songArray); //ERROR AT THIS LINE
playerSrv.setSong(position);
playerSrv.playSong();
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.all_songs_fragment_layout, container, false);
return rootView;
} //onCreateView()
/*#Override
public void onPause() {
getActivity().stopService(playIntent);
//playerSrv=null;
super.onPause();
}*/
public void getSongList() {
//retrieve song info
ContentResolver musicResolver = getActivity().getContentResolver();
Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] projection = new String[] {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST};
Cursor musicCursor = musicResolver.query(musicUri, projection, null, null, null);
// Iterate over the List
if(musicCursor!=null && musicCursor.moveToFirst()) {
//get columns
int idColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media._ID);
int titleColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int artistColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
String thisId = musicCursor.getString(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
if(thisArtist == null || thisArtist.equals(MediaStore.UNKNOWN_STRING)) {
thisArtist = "Unknown Artist";
}
songArray.add(new Song(thisId, thisTitle, thisArtist));
} while (musicCursor.moveToNext());
} // if
} //getSongList()
} //AllSongsFragment
The service class is
public class PlayerService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener {
private MediaPlayer player;
private ArrayList<Song> songs;
private int songPosition;
private final IBinder serviceBind = new ServiceBinder();
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return serviceBind;
}
#Override
public boolean onUnbind(Intent intent) {
player.stop();
player.release();
return false;
}
#Override
public void onCreate() {
super.onCreate();
//initialize position
songPosition=0;
//create player
player = new MediaPlayer();
initMusicPlayer();
}
public void initMusicPlayer() {
//set player properties
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void setList(ArrayList<Song> theSongs) {
// Used to pass music list from music browser to the Player Service
songs=theSongs;
}
public class ServiceBinder extends Binder {
PlayerService getService() {
return PlayerService.this;
}
}
public void playSong() {
//play a song
player.reset();
//get song
Song currentSong = songs.get(songPosition);
//get id
long songId = Long.parseLong(currentSong.getId());
//set uri
Uri trackUri = ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, songId);
try {
player.setDataSource(getApplicationContext(), trackUri);
} catch(Exception e) {
Log.e("PLAYER SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
#Override
public void onPrepared(MediaPlayer mp) { //start playback
mp.start();
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
}
public void setSong(int songIndex) {
songPosition=songIndex;
}
}