How to avoid multiple instances of MediaPlayer objects? - android

I'm devolping an music player application, when user click on an item (song) in the listview in PlayListFragment user redirects to the mediaPlayerFragment and the choosen melody starts to play. When user repeat the scenario i think that a new instance of mediaPlayer is created because there is two melodys playing at the same time.
How to avoid this problem?
(I have tried to place mediaPlayer.create(..) in onCreate() but there is probably something more that is need to be done to make it work correctly. I have also tried to create a singletonObject without success)
MediaPlayerFragment.java
public class MediaPlayerFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private MediaPlayer mediaPlayer;
private double endTime = 0;
private double startTime = 0;
private int forwardTime = 5000;
private int backwardTime = 5000;
public static int oneTimeOnly = 0;
private SeekBar seekBar;
private ImageButton btnPlay;
private ImageButton btnPause;
private ImageButton btnStop;
private ImageButton btnForward;
private ImageButton btnRewind;
public TextView songInfo;
public TextView txtEndTime;
public TextView txtStartTime;
private Handler mediaHandler = new Handler();
private boolean isPausePressed = false;
private boolean isPlayPressed = false;
private boolean isStopPressed = true;
private OnFragmentInteractionListener mListener;
private Song currentSong;
public static MediaPlayerFragment newInstance(String param1, String param2) {
MediaPlayerFragment fragment = new MediaPlayerFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public MediaPlayerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_media_player, container, false);
getActivity().setTitle("Media Player");
songInfo = (TextView)view.findViewById(R.id.txt_currentsong);
txtEndTime = (TextView)view.findViewById(R.id.txt_time_left);
txtStartTime = (TextView)view.findViewById(R.id.txt_time_start);
seekBar = (SeekBar)view.findViewById(R.id.seek_bar_elapsed_time);
btnPlay = (ImageButton)view.findViewById(R.id.btn_play);
btnPause = (ImageButton)view.findViewById(R.id.btn_pause);
btnStop = (ImageButton)view.findViewById(R.id.btn_stop);
btnRewind = (ImageButton)view.findViewById(R.id.btn_previous);
btnForward = (ImageButton)view.findViewById(R.id.btn_next);
songInfo.setText(currentSong.getArtist() + " - " + currentSong.getTitle());
mediaPlayer = MediaPlayer.create(getActivity(), Uri.parse(currentSong.getUri()));
seekBar.setClickable(false);
btnPause.setEnabled(false);
btnStop.setEnabled(false);
btnForward.setEnabled(false);
btnRewind.setEnabled(false);
//Click events!
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pause(view);
isPausePressed = true;
isPlayPressed = false;
isStopPressed = false;
}
});
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play(view);
isPausePressed = false;
isPlayPressed = true;
isStopPressed = false;
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stop(view);
isPausePressed = false;
isPlayPressed = false;
isStopPressed = true;
}
});
btnForward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
forward(view);
isPausePressed = false;
isPlayPressed = false;
isStopPressed = false;
}
});
btnRewind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rewind(view);
isPausePressed = false;
isPlayPressed = false;
isStopPressed = false;
}
});
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStartTrackingTouch(SeekBar s) {
}
#Override
public void onStopTrackingTouch(SeekBar s) {
}
#Override
public void onProgressChanged(SeekBar s, int progress, boolean fromUser) {
if (mediaPlayer != null && fromUser) {
mediaPlayer.seekTo(progress);
// Check if pause, play or stop buttons is pressed
if(!isPausePressed && !isPlayPressed && !isStopPressed) {
play(view);
}
}
}
});
return view;
}
public void play(View view) {
//Check if a track has been choosen from playlist...
if(currentSong.getId() != null) {
mediaPlayer.start();
endTime = mediaPlayer.getDuration();
startTime = mediaPlayer.getCurrentPosition();
if (oneTimeOnly == 0) {
seekBar.setMax((int) endTime);
oneTimeOnly = 1;
}
txtEndTime.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes((long) endTime),
TimeUnit.MILLISECONDS.toSeconds((long) endTime) -
TimeUnit.MILLISECONDS.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) endTime)))
);
txtStartTime.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes((long) startTime),
TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime)))
);
seekBar.setProgress((int) startTime);
mediaHandler.postDelayed(UpdateSongTime, 100);
btnPause.setEnabled(true);
btnStop.setEnabled(true);
btnRewind.setEnabled(true);
btnForward.setEnabled(true);
}
}
private Runnable UpdateSongTime = new Runnable() {
public void run() {
startTime = mediaPlayer.getCurrentPosition();
txtStartTime.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes((long) startTime),
TimeUnit.MILLISECONDS.toSeconds((long) startTime),
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime)))
);
seekBar.setProgress((int) startTime);
mediaHandler.postDelayed(this, 100);
}
};
public void stop(View view) {
btnPause.setEnabled(false);
btnForward.setEnabled(false);
btnRewind.setEnabled(false);
btnStop.setEnabled(false);
mediaPlayer.pause();
mediaPlayer.seekTo(0);
}
public void pause(View view) {
mediaPlayer.pause();
btnPause.setEnabled(false);
btnPlay.setEnabled(true);
}
public void forward(View view) {
int temp = (int)startTime;
if ((temp + forwardTime)<= endTime) {
startTime = startTime + forwardTime;
mediaPlayer.seekTo((int) startTime);
}
}
public void rewind(View view) {
int temp = (int) startTime;
if ((temp-backwardTime)> 0) {
startTime = startTime - backwardTime;
mediaPlayer.seekTo((int)startTime);
}
}
public void setSong(Song song) {
this.currentSong = song;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
PlayListFragment.java
public class PlayListFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private PlayListAdapter playListAdapter;
private ListView lstPlayList;
public static ArrayList<Song> storeSongs = new ArrayList<>();
private OnFragmentInteractionListener mListener;
public static PlayListFragment newInstance(String param1, String param2) {
PlayListFragment fragment = new PlayListFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public PlayListFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_play_list, container, false);
getActivity().setTitle("Play List");
getSongList();
sort(storeSongs);
AddToListView(view);
lstPlayList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Song song = new Song();
//Get clicked song from listview.
song = (Song) parent.getAdapter().getItem(position);
changeToMediaPlayerFragment(song);
}
});
return view;
}
private void getSongList() {
ContentResolver musicResolver = getActivity().getContentResolver();
Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if (musicCursor != null && musicCursor.moveToFirst()) {
//get columns
int titleColumns = musicCursor.getColumnIndex( MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
int uriColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.DATA);
//Add songs to container (storeSongs).
do {
Long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumns);
String thisArtist = musicCursor.getString(artistColumn);
String thisUri = musicCursor.getString(uriColumn);
storeSongs.add(new Song(thisId, thisTitle, thisArtist, thisUri));
} while (musicCursor.moveToNext());
}
}
public void changeToMediaPlayerFragment(Song song) {
MediaPlayerFragment mediaPlayerFragment = MediaPlayerFragment.newInstance("", "");
mediaPlayerFragment.setSong(song);
FragmentManager fM = getFragmentManager();
FragmentTransaction fT = fM.beginTransaction();
fT.replace(R.id.container, mediaPlayerFragment, null);
fT.addToBackStack("go to mediaPlayer fragmement");
fT.commit();
}
private void AddToListView(View view) {
if (playListAdapter == null) {
playListAdapter = new PlayListAdapter(getActivity(), storeSongs);
}
this.lstPlayList = (ListView) view.findViewById(R.id.listView_play_list);
lstPlayList.setAdapter(playListAdapter);
playListAdapter.notifyDataSetChanged();
}
private void sort(ArrayList<Song> songs) {
Collections.sort(songs, new Comparator<Song>() {
#Override
public int compare(Song lhs, Song rhs) {
return lhs.getArtist().compareTo(rhs.getArtist());
}
});
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}

As Dyrborg pointed out i have now made the activity responsible for holding one reference to PlayListFragment and one reference of the MediaPlayerFragment.
public void changeToPlayListFragment() {
if (playListFragment == null) {
playListFragment = PlayListFragment.newInstance("", "");
}
if (getCurrentFragment() == 2) {
return;
} else {
FragmentManager fME = getFragmentManager();
FragmentTransaction fTE = fME.beginTransaction();
fTE.replace(R.id.container, playListFragment, null);
fTE.addToBackStack("go to Playlist fragment");
fTE.commit();
}
}
private int getCurrentFragment() {
Fragment currentFragment = getFragmentManager().findFragmentById(R.id.container);
if (currentFragment instanceof MediaPlayerFragment) {
return 1;
} else if (currentFragment instanceof PlayListFragment) {
return 2;
} else {
return 0;
}
}
Link contains all java code for a simple light weight media player with knocking interaction "http://pastebin.com/BHVZYLGv"

Related

How to pass mediaplayer data from service to fragment in android

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.

Hello, please tell me how to send ArrayList to another activity

I tried all the possible options that I just found.
I can’t send ArrayList to another activity via the Parcelable interface.
To implement a media player
String format information it sends.
I would be very grateful, maybe there are some other options. This is the first time I'm asking a question here
Here is my activity that I use to send, the code is still very raw
public class MainActivity extends AppCompatActivity {
ScheduledExecutorService scheduledExecutorService;
public MediaPlayer mediaPlayer;
private SeekBar seekBar;
private ImageView btn_Play;
private ImageView btn_Next;
private ImageView btn_Pre;
private TextView setCurrentDuration, setTotalDuration;
private ArrayList<SoundInfo> audioList = new ArrayList<>();
SoundAdapter adapter = new SoundAdapter();
public Handler handler = new Handler();
AudioEffect audioEffect;
private int currentPosition = 0;
private SoundInfo soundInfo = new SoundInfo(this);
SoundEffects soundEffects;
boolean mediaPauseStat = false;
Context context;
PageFragmentOne pageFragmentOne;
//public MainActivity(PageFragmentOne pageFragmentOne) {
// this.pageFragmentOne = pageFragmentOne;
//}
MediaManager mediaManager = new MediaManager(this, adapter, audioList);
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Старт сервиса
//Intent i = new Intent(this, MediaPlaybackService.class);
//i.putExtra("play", "письмо от главного активити");
//startService(i);
//mediaManager.LoadSounds();
/**
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
**/
////////////////////////////////////////////////////////////////////////////////////////////
setCurrentDuration = findViewById(R.id.current_Duration);
setTotalDuration = findViewById(R.id.total_Duration);
seekBar = findViewById(R.id.seekBar);
RecyclerView list = findViewById(R.id.my_recycler_view);
list.setAdapter(adapter);
list.setLayoutManager(new LinearLayoutManager(this));
// Оформление отображения адаптера
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, LinearLayout.VERTICAL);
dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.list_item_divider, null));
list.addItemDecoration(dividerItemDecoration);
///////////////////////////////////////////////
soundInfo.setMassive(audioList);
adapter.setOnItemClickListener(new SoundAdapter.OnItemClickListener() {
#Override
public void onClick(View v, final SoundInfo obj, final int position, final ImageView onNext) {
final SoundInfo path = audioList.get(position);
String audioPath = obj.getData();
prepareMedia(position);
// Задаем текующию позицию трека
currentPosition = position;
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
mediaPlayer.start();
// Всегда должен быть после старта плеера, что бы не вылазило 238
updateProgressBar();
//seekBar.setProgress(0);
seekBar.setMax(mediaPlayer.getDuration());
btn_Play.setImageResource(R.drawable.btn_pause);
}
});
// Перемотка аудио
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// Слишком часто обновляет
}
#Override
public void onStartTrackingTouch(final SeekBar seekBar) {
if (mediaPlayer != null) {
soundInfo.setMediaPauseStat(false);
soundInfo.setMediaRewind(false);
mediaPlayer.pause();
seekBar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
mediaPlayer.seekTo(seekBar.getProgress());
return false;
}
});
}
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mediaPlayer != null) {
soundInfo.setMediaPauseStat(true);
//soundInfo.setMediaRewind(true);
mediaPlayer.start();
}
}
});
// Кнопка проигрывания и паузы
btn_Play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!mediaPlayer.isPlaying()) {
onPlay();
} else {
onPaused();
}
}
});
// Следующий трек
btn_Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onNext();
}
});
// Предыдущий трек
btn_Pre.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onPre();
}
});
}
});
init();
}
private MyBroadcastReceiver myReceiver;
#Override
public void onResume() {
super.onResume();
myReceiver = new MyBroadcastReceiver();
final IntentFilter intentFilter = new IntentFilter("YourAction");
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, intentFilter);
}
#Override
public void onPause() {
super.onPause();
if (myReceiver != null)
LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
myReceiver = null;
}
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// String yourValue = b.getString("ser");
Bundle bundle = intent.getExtras();
}
}
public void onMainMediaPlayList(View view) {
final Intent intent2 = new Intent(getApplicationContext(), MainMediaPlayList.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("MEDIA_MASSIVE", audioList);
intent2.putExtras(bundle);
startActivity(intent2);
//Intent i = new Intent(MainActivity.this, MediaPlaybackService.class);
//startService(i);
////////////////////////////////////////////////////////////////////////////////////////////
}
public void init() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Разрешение не предоставляется
// Должны ли мы показать объяснение?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Показать объяснение пользователю * асинхронно* -- не блокировать
// этот поток ждет ответа пользователя! После пользователя
// увидев объяснение, попробуйте еще раз запросить разрешение.
} else {
// Никаких объяснений не требуется; запросить разрешение
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.MODIFY_AUDIO_SETTINGS,
Manifest.permission.RECORD_AUDIO},
101);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS является
// app-определенная константа int. Метод обратного вызова получает
// результат запроса.
}
} else {
// Разрешение уже предоставлено
//loadSounds();
mediaManager.LoadSounds();
}
//bPlayPause = findViewById(R.id.bPlayPause);
//lv = (ListView) findViewById(R.id.lvPlayList);
btn_Play = findViewById(R.id.btn_Play);
btn_Next = findViewById(R.id.btn_Next);
btn_Pre = findViewById(R.id.btn_Pre);
}
Here is my SoundInfo
public class SoundInfo implements Parcelable {
private String data, artist, title;
private Context context;
private String pathData;
public SoundInfo(MainActivity context) {
this.context = context;
}
public SoundInfo() {
}
public SoundInfo(MainMediaPlayList context) {
this.context = context;
}
public SoundInfo(MediaPlaybackService mediaPlaybackService, String star) {
this.context = mediaPlaybackService;
this.star = star;
}
protected SoundInfo(Parcel in) {
data = in.readString();
artist = in.readString();
title = in.readString();
pathData = in.readString();
mediaPauseStat = in.readByte() != 0;
ismediaRewind = in.readByte() != 0;
audioList = in.createTypedArrayList(SoundInfo.CREATOR);
star = in.readString();
}
public static final Creator<SoundInfo> CREATOR = new Creator<SoundInfo>() {
#Override
public SoundInfo createFromParcel(Parcel in) {
return new SoundInfo(in);
}
#Override
public SoundInfo[] newArray(int size) {
return new SoundInfo[size];
}
};
public void SoundInfo(String data, String artist, String title) {
this.data = data;
this.artist = artist;
this.title = title;
}
public SoundInfo(String data, String artist, String title) {
this.data = data;
this.artist = artist;
this.title = title;
}
public String getData() {
return data;
}
public String getArtist() {
return artist;
}
public String getTitle() {
return title;
}
public void setData(String artist) {
this.data = data;
}
public void setArtist(String artist) {
this.artist = artist;
}
public void setTitle(String title) {
this.title = title;
}
public void setpathData(String pathData) {
this.pathData = pathData;
}
public String getpathData() {
return pathData;
}
// Запись в память для отображения времени
boolean mediaPauseStat = true;
boolean ismediaRewind = true;
public void setMediaPauseStat(boolean mediaPauseStat) {
this.mediaPauseStat = mediaPauseStat;
}
public boolean getMediaPauseStat() {
return mediaPauseStat;
}
public void setMediaRewind(boolean isMediaRewind) {
this.ismediaRewind = ismediaRewind;
}
public boolean getMediaRewind() {
return ismediaRewind;
}
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
// Массив
private ArrayList<SoundInfo> audioList = new ArrayList<SoundInfo>();
public ArrayList<SoundInfo> getMassive() {
return audioList;
}
public void setMassive(ArrayList<SoundInfo> audioList) {
this.audioList = audioList;
}
private String star;
public String getStar() {
return star;
}
public void setStar(String star) {
this.star = star;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(data);
dest.writeString(artist);
dest.writeString(title);
dest.writeString(pathData);
dest.writeByte((byte) (mediaPauseStat ? 1 : 0));
dest.writeByte((byte) (ismediaRewind ? 1 : 0));
dest.writeTypedList(audioList);
dest.writeString(star);
}
}
Here is my adater which I use
public class SoundAdapter extends RecyclerView.Adapter<SoundAdapter.ViewHolder> {
private ArrayList<SoundInfo> audioList = new ArrayList<SoundInfo>();
Context context;
//private String[] items;
private OnItemClickListener onItemClickListener;
public void setItems(Context context, ArrayList<SoundInfo> audioList) {
this.context = context;
this.audioList = audioList;
//audioList.addAll(items);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_audio, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.bind(audioList.get(position));
holder.clickFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final SoundInfo path = audioList.get(position);
onItemClickListener.onClick(view, path, position, holder.onNext);
}
});
}
#Override
public int getItemCount() {
return audioList == null ? 0 : audioList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
private TextView data, title, artist;
private ImageView onNext;
private View clickFile;
ViewHolder(View view) {
super(view);
title = view.findViewById(R.id.tvSoundTitle);
artist = view.findViewById(R.id.tvSoundArtist);
clickFile = view.findViewById(R.id.clickFile);
//data = view.findViewById(R.id.item_title);
//onNext = view.findViewById(R.id.imageNext);
}
public void bind(SoundInfo soundInfo) {
title.setText(soundInfo.getTitle());
artist.setText(soundInfo.getArtist());
//clickFile.setText(soundInfo.getData());
}
}
// Передача данных в основной активити
public interface OnItemClickListener {
void onClick(View view, SoundInfo obj, int position, ImageView onNext);
}
}
Here is the second activity that an ArrayList gets.
Bundle bundle = getIntent().getExtras();
ArrayList<SoundInfo> audioList = bundle.getParcelableArrayList("MEDIA_MASSIVE");
adapter.setItems(MainMediaPlayList.this, audioList);
adapter.notifyDataSetChanged();
// загрузка адаптера
RecyclerView list = findViewById(R.id.my_recycler_view);
list.setAdapter(adapter);
list.setLayoutManager(new LinearLayoutManager(MainMediaPlayList.this));
When you open a new activity, the application crashes
does not display any errors in the log, the problem is as I understand that intent can not find
audioList as it seems to me
If I remove the method everything loads
public void onMainMediaPlayList(View view) {
final Intent intent2 = new Intent(getApplicationContext(), MainMediaPlayList.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("MEDIA_MASSIVE", audioList);
intent2.putExtras(bundle);
startActivity(intent2);
Here I took off the launch log, it may somehow help
2020-03-08 18:09:43.406 15730-15730/com.shimmer.myapplication W/r.myapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2020-03-08 18:09:43.406 15730-15730/com.shimmer.myapplication W/r.myapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2020-03-08 18:09:43.431 15730-15730/com.shimmer.myapplication I/OverScrollerOptimization: start init SmartSlideOverScroller and get the overscroller config
2020-03-08 18:09:43.431 15730-15730/com.shimmer.myapplication I/OverScrollerOptimization: get the overscroller config
2020-03-08 18:09:43.466 15730-15730/com.shimmer.myapplication D/HwFrameworkSecurityPartsFactory: HwFrameworkSecurityPartsFactory in.
2020-03-08 18:09:43.466 15730-15730/com.shimmer.myapplication I/HwFrameworkSecurityPartsFactory: add HwFrameworkSecurityPartsFactory to memory.
2020-03-08 18:09:43.506 15730-15730/com.shimmer.myapplication D/ActivityThread: add activity client record, r= ActivityRecord{e3185e4 token=android.os.BinderProxy#837d3d7 {com.shimmer.myapplication/com.shimmer.myapplication.MainActivity}} token= android.os.BinderProxy#837d3d7
I don't think so, You can send an ArrayList like this.
I recommend you sending Class instead of sending an Arraylist.
So, just create a class like AudiolistHolder and put your ArrayList inside this class and don't forget to implement Parcelable interface for this class, too, and send this class between activities this should solve your problem. I always use this way.
EDIT:
You can use this to send your data
Intent intent2 = new Intent(this, MainMediaPlayList.class);
MassiveAudioList m = new MassiveAudioList(audioList);
intent2.putExtra("MEDIA_MASSIVE”, m);
startActivity(intent2);
and you can use this in your second activity to retrieve data
MassiveAudioList massiveAudio=getIntent().getParcelableExtra("MEDIA_MASSIVE");
ArrayList<SoundInfo> audioList = massiveAudio.getMassiveAudioList();
Have you tried like this with arraylist
I think it can be,
In MainActivity.java
ArrayList<String> audioList= new ArrayList<>();
audioList.add("ChipThrills");
Intent i = new Intent(MainActivity.this, Secondactivity.class);
i.putExtra("Musickey", audioList);
startActivity(i);
In SecondActivity.java
ArrayList<String> audioList = (ArrayList<String>) getIntent().getSerializableExtra("Musickey");
I am writing to you here because I did not understand how to add code to the comment
And how do I extract data by adding it to an array. If of course I did the right thing, I'm new to this field. Thanks.
public class MassiveAudioList implements Parcelable {
private ArrayList<SoundInfo> audioList = new ArrayList<>();
private Context context;
public MassiveAudioList(Context context) {
this.context = context;
}
public MassiveAudioList(ArrayList audioList) {
this.audioList = audioList;
}
protected MassiveAudioList(Parcel in) {
audioList = in.createTypedArrayList(SoundInfo.CREATOR);
}
public static final Creator<MassiveAudioList> CREATOR = new Creator<MassiveAudioList>() {
#Override
public MassiveAudioList createFromParcel(Parcel in) {
return new MassiveAudioList(in);
}
#Override
public MassiveAudioList[] newArray(int size) {
return new MassiveAudioList[size];
}
};
public ArrayList<SoundInfo> getMassiveAudioList() {
return audioList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(audioList);
}
}
public void onMainMediaPlayList(View view) {
Log.d("TAG", "soundinfo" + soundInfo.getData());
final Intent intent2 = new Intent(getApplicationContext(), MainMediaPlayList.class);
massiveAudioList = new MassiveAudioList(this);
MassiveAudioList m = new MassiveAudioList(audioList);
Bundle bundle = new Bundle();
bundle.putParcelable("MEDIA_MASSIVE", m);
intent2.putExtras(bundle);
startActivity(intent2);
}

How to update textview of viewpager adpater's fragment which inside the fragment?

I need to update the textview which is inside view pager adpater's fragment
I have 2 fragments inside viewpager adapter.
and adapter itself is within the fragment.
Main fragment is initialize from MainActivity.
I used Greenrobot approach.for updating textview values on runtime.i get that value but UI is flickering means not getting good UI.
So Shall i used another approach please suggest me.
Adapter Code:-
public class SamplePagerAdapter extends FragmentPagerAdapter {
private final Random random = new Random();
private int mSize = 2;
private int heart_rate;
FragmentManager fm;
public SamplePagerAdapter(FragmentActivity activity, FragmentManager supportFragmentManager, int heart) {
super(supportFragmentManager);
fm = supportFragmentManager;
heart_rate = heart;
}
#Override
public int getCount() {
return mSize;
}
#Override
public Fragment getItem(int position) {
Fragment f = null;
if (position == 0) {
f = new MyFragment();
} else if (position == 1) {
f = new SecondFragment();
}
return f;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
fm.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
return true;
}
return false;
}
}
//code for loading main Fragment:-MeasureFragment
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
Bundle bundle = new Bundle();
bundle.putString("ble_address",bleAddress);
fragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container,fragment)
.addToBackStack(null)
.commit();
return true;
}
return false;
}
//also add measure fragment code:-
public class MeasureFragment extends Fragment implements ISmctAlgoCallback, IBleOperateCallback {
protected boolean measureSwitch = false;
private EcgAlgo ecgAlgo;
private BluetoothLeService mBluetoothLeService;
protected ProgressDialog mProgressDialog;
protected boolean isContecting = false;
private TextView btn_start;
private TextView tv_heartrate, tv_time, tv_pauseorresume;
private RelativeLayout linear, linear1;
private LinearLayout linear_pause, linear_stop;
private CountDownTimer timer;
private int count = 0;
private boolean running;
private Handler handler;
Runnable runnable;
ImageView iv_pauseorresume;
private boolean onclick = true;
private boolean isstop = false;
private String bleAddress;
View view1, view2, view3, view4, view5;
TextView tv_toolbar_title, tv_alarm_setting, tv_battery_percentage;
private int heart_rate;
SamplePagerAdapter samplePagerAdapter;
private FragmentActivity myContext;
ViewPager viewpager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_measure, container, false);
bleAddress = getArguments().getString("ble_address");
viewpager = (ViewPager) view.findViewById(R.id.viewpager);
CircleIndicator indicator = (CircleIndicator) view.findViewById(R.id.indicator);
btn_start = (TextView) view.findViewById(R.id.btn_start);
linear = (RelativeLayout) view.findViewById(R.id.linear);
linear1 = (RelativeLayout) view.findViewById(R.id.linear1);
linear_pause = (LinearLayout) view.findViewById(R.id.linear_pause);
linear_stop = (LinearLayout) view.findViewById(R.id.linear_stop);
tv_heartrate = (TextView) view.findViewById(R.id.tv_heart_rate);
tv_toolbar_title = (TextView) view.findViewById(R.id.tv_toolbar_title);
tv_alarm_setting = (TextView) view.findViewById(R.id.tv_alarm_setting);
tv_battery_percentage = (TextView) view.findViewById(R.id.tv_battery_percentage);
view1 = (View) view.findViewById(R.id.view1);
view2 = (View) view.findViewById(R.id.view2);
view3 = (View) view.findViewById(R.id.view3);
view4 = (View) view.findViewById(R.id.view4);
view5 = (View) view.findViewById(R.id.view5);
iv_pauseorresume = (ImageView) view.findViewById(R.id.iv_pauseorresume);
tv_pauseorresume = (TextView) view.findViewById(R.id.btn_pause);
tv_time = (TextView) view.findViewById(R.id.time);
ecgAlgo = new EcgAlgo();
ecgAlgo.setISmctAlgoCallback(this);
handler = new Handler();
samplePagerAdapter = new SamplePagerAdapter(getActivity(), getChildFragmentManager(), heart_rate);
viewpager.setAdapter(samplePagerAdapter);
indicator.setViewPager(viewpager);
viewpager.setCurrentItem(0);
linear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isstop) {
measureSwitch = true;
linear1.setVisibility(View.VISIBLE);
linear.setVisibility(View.GONE);
handler.post(runnable = new Runnable() {
#Override
public void run() {
int hours = count / 3600;
int minutes = (count % 3600) / 60;
int sec = count % 60;
String time = String.format("%02d:%02d:%02d", hours, minutes, sec);
tv_time.setText(time);
if (running) {
count++;
}
handler.postDelayed(this, 1000);
}
});
} else {
connectBle();
running = true;
}
}
});
linear_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ecgAlgo.clearECGParam();
isstop = true;
measureSwitch = false;
count = 0;
handler.removeCallbacks(runnable);
linear1.setVisibility(View.GONE);
linear.setVisibility(View.VISIBLE);
}
});
linear_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (onclick) {
iv_pauseorresume.setImageResource(R.drawable.resume1);
tv_pauseorresume.setText("Resume");
running = false;
onclick = false;
} else {
onclick = true;
running = true;
iv_pauseorresume.setImageResource(R.drawable.pause);
tv_pauseorresume.setText("Pause");
}
}
});
return view;
}
private void connectBle() {
if (TextUtils.isEmpty(bleAddress)) {// 蓝牙地址为空
showToast(R.string.ble_address_empty);
} else if (mBluetoothLeService != null && !isContecting) {// 蓝牙未连接
showDialog();
mBluetoothLeService.connect(bleAddress);
measureSwitch = true;
} else if (mBluetoothLeService == null) {// 连接服务
connectBleService();
} else {// 其它
disDialog();
showToast(R.string.ble_connect_fail);
}
}
/**
* 连接蓝牙服务
*/
public void connectBleService() {
Intent gattServiceIntent = new Intent(getActivity(), BluetoothLeService.class);
getActivity().bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
#Override
public void bleData(short key, short value) {
// TODO Auto-generated method stub
switch (key) {
case SmctConstant.KEY_BLE_CONNECT_STATE:// 连接状态改变
if (SmctConstant.VALUE_BLE_CONNECTED == value) {// 已连接
// hasReConnectCount = 0;
//updateNotification(getString(R.string.notification_nomal));
} else if (SmctConstant.VALUE_BLE_DISCONNECTED == value) {// 连接断开
disDialog();
if (isContecting) {//如果已连接 提示设备以断开连接
showToast(R.string.ble_connect_disconnect);
} else {//没有连接 提示连接失败
//showToast(R.string.ble_connect_fail);
}
isContecting = false;
//changeButtonSate(isContecting);
//changeSwitchView(false);
} else if (SmctConstant.VALUE_BLE_SERVICE_DISCOVERED == value) {// 发现服务
if (mBluetoothLeService != null) {
mBluetoothLeService.setCharacteristic(mBluetoothLeService.getSupportedGattServices(),
SmctConstant.UUID_KEY_DATA_FFE2);
}
disDialog();
isContecting = true;
//changeButtonSate(isContecting);
//changeSwitchView(false);
showToast(R.string.ble_connect_success);
}
break;
case SmctConstant.KEY_DEVICE_POWER_LEVEL:// 电量
//refrashPowerLevel(value);
//Log.d("power leve", "" + value);
break;
case SmctConstant.KEY_DEVICE_ELECTRODE_DROP:// 电极脱落
if (measureSwitch)
showToast("Elctrode Dropout!!!");
break;
case SmctConstant.KEY_ECG_DATA:// ecg数据
// 正在测量中
if (measureSwitch) {
//refrashEcgData(value);
//Log.d("Ecg data", "" + value);
//算法计算
ecgAlgo.addECGParam(value);
}
break;
case SmctConstant.KEY_BODY_POSE:// 姿态
if (value == SmctConstant.VALUE_POSE_WALK) {
//refrashPose("go");
Log.d("pose", "go");
} else if (value == SmctConstant.VALUE_POSE_FALL_DOWN) {
showToast("Falls!!!!!!");
Log.d("pose", "Falls");
} else if (value == SmctConstant.VALUE_POSE_LIE_LOW) {
//refrashPose("Flat lay");
Log.d("pose", "Flat lay");
} else if (value == SmctConstant.VALUE_POSE_STAND) {
//refrashPose("Flat lay");
Log.d("pose", "Standing");
} else if (value == SmctConstant.VALUE_POSE_SIDE_DECUBITUS) {
Log.d("pose", "Standing");
}
break;
}
}
#Override
public void bleData(short key, float[] value) {
if (SmctConstant.KEY_ACC_DATA == key) {
//refreshAccData(value);
}
}
/**
* 算法数据
*/
#Override
public void algoData(final int key, final int value) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
switch (key) {
case SmctConstant.KEY_ALGO_HEART_RATE:// 心率
//tv_heartrate.setText(String.valueOf(value));
//arc_progress.setProgress(value);
//heart_rate=value;
// Bundle bundle = new Bundle();
//bundle.putInt("heart_rate", value);
//fragment.setArguments(bundle);
heart_rate = value;
Bundle bundle=new Bundle();
bundle.putInt("heart_rate",value);
samplePagerAdapter.getItem(0).setArguments(bundle);
//notifyViewPagerDataSetChanged();
break;
case SmctConstant.KEY_ALGO_ARRHYTHMIA:// 心律失常
//tvArr.setText(formatString(R.string.arrhythmia, value));
break;
}
}
});
}
public ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
// LogUtil.e("smctservice", "Unable to initialize Bluetooth");
// mHandler.sendEmptyMessage(MSG_BLE_UNINIT);
} else {
mBluetoothLeService.setBleOperate(MeasureFragment.this);
connectBle();
}
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
// LogUtil.e("smctservice", "onServiceDisconnected");
mBluetoothLeService = null;
}
};
private void notifyViewPagerDataSetChanged() {
Log.d(TAG, "\nnotifyDataSetChanged()");
samplePagerAdapter.notifyDataSetChanged();
}
protected void disDialog() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (mProgressDialog != null) {
mProgressDialog.dismiss();
linear.setVisibility(View.GONE);
linear1.setVisibility(View.VISIBLE);
//new MyCountDownTimer(System.currentTimeMillis(),1000).start();
}
handler.post(runnable = new Runnable() {
#Override
public void run() {
int hours = count / 3600;
int minutes = (count % 3600) / 60;
int sec = count % 60;
String time = String.format("%02d:%02d:%02d", hours, minutes, sec);
tv_time.setText(time);
if (running) {
count++;
}
handler.postDelayed(this, 1000);
}
});
}
});
}
protected void showToast(String msg) {
ToastUtils.showToast(getActivity(), msg);
}
/**
* 统一显示toast管理
*/
protected void showToast(int id) {
ToastUtils.showToast(getActivity(), getResources().getString(id));
}
/**
* 显示连接蓝牙dialog
*/
protected void showDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
mProgressDialog = null;
}
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage(getResources().getString(R.string.text_conn_ble));
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
}
}
And need to update textview already discuss.in this fragment.
public class MyFragment extends Fragment {
private int heart_rate;
private ArcProgress arc_progress;
private TextView tv_heartrate;
private Handler handler;
private Runnable runnable;
private View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveBundle) {
view = inflater.inflate(R.layout.ecg_layout, container, false);
arc_progress = (ArcProgress) view.findViewById(R.id.arc_progress);
tv_heartrate = (TextView) view.findViewById(R.id.tv_heart_rate);
handler = new Handler();
handler.post(runnable = new Runnable() {
#Override
public void run() {
Log.d("heartrate", "" + heart_rate);
arc_progress.setProgress(heart_rate);
tv_heartrate.setText(String.valueOf(heart_rate));
handler.postDelayed(this, 1000);
}
});
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}

Using searchview in actionbar in fragments

I am displaying a userlist and I am using serachview in my actionbar to search. When I am using the searchView in activity, it works fine but when I use it for fragment, searchview doesn't work. It does not search in the listview.
Below is my code.
UserListFragment.java
public class UsersListFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Activity activity;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private static final String TAG = "UsersListFragment";
private OnFragmentInteractionListener mListener;
private ListView listView;
private List<UserData> users;
private CustomAdapter adapter;
SharedPreferences.Editor preferenceEditor;
Timer myTimer;
View view;
ActionBar actionBar;
private static final String PREFRENCES_NAME = "setPreferences";
private ProgressDialog progressBar;
String partnerKeyValue;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment UsersListFragment.
*/
// TODO: Rename and change types and number of parameters
public static UsersListFragment newInstance(String param1, String param2) {
UsersListFragment fragment = new UsersListFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progressBar = new ProgressDialog(getActivity());
progressBar.setCancelable(false);
progressBar.setMessage("Loading...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
Log.i(TAG, "UsersListFragment onCreate");
users = new ArrayList<>();
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
SharedPreferences preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("refresh","userlistview");
preferenceEditor.commit();
FirebaseUtil uts = new FirebaseUtil(getContext());
uts.startListeningNotification(Global.getInstance().ownerId, new CallBack() {
#Override
public void onCallback(Map<String, Object> response, String Success) {
Log.i(TAG, Success);
setHasOptionsMenu(true);
String partnerKey = (String) response.get("key");
if (partnerKey != null) {
Map<String, Object> typeCheck = (Map<String, Object>) response.get("value");
String type = (String) typeCheck.get("type");
if (type.equals("chat")) {
String key1 = Global.getInstance().ownerId;
String key2 = partnerKey;
partnerKeyValue = partnerKey;
if (key2 != null) {
String currentPartner = Global.getInstance().partnerId;
if (currentPartner.length() > 0) {
if (currentPartner.equals(partnerKey)) {
} else {
Global.getInstance().unreadMessageUsers.add(partnerKey);
}
Global.getInstance().unreadMessageUsers.add(partnerKey);
} else {
}
}
}
}
}
});
}
#Override
public void onStart() {
super.onStart();
Log.i(TAG, "UsersListFragment onStart");
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "UsersListFragment onResume");
}
#Override
public void onPause() {
super.onPause();
Log.i(TAG, "UsersListFragment onStart");
}
#Override
public void onStop() {
super.onStop();
Log.i(TAG, "UsersListFragment onStop");
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onDestroy() {
super.onDestroy();
FirebaseUtil util = new FirebaseUtil(getContext());
util.updateUserStatus(Global.getInstance().ownerId, "4");
Log.i(TAG, "UsersListFragment onDestroy");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if(actionBar!=null) {
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setLogo(R.drawable.ic_logo);
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#006EAD"));
actionBar.setBackgroundDrawable(colorDrawable);
}
Toast.makeText(getActivity(), String.valueOf( Global.getInstance().unreadMessageUsers.size()) , Toast.LENGTH_SHORT).show();
int vd = users.size();
view = inflater.inflate(R.layout.fragment_userslist, container, false);
listView = (ListView) view.findViewById(R.id.userdisplay);
adapter = new CustomAdapter(getActivity(),R.layout.program_list, users );
listView.setAdapter(adapter);
if (users.size()==0){
usersList();
}else {
adapter.notifyDataSetChanged();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UserData data = users.get(position);
Global.getInstance().someData = data.getId();
Global.getInstance().partnerId = data.getId();
int i = 0;
for (Iterator<String> iter = Global.getInstance().unreadMessageUsers.iterator(); iter.hasNext(); ) {
String element = iter.next();
if (element.equals(data.getId().toString())) {
iter.remove();
}
}
data.setUnreadMessageCount(0);
users.remove(position);
users.add(position, data);
Toast.makeText(getActivity().getApplicationContext(),String.valueOf(Global.getInstance().unreadMessageUsers.size()),Toast.LENGTH_LONG).show();
Fragment fragmentOne = new ChatFragment();
android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
Bundle args = new Bundle();
args.putString(ChatFragment.DATA_RECEIVE, data.getName());
fragmentOne .setArguments(args);
ft.addToBackStack(null);
ft.replace(R.id.framecontainerMain, fragmentOne).commit();
}
});
// Inflate the layout for this fragment
return view;
}
public void usersList () {
SharedPreferences preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
//get the data from userlist api
final String URL = "url";
String token = preferenceSettings.getString("authToken","");
final String userId = preferenceSettings.getString("userId","");
HashMap<String, String> params = new HashMap<String, String>();
params.put("user_id",userId);
params.put("auth_token",token);
progressBar.show();
JsonObjectRequest myRequest = new JsonObjectRequest(Request.Method.POST, URL,new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "onResponse:" +response);
String success = null;
try {
success = response.getString("success");
} catch (JSONException e) {
e.printStackTrace();
}
if(success == "true") {
JSONArray Array = null;
try {
//get the users
} else {
users.add(data);
}
}
Log.i(TAG, "arraylist");
adapter.notifyDataSetChanged();
onlineUsers();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 5000);
progressBar.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject Obj;
} else {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.dismiss();
VolleyLog.e("Error: ", error.getMessage());
Log.i(TAG, "onErrorResponse:" +error.networkResponse);
}
});
ApplicationController.getInstance().addToRequestQueue(myRequest);
myRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
public void sortingArray(){
if (users.size()>0) {
synchronized (this) {
if (Global.getInstance().unreadMessageUsers.size() > 0) {
System.out.println("\nExample 3 - Count all with Map");
Map<String, Integer> map = new HashMap<String, Integer>();
for (String temp : Global.getInstance().unreadMessageUsers) {
Integer count = map.get(temp);
map.put(temp, (count == null) ? 1 : count + 1);
}
System.out.println("\nSorted Map");
Map<String, Integer> unreadCount = new TreeMap<String, Integer>(map);
for (String key : unreadCount.keySet()) {
int count_unread = unreadCount.get(key);
int i = 0;
for (UserData obj : users) {
UserData user = obj;
if (user.getId().equals(key)) {
user.setUnreadMessageCount(count_unread);
users.remove(i);
users.add(i, user);
break;
}
i++;
}
}
}
synchronized (this) {
if (Global.getInstance().userStatus.size() > 0) {
try {
for (Object dict : Global.getInstance().userStatus) {
Map<String, Object> val = (Map<String, Object>) dict;
String key = val.keySet().iterator().next();
val.get(key).toString().trim();
int statusValue;
if (val.get(key).toString().equals("")) {
statusValue = 4;
} else {
statusValue = Integer.valueOf(val.get(key).toString());
}
int i = 0;
for (UserData obj : users) {
UserData user = obj;
if (user.getId().equals(key)) {
user.setOnlineStatus(statusValue);
users.remove(i);
users.add(i, user);
break;
}
i++;
}
}
}catch (ConcurrentModificationException e){
e.printStackTrace();
}
}
}
Log.i(TAG, users.get(0).getName());
if (users.size() > 0) {
Collections.sort(users, new Comparator<UserData>() {
#Override
public int compare(UserData o1, UserData o2) {
if (o1.getOnlineStatus() > o2.getOnlineStatus()) {
return 1;
} else if (o1.getOnlineStatus() < o2.getOnlineStatus()) {
return -1;
} else {
return 0;
}
}
});
}
if (users.size() > 0) {
Collections.sort(users, new Comparator<UserData>() {
#Override
public int compare(UserData o1, UserData o2) {
if (o1.getUnreadMessageCount() > o2.getUnreadMessageCount()) {
return -1;
} else if (o1.getUnreadMessageCount() < o2.getUnreadMessageCount()) {
return 1;
} else {
return 0;
}
}
});
Global.getInstance().userStatus.clear();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(), "any mesage", Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
});
}
}
}
}
public void TimerMethod() {
synchronized(this) {
SharedPreferences preferenceSettings = getActivity().getSharedPreferences("setPreferences", Context.MODE_PRIVATE);
String checkView = preferenceSettings.getString("refresh", "");
if (checkView.equals("userlistview")) {
if (Global.getInstance().userStatus.size() > 0) {
sortingArray();
}
} else {
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("refresh", "userlistview");
preferenceEditor.commit();
if (Global.getInstance().unreadMessageUsers.size() > 0){
sortingArray();
}
}
}
}
public void onlineUsers (){
String value;
for (UserData data : users) {
value = data.getId();
FirebaseUtil online = new FirebaseUtil(getContext());
online.onlineUsers(value, new CallBack() {
#Override
public void onCallback(Map<String, Object> response, String Success) {
if (response == null) {
} else {
Global.getInstance().userStatus.add(response);
}
}
});
}
}
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
inflater.inflate(R.menu.menu_userlist,menu);
MenuItem item = menu.findItem(R.id.menuSearch);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
super.onCreateOptionsMenu(menu,inflater);
}
private void logoutUser(){
Intent I = new Intent(getActivity(), LoginActivity.class);
startActivity(I);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuSearch :
return true;
case R.id.menuLogout :
logoutUser();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
String val = "'";
mListener.onFragmentInteraction(val);
}
}
public void initlizeval(Context context) {
mListener = (OnFragmentInteractionListener) context;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
myTimer.cancel();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(String val);
}
}
menu_userlist.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/menuSearch"
android:title="#string/search"
android:icon="#drawable/ic_search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always">
</item>
<item android:id="#+id/menuLogout"
android:title="#string/logout"
android:icon="#drawable/ic_logout"
android:tint="#android:color/white"
app:showAsAction="always">
</item>
</menu>
CustomAdapter.java
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class CustomAdapter extends ArrayAdapter<UserData> {
private Activity activity;
private List<UserData> messages;
public CustomAdapter(Activity context, int resource, List<UserData> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
packagename.CustomAdapter.ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
int layoutResource = 0; // determined by view type
UserData data = getItem(position);
int viewType = getItemViewType(position);
layoutResource = R.layout.program_list;
if (convertView != null) {
holder = (com.your.package.CustomAdapter.ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(layoutResource, parent, false);
holder = new com.your.package.CustomAdapter.ViewHolder(convertView);
convertView.setTag(holder);
}
//set message content
holder.msg.setText(data.getName());
holder.id = data.geId();
holder.roleMsg.setText(data.getRole());
return convertView;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
private class ViewHolder {
private TextView msg;
private String id;
private TextView roleMsg;
public ViewHolder(View v) {
msg = (TextView) v.findViewById(R.id.textView1);
roleMsg = (TextView) v.findViewById(R.id.textView2);
}
}
}
HomeActivity.java
public class HomeActivity extends AppCompatActivity implements UsersListFragment.OnFragmentInteractionListener {
private UsersListFragment mItemsFragment;
private ChatFragment mFragmentOne;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
VideoFragment fragmentTwo ;
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
android.support.v4.app.FragmentTransaction fts = getSupportFragmentManager().beginTransaction();
fts.add(R.id.framecontainer, mItemsFragment).commit();
//Instantiate some stuff here like view components
Fragment fragmentOne = new ChatFragment();
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.framecontainerTab, fragmentOne).commit();
}else{
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
layout2.removeAllViews();
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
setFragment(mItemsFragment);
}
}
public void setFragment(Fragment frag)
{
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
}
public void attemptLogin1() {
String test = "one";
String tested = "fail";
}
#Override
public void onFragmentInteraction(String uri) {
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
LinearLayout layout2 = (LinearLayout)findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
findViewById(R.id.framecontainerVideo);
Toast.makeText(getApplicationContext(), "bullet", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Fragment fragmentOne = new ChatFragment();
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
}
#Override
protected void onStart() {
super.onStart();
getDelegate().onStart();
}
}
I have written setHasOptionsMenu(true); in onCreate of UserFragment.java
The logout functionality works fine but the search isn't working.
I have tried various options given on Stackoverflow as well as from other resource, but nothing worked. :(
Any help is appreciated.
Thanks in advance.
Create Constructor in your fragment. Pass Context object inside fragment constructor.which allows your activity as global access.
Remove this line and it will work
case R.id.menuSearch:
return true;

PullToRefreshAttacher.OnRefreshListener cannot be resolved to a type

am building an open source project, here is its link
http://slidese.github.io/slidese/2013/11/25/update_listview_item.html
I've imported all library projects which it is using into eclipse. All are fine except PullToRefresh library. it is giving me the error "PullToRefreshAttacher.OnRefreshListener cannot be resolved to a type" where fragment implements it
2nd error is at
mPullToRefreshAttacher.addRefreshableView(mListview, this);
it says "The method addRefreshableView(View, ViewDelegate) in the type PullToRefreshAttacher is not applicable for the arguments (ListView, ContentFragment)"
3rd error is at
#Override
public void onRefreshStarted(View view) {
Intent intent = new Intent(getActivity(), DownloaderService.class);
intent.putExtra(DownloaderService.EXTRA_USER_INITIATED, true);
getActivity().startService(intent);
}
It is asking me to remove override annotation. here is complete code of fragment.
public class ContentFragment extends Fragment implements PullToRefreshAttacher.OnRefreshListener {
private final String TAG = "ContentFragment";
public static final String CONTENT_MODE = "content_mode";
public static final int MODE_ADFREE = 0;
public static final int MODE_PREMIUM = 1;
private StartActivity mListener;
private PullToRefreshAttacher mPullToRefreshAttacher;
private UpdaterAsyncTask mUpdater;
private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE;
ListView mListview;
Button mPlayButton;
ContentAdapter mAdapter;
int mMode;
Map<String, UpdateHolder> mUpdates = new HashMap<String, UpdateHolder>();
public ContentFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (StartActivity) activity;
Log.d(TAG, "Attached podcast list fragment");
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must be the StartActivity");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_content, null);
mListview = (ListView) view.findViewById(android.R.id.list);
mListview.setEmptyView(view.findViewById(R.id.empty_list_view));
mListview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mListview.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_menu_content, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
if (item.getItemId() == R.id.action_delete) {
SparseBooleanArray checked = mListview.getCheckedItemPositions();
Content[] params = new Content[checked.size()];
int index = 0;
int first = mListview.getFirstVisiblePosition();
int last = mListview.getLastVisiblePosition();
for (int i = 0; i < mListview.getCount(); i++) {
if (checked.get(i)) {
params[index++] = (Content)mListview.getItemAtPosition(i);
if (i >= first && i <= last) {
View view = mListview.getChildAt(i-first);
Animation animation = AnimationUtils.loadAnimation(getActivity(), android.R.anim.slide_out_right);
animation.setDuration(200);
//animation.setFillAfter(true);
animation.setStartOffset(100 * (index) );
view.startAnimation(animation);
}
}
}
new AsyncTask<Content, Void, Void>() {
#Override
protected Void doInBackground(Content... params) {
for (Content content : params) {
File file = Utils.getFilepath(content.getFilename());
file.delete();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mAdapter.notifyDataSetChanged();
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
mode.finish();
return true;
}
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}
});
mListview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
Content content = mAdapter.getItem(position);
mListener.showContentDetails(content);
}
});
mListview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mScrollState = scrollState;
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
mPullToRefreshAttacher = ((StartActivity) getActivity()).getPullToRefreshAttacher();
mPullToRefreshAttacher.addRefreshableView(mListview, this);
mMode = getArguments().getInt(CONTENT_MODE);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onPause() {
super.onPause();
if (mUpdater != null)
mUpdater.stop();
}
#Override
public void onResume() {
super.onResume();
updateAdapter();
mUpdater = new UpdaterAsyncTask();
mUpdater.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void)null);
}
public void refresh() {
updateAdapter();
}
public void replaceCurrentlyPlayingContent() {
GlobalContext.INSTANCE.replaceCurrentlyPLayingContent(mAdapter.getObjects(), mListener.getCurrentTrack());
}
private void updateAdapter() {
Log.d(TAG, "updateAdapter");
//new FetchContentAsyncTask(mMode).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
final String mp3 = mListener.getSavedStateMp3();
final boolean isPlaying = mListener.getSavedStateIsPlaying();
final boolean isPaused = mListener.getSavedStateIsPaused();
List<Content> listOfContent = GlobalContext.INSTANCE.getCachedContent(mMode, mp3, isPlaying, isPaused);
mAdapter = new ContentAdapter(getActivity(), R.layout.list_item_card, listOfContent);
mListview.setAdapter(mAdapter);
}
#Override
public void onRefreshStarted(View view) {
Intent intent = new Intent(getActivity(), DownloaderService.class);
intent.putExtra(DownloaderService.EXTRA_USER_INITIATED, true);
getActivity().startService(intent);
}
private class UpdaterAsyncTask extends AsyncTask<Void, Void, Void> {
boolean isRunning = true;
public void stop() {
isRunning = false;
}
#Override
protected Void doInBackground(Void... params) {
while (isRunning) {
/*
Map<String, UpdateHolder> map = gatherMetadata();
publishProgress(map);
*/
updateCurrentAdapterContent();
publishProgress();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... params) {
super.onProgressUpdate();
if (mScrollState == OnScrollListener.SCROLL_STATE_IDLE) {
// http://stackoverflow.com/questions/2123083/android-listview-refresh-single-row
int start = mListview.getFirstVisiblePosition();
for(int i = start, j = mListview.getLastVisiblePosition(); i<=j; i++) {
View view = mListview.getChildAt(i-start);
if (((Content)mListview.getItemAtPosition(i)).dirty) {
Log.v(TAG, "Content is dirty");
mListview.getAdapter().getView(i, view, mListview);
}
}
}
}
}
private void updateCurrentAdapterContent() {
List<Content> listOfContent = mAdapter.getObjects();
Map<String, UpdateHolder> map = new HashMap<String, UpdateHolder>();
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterByStatus(DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
try {
Cursor cursor = ContentDownloadManager.INSTANCE.query(q);
while (cursor.moveToNext()) {
//long id = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
String uri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI));
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
int downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
float progress = (float)downloaded/(float)total;
UpdateHolder holder = new UpdateHolder();
holder.progress = progress;
holder.status = status;
map.put(uri, holder);
}
cursor.close();
final Content currentContent = mListener.getCurrentTrack();
final boolean isPlaying = mListener.isPlaying();
final boolean isPaused = mListener.isPaused();
for (Content content : listOfContent) {
// First update any download progress we might have for this specific content item
UpdateHolder holder = map.get(content.mp3);
if (holder != null) {
if (content.downloadProgress != holder.progress) {
content.downloadProgress = holder.progress;
content.dirty = true;
}
if (content.downloadStatus != holder.status) {
content.downloadStatus = holder.status;
content.dirty = true;
}
}
else {
if (content.downloadProgress != 0f) {
content.downloadProgress = 0f;
content.dirty = true;
}
if (content.downloadStatus != -1) {
content.downloadStatus = -1;
content.dirty = true;
}
}
// Update with elapsed (to be done)
// File exists?
File file = Utils.getFilepath(content.getFilename());
if (content.exists != file.exists()) {
content.exists = file.exists();
content.dirty = true;
}
// Is this the currently playing content
if (currentContent != null && content.mp3.equals(currentContent.mp3)) {
if (content.isPlaying != isPlaying) {
content.isPlaying = isPlaying;
content.dirty = true;
}
if (content.isPaused != isPaused) {
content.isPaused = isPaused;
content.dirty = true;
}
}
else {
if (content.isPlaying != false) {
content.isPlaying = false;
content.dirty = true;
}
if (content.isPaused != false) {
content.isPaused = false;
content.dirty = true;
}
}
if (content.dirty) {
DatabaseManager.getInstance().createOrUpdateContent(content);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class UpdateHolder {
public String mp3;
public int status;
public boolean played;
public float progress;
public boolean exists = false;
public boolean isPlaying = false;
public boolean isPaused = false;
//public int elapsed;
//public int duration;
}
}
I couldn't find the issue in it. I'm stuck here for last 40 hours. Please help. Thank you!
Maybe you are using old version of the library. I found that PullToRefreshAttacher doesn't contain OnRefreshListener. (https://github.com/chrisbanes/ActionBar-PullToRefresh/blob/master/library/src/main/java/uk/co/senab/actionbarpulltorefresh/library/PullToRefreshAttacher.java)
Try to import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener; and use it instead of PullToRefreshAttacher.OnRefreshListener.

Categories

Resources