When my first to get the data from the first tab of fragment,it was something wrong.And through the web page to open it ,these data is normal.
public class OnlineAllInsuranceFragment extends Fragment implements OnListViewListener {
private ScrollListView MainView;
private BasicAdapter2 Adapter;
private Integer Step=10;
private Integer Start=0;
private Integer End=Step;
private Handler handler,handler2;
private DataTable dTable;
public static String SelectCode="";
private static final int OVER = 1;
private String polnum;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_online_insurance,container,false);
handler2 = new Handler();
new Thread(new Runnable() {
public void run() {
Looper.prepare();
handler2.post(runSetList);
Looper.loop();
}
}).start();
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.MainView=(ScrollListView)getView().findViewById(R.id.contractlistView1);
this.MainView.setPullLoadEnable(true);
this.MainView.setXListViewListener(this);
}
private void SetList(){
Start=0;
End=3;
this.dTable = new DataTable(getActivity(),"newcontract");
this.dTable.Load("AgentCode="+OnlineAllInsuranceFragment.SelectCode+"&Start=0&End="+Step);
if(dTable.GetRowCount()>0){
this.MainView.setVisibility(0);
this.StartData(this.dTable.GetList(),R.layout.userlistitem4);
}else{
this.MainView.setVisibility(8);
TextView NullView=(TextView) getView().findViewById(R.id.listViewNull1);
NullView.setVisibility(0);
NullView.setHeight(50);
}
}
private void StartData(ArrayList<Map<String, Object>> List, int Resource) {
this.Adapter = new BasicAdapter2(getActivity(), List, Resource,
new String[] { "Provider", "ProdName", "NoType", "ContractNo",
"AcceptTime", "ContractStatus", "Premium", "Gain",
"ReceivedPremium", "Name" },
new int[] {R.id.contractitem_label_Provider,
R.id.contractitem_label_ProdName,
R.id.contract_label_cno,
R.id.contractitem_label_contractNo,
R.id.contractitem_label_acceptTime,
R.id.contractitem_label_contractStatus,
R.id.contractitem_label_premium,
R.id.contractitem_label_feilv,
R.id.contractitem_label_receivedPremium,
R.id.contractitem_label_Name },
new int[] {R.id.listitem_button_look, R.id.listitem_button_pay,
R.id.listitem_main1,R.id.contractitem_label_companyImage,R.id.contractitem_label_payImage },
new BasicAdapter2.ListAdapterListener() {
#Override
public void onClickAtOKButton(View v) {
String company = dTable.GetValue((Integer)v.getTag(), 1).toString();//产品名
String status = dTable.GetValue((Integer)v.getTag(), 4).toString();//保单状态
switch (v.getId()) {
case R.id.listitem_button_pay:
polnum = dTable.GetValue((Integer)v.getTag(), 3).toString();
String numPol = dTable.GetValue((Integer)v.getTag(), 2).toString();//是“保单号”还是“投保单号”
if (numPol.contains("aa")) {
Intent intent = new Intent();
intent.setClass(getActivity(),PolicyInformationActivity.class);
intent.putExtra("polnum", polnum);
startActivity(intent);
} else if (numPol.contains("bb")) {
toastDialog();
}
break;
case R.id.listitem_button_look:
Toast.makeText(getActivity(),"...", Toast.LENGTH_SHORT).show();
LogUtil.e("company+status", company+"=="+status);
break;
case R.id.listitem_main1:
break;
}
}
},
new BasicAdapter2.VisibleAdapterListener() {
#Override
public int onSetVisible(View v) {
String company = dTable.GetValue((Integer)v.getTag(), 1).toString();//产品名
String status = dTable.GetValue((Integer)v.getTag(), 4).toString();//保单状态
LogUtil.e("status","=="+status);
int drawId;
switch (v.getId()) {
case R.id.contractitem_label_companyImage:
if ( company.contains("cc") ) {
drawId = R.drawable.taikang2x;
return drawId;
} else if (company.contains("dd") ) {
drawId = R.drawable.youban2x;
return drawId;
}
break;
case R.id.contractitem_label_payImage:
if ( status.equals("ee") ) {
drawId = R.drawable.security2x;
return drawId;
} else if (status.equals("ff")) {
drawId = R.drawable.nopay2x;
return drawId;
} else if ( status.equals("gg")) {
drawId = R.drawable.invalid2x;
return drawId;
}
break;
case R.id.listitem_button_pay:
if (company.contains("hh") && status.equals("ii")) {
return 0;
} else if (company.contains("jj") || status.equals("kk")) {
return 4;
}
break;
}
return 99;
}
});
handler = new Handler();
this.Adapter.Start(this.MainView);
this.Start += Step;
this.End += Step;
}
private void LoadData(){
this.dTable.Load("AgentCode="+OnlineAllInsuranceFragment.SelectCode+"&Start="+Start+"&End="+End);
this.Start += Step;
this.End += Step;
}
private void stopRefresh() {
this.MainView.stopRefresh();
this.MainView.setRefreshTime("just");
}
private void stopLoadMore() {
this.MainView.stopLoadMore();
}
#Override
public void onRefresh() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
SetList();
stopRefresh();
}
}, 2000);
}
#Override
public void onLoadMore() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
LoadData();
stopLoadMore();
}
}, 2000);
}
#SuppressLint("HandlerLeak")
Handler handler1 = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case OVER:
Control.ExitDialog();
break;
default:
break;
}
super.handleMessage(msg);
}
};
Runnable runSetList = new Runnable() {
#Override
public void run() {
SetList();
}
};
private void toastDialog() {
CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
builder.setTitle("xx");
builder.setMessage("yy");
builder.setNegativeButton("vv", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setPositiveButton("ww", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Control.StartDialog(getActivity());
new Thread(new Runnable() {
public void run() {
Looper.prepare();
startActivity(new Intent(getActivity(),HomeActivity.class));
send();
handler1.sendEmptyMessage(1);
Looper.loop();
}
}).start();
}
});
Dialog noticeDialog = builder.create();
noticeDialog.setCancelable(false);
noticeDialog.setCanceledOnTouchOutside(false);
noticeDialog.show();
}
private void send() {
}
}
And when I keep away from this Fragment then comeback,the data become normal,too.The data is not normal just when my first in the Fragment.
Related
When I click music notification and run activity. When music change the content of textview changed, but view not update, but when I run an activity independently, everything works fine and view updated.
In musicService class:
PendingIntent contentPendingIntent = PendingIntent.getActivity
(this, 0, new Intent(this, MusicPlayer.class), 0);
builder.setContentTitle(mMedia.getTitleMedia())
.setContentText(mMedia.getSingerName())
.setContentIntent(contentPendingIntent)
.setSmallIcon(R.drawable.ic_notification)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.addAction(restartAction)
.addAction(playPauseAction)
.addAction(nextMusic)
.setDeleteIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(getApplicationContext(), PlaybackStateCompat.ACTION_STOP));
and my activity class
public class MusicPlayer extends AppCompatActivity implements ServiceConnection, CacheListener, SeekBar.OnSeekBarChangeListener, Player.EventListener {
private SimpleExoPlayerView mPlayerView;
public PlayerService mPlayerService;
private boolean mBound;
//______________________________________________________________________________________________
VolleyRequestHelper volleyRequestHelper;
//______________________________________________________________________________________________
public static MusicPlayer instance;
public ImageView download;
TextView title;
TextView artist;
SeekBar progressBar;
ImageView circleImageView;
ImageView album_art_blurred;
PlayPauseButton mPlayPause;
public AppBarLayout appBarLayout;
private final VideoProgressUpdater updater = new VideoProgressUpdater();
public DownloadProgressView downloadProgressView;
//______________________________________________________________________________________________
TextView songElapsedTime;
TextView songDuration;
int positionOfMusic = 0;
public Media media;
boolean initAlbum = false;
boolean startService = false;
boolean checkChangeMediaDetails = true;
//______________________________________________________________________________________________
RecyclerView recyclerViewArtist;
SimilarSongsAdapter similarSongsAdapter;
public List<Media> similarSongsList = new ArrayList<>();
//______________________________________________________________________________________________
int songElapsed = 0;
int songDurationTime = 0;
int videoProgress = 0;
int mediaServiceRun = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_player);
instance = this;
volleyRequestHelper = VolleyRequestHelper.getInstance(getApplicationContext(), requestCompletedListener);
initView();
initRecyclerview();
Intent intent = getIntent();
mediaServiceRun = intent.getIntExtra("mediaServiceRun", 1);
if (mediaServiceRun == 1) {
Intent i = new Intent(this, PlayerService.class);
bindService(i, this, Context.BIND_AUTO_CREATE);
startService(i);
} else {
media = intent.getParcelableExtra("media");
switch (media.getCustomMediaType()) {
case "آهنگ آلبوم":
setMedia(media);
getAlbumTrack(media.getAlbumId());
break;
case "آلبوم":
initAlbum = true;
getAlbumTrack(media.getId());
break;
default:
setMedia(media);
Serach(media.getSingerName(), "1");
break;
}
selectMedia(media);
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (mBound) {
unbindService(this);
mBound = false;
}
}
#Override
protected void onResume() {
super.onResume();
updater.start();
}
#Override
public void onPause() {
super.onPause();
updater.stop();
}
//_________________________ServiceConnected_and_ServiceDisconnected_____________________________
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
PlayerService.MyBinder b = (PlayerService.MyBinder) iBinder;
mPlayerService = b.getService();
mPlayerView.setUseController(false);
mPlayerView.setPlayer(mPlayerService.getExoPlayer());
if (mediaServiceRun == 1) {
similarSongsList = mPlayerService.getOnlineList();
initView();
initRecyclerview();
musicChange(mPlayerService.getPlayingMedia());
} else {
mPlayerService.getExoPlayer().addListener(this);
mPlayerService.setPlayingMedia(positionOfMusic);
setMusicInService(media, mPlayerService.getPlayingMedia());
if (similarSongsList != null && similarSongsList.size() != 0) {
mPlayerService.setOnlineList(similarSongsList);
}
}
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBound = false;
}
//______________________________________________________________________________________________
//_______________________________________setMediaInView_________________________________________
public void setMedia(Media mediaL) {
media = mediaL;
bluredImage(mediaL.getCover());
Picasso.with(this).load(mediaL.getCover()).into(circleImageView);
title.setText(mediaL.getTitleMedia());
artist.setText(mediaL.getSingerName());
checkCachedState(mediaL.getStreamUrl());
checkChangeMediaDetails = false;
}
public void bluredImage(String IMAGE_URL) {
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
album_art_blurred.setImageBitmap(BlurImage.fastblur(bitmap, 1f, 50));
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
album_art_blurred.setImageResource(R.mipmap.ic_launcher);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
album_art_blurred.setTag(target);
Picasso.with(this)
.load(IMAGE_URL)
.error(R.mipmap.ic_launcher)
.placeholder(R.mipmap.ic_launcher)
.into(target);
}
//______________________________________________________________________________________________
//______________________________________initView________________________________________________
public void initRecyclerview() {
recyclerViewArtist = (RecyclerView) findViewById(R.id.queue_recyclerview_horizontal);
recyclerViewArtist.setNestedScrollingEnabled(false);
recyclerViewArtist.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
LinearLayoutManager horizontalLayoutManagaertwo
= new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
recyclerViewArtist.setLayoutManager(horizontalLayoutManagaertwo);
similarSongsAdapter = new SimilarSongsAdapter(this, similarSongsList, recyclerViewArtist);
recyclerViewArtist.setAdapter(similarSongsAdapter);
}
public void initView() {
mPlayerView = (SimpleExoPlayerView) findViewById(R.id.simpleExoPlayerView);
appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
downloadProgressView = (DownloadProgressView) findViewById(R.id.downloadProgressView);
downloadProgressView.setPercentageColor(Color.parseColor("#ffffff"));
downloadProgressView.setDownloadedSizeColor(Color.parseColor("#ffffff"));
downloadProgressView.setTotalSizeColor(Color.parseColor("#ffffff"));
songElapsedTime = (TextView) findViewById(R.id.song_elapsed_time);
songDuration = (TextView) findViewById(R.id.song_duration);
progressBar = (SeekBar) findViewById(R.id.song_progress);
progressBar.setOnSeekBarChangeListener(this);
circleImageView = (ImageView) findViewById(R.id.album_art);
album_art_blurred = (ImageView) findViewById(R.id.album_art_blurred);
title = (TextView) findViewById(R.id.song_title);
artist = (TextView) findViewById(R.id.song_artist);
mPlayPause = (PlayPauseButton) findViewById(R.id.playpause);
download = (ImageView) findViewById(R.id.download);
if (SornaDownloadManager.inQueue) {
if (SornaDownloadManager.checkDownloadId(media.getId())) {
download.setVisibility(View.GONE);
downloadProgressView.show(SornaDownloadManager.lastDownloadID,
new DownloadProgressView.DownloadStatusListener() {
#Override
public void downloadFailed(int reason) {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadSuccessful() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadCancelled() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
});
}
}
}
//______________________________________________________________________________________________
//_________________________________Cache_and_UpdateProgressBar__________________________________
private void checkCachedState(String url) {
HttpProxyCacheServer proxy = TimberApp.getProxy(this);
boolean fullyCached = proxy.isCached(url);
if (fullyCached) {
progressBar.setSecondaryProgress(100);
}
proxy.registerCacheListener(this, url);
}
private void updateVideoProgress() {
if (mPlayerService != null)
try {
videoProgress = (int) (mPlayerService.getExoPlayer().getCurrentPosition() * 100 / mPlayerService.getExoPlayer().getDuration());
} catch (Exception e) {
}
progressBar.setProgress(videoProgress);
}
private final class VideoProgressUpdater extends Handler {
public void start() {
sendEmptyMessage(0);
}
public void stop() {
removeMessages(0);
}
#Override
public void handleMessage(Message msg) {
updateVideoProgress();
sendEmptyMessageDelayed(0, 500);
if (mPlayerService != null) {
try {
songElapsed = (int) mPlayerService.getExoPlayer().getCurrentPosition();
songDurationTime = (int) mPlayerService.getExoPlayer().getDuration();
} catch (Exception e) {
}
}
songElapsedTime.setText(millisecondsTOminutes.milliSecondsToTimer(songElapsed));
songDuration.setText(millisecondsTOminutes.milliSecondsToTimer(songDurationTime));
}
}
#Override
public void onCacheAvailable(File cacheFile, String url, int percentsAvailable) {
progressBar.setSecondaryProgress(percentsAvailable);
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
void seekVideo() {
int videoPosition = (int) (mPlayerService.getExoPlayer().getDuration() * progressBar.getProgress() / 100);
mPlayerService.getExoPlayer().seekTo(videoPosition);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekVideo();
songElapsedTime.setText(millisecondsTOminutes.milliSecondsToTimer(mPlayerService.getExoPlayer().getCurrentPosition()) + "");
}
//______________________________________________________________________________________________
//____________________________________setButtonsFuction_________________________________________
public void setFunc(View v) {
switch (v.getId()) {
case R.id.playpause:
if (!mPlayPause.isPlayed()) {
setPlayButton(true);
if (!startService) {
setStopService();
setStartService();
onlinePlay(media.getId());
} else {
mPlayerService.playTrack();
}
} else {
setPlayButton(false);
mPlayerService.pauseTrack();
}
break;
case R.id.next:
mPlayerService.nextTrack();
//positionOfMusic = mPlayerService.getPlayingMedia();
break;
case R.id.previous:
mPlayerService.previousTrack();
//positionOfMusic = mPlayerService.getPlayingMedia();
break;
case R.id.download:
showPopup(media);
break;
case R.id.share:
share.shareTrack(media, this);
break;
}
}
public void showPopup(final Media media) {
View popupView = LayoutInflater.from(this).inflate(R.layout.popup_layout, null);
final PopupWindow popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT
, WindowManager.LayoutParams.MATCH_PARENT);
popupWindow.setOutsideTouchable(false);
popupWindow.setFocusable(true);
popupWindow.showAtLocation(popupView, Gravity.CENTER, 1, 1);
Button dnlow = (Button) popupView.findViewById(R.id.dnlow);
Button dnhigh = (Button) popupView.findViewById(R.id.dnhigh);
if (media.getDownloadLinksList128().matches("noLink"))
dnlow.setVisibility(View.GONE);
if (media.getDownloadLinksList320().matches("noLink"))
dnhigh.setVisibility(View.GONE);
dnlow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SornaDownloadManager sornaDownloadManager = SornaDownloadManager.getInstance(getApplicationContext());
long downloadID = sornaDownloadManager.AddForDownload(media.getDownloadLinksList128(),
media.getTitleMedia() + "-" + media.getSingerName(), media.getId());
downloadProgressView.show(downloadID, new DownloadProgressView.DownloadStatusListener() {
#Override
public void downloadFailed(int reason) {
}
#Override
public void downloadSuccessful() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadCancelled() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
});
popupWindow.dismiss();
}
});
dnhigh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SornaDownloadManager sornaDownloadManager = SornaDownloadManager.getInstance(getApplicationContext());
long downloadID = sornaDownloadManager.AddForDownload(media.getDownloadLinksList320(),
media.getTitleMedia() + "-" + media.getSingerName(), media.getId());
downloadProgressView.show(downloadID, new DownloadProgressView.DownloadStatusListener() {
#Override
public void downloadFailed(int reason) {
}
#Override
public void downloadSuccessful() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadCancelled() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
});
popupWindow.dismiss();
}
});
popupWindow.showAsDropDown(popupView, 0, 0);
}
//______________________________________________________________________________________________
//__________________________________GetDataFromServer___________________________________________
public void Serach(String searchQuery, String page) {
updateData();
volleyRequestHelper.RequestFetchSearchMedia
(constantsURL.REQUEST_FETCH_SIMILAR_SONGS, searchQuery, page, false);
}
public void getAlbumTrack(String albumId) {
updateData();
volleyRequestHelper.RequestFetchAlbumTrack
(constantsURL.REQUEST_FETCH_ALBUM_TRACKS, albumId, false);
}
public void selectMedia(final Media media) {
if (!constants.refLogId.matches(""))
volleyRequestHelper.requestSetLog
(constantsURL.REQUEST_SET_LOG, "selectSearchResult", media.getId(), constants.refLogId, false);
}
public void onlinePlay(final String mediaid) {
volleyRequestHelper.requestSetLog
(constantsURL.REQUEST_SET_LOG, "onlinePlay", mediaid, constants.refLogId, false);
}
public void updateData() {
similarSongsAdapter.notifyDataSetChanged();
similarSongsAdapter.setLoaded();
}
public void parseJson(String response, List<Media> arrayList) {
try {
JsonParser parser = new JsonParser();
JsonElement json = parser.parse(response);
JSONObject jsonObject = new JSONObject(String.valueOf(json));
JSONArray arrey = jsonObject.getJSONArray("result");
if (!media.getCustomMediaType().matches("آلبوم"))
arrayList.add(media);
for (int i = 0; i < arrey.length(); i++) {
JSONObject j = arrey.getJSONObject(i);
Media mdia = new Media(j);
if (!media.getId().matches(mdia.getId()) && !mdia.getCustomMediaType().matches("آلبوم"))
arrayList.add(mdia);
}
} catch (Exception e) {
}
if (mPlayerService != null) {
mPlayerService.setOnlineList(similarSongsList);
}
}
private VolleyRequestHelper.OnRequestCompletedListener requestCompletedListener =
new VolleyRequestHelper.OnRequestCompletedListener() {
#Override
public void onRequestCompleted(String requestName, boolean status,
String response, String errorMessage) {
//homeView.hideProgress();
switch (requestName) {
case "SIMILAR_SONGS":
if (status) {
parseJson(response, similarSongsList);
updateData();
}
break;
case "ALBUM_TRACKS":
if (status) {
parseJson(response, similarSongsList);
updateData();
if (initAlbum) {
setMedia(similarSongsList.get(0));
}
}
break;
}
}
};
//_______________________________________EXOPLAYER______________________________________________
#Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
if (checkChangeMediaDetails) {
musicChange(mPlayerService.getPlayingMedia());
} else checkChangeMediaDetails = true;
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if ((playbackState == Player.STATE_READY) && playWhenReady) {
if (!mPlayPause.isPlayed()) {
setPlayButton(true);
}
} else if ((playbackState == Player.STATE_READY)) {
setPlayButton(false);
} else if (playbackState == Player.STATE_ENDED) {
}
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity() {
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
//______________________________________________________________________________________________
public void setStartService() {
Intent intent = new Intent(this, PlayerService.class);
bindService(intent, this, Context.BIND_AUTO_CREATE);
startService(intent);
startService = true;
}
public void setStopService() {
Intent intentStop = new Intent(this, PlayerService.class);
stopService(intentStop);
}
public void setPlayButton(boolean playButton) {
mPlayPause.setPlayed(playButton);
mPlayPause.startAnimation();
}
public void setMusicInService(Media mMedia, int position) {
positionOfMusic = position;
if (mPlayerService != null) {
mPlayerService.setPlayMedia(mMedia, position);
} else {
setStartService();
setMedia(mMedia);
}
//positionOfMusic = position;
/*if (mPlayerService != null) {
mPlayerService.setMediaUri(mMedia.getStreamUrl());
mPlayerService.setMedia(mMedia);
mPlayerService.setPlayingMedia(position);
mPlayerService.preparePlayer();
} else {
positionOfMusic = position;
setStartService();
setMedia(mMedia);
}*/
}
public void musicChange(int newPosition) {
if (similarSongsList != null && similarSongsList.size() != 0) {
setMedia(similarSongsList.get(newPosition));
similarSongsAdapter.setPlayPosition(newPosition);
similarSongsAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder)
{
PlayerService.MyBinder b = (PlayerService.MyBinder) iBinder;
mPlayerService = b.getService();
mPlayerView.setUseController(false);
mPlayerView.setPlayer(mPlayerService.getExoPlayer());
if (mediaServiceRun == 1) {
similarSongsList = mPlayerService.getOnlineList();
initView();
initRecyclerview();
musicChange(mPlayerService.getPlayingMedia());
} else {
mPlayerService.getExoPlayer().addListener(this);
mPlayerService.setPlayingMedia(positionOfMusic);
setMusicInService(media, mPlayerService.getPlayingMedia());
if (similarSongsList != null && similarSongsList.size() != 0) {
mPlayerService.setOnlineList(similarSongsList);
}
}
mBound = true;
}
How to show message in showDialog();
I want when freshDownloadView is finished show showDialog.
My code is as follows:
public class MainActivity extends Activity implements View.OnClickListener {
private FreshDownloadView freshDownloadView;
private Button btDownloaded;
private TextView btReset;
private TextView btDownloadError;
private final int FLAG_SHOW_OK = 10;
private final int FLAG_SHOW_ERROR = 11;
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
int progress = (int) msg.obj;
freshDownloadView.upDateProgress(progress);
switch (msg.what) {
case FLAG_SHOW_OK:
break;
case FLAG_SHOW_ERROR:
freshDownloadView.showDownloadError();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
freshDownloadView = (FreshDownloadView) findViewById(R.id.pitt);
btDownloaded = (Button) findViewById(R.id.bt_downloaded);
btReset = (Button) findViewById(R.id.bt_reset);
btDownloadError = (Button) findViewById(R.id.bt_download_error);
btDownloaded.setOnClickListener(this);
btReset.setOnClickListener(this);
btDownloadError.setOnClickListener(this);
}
this is button freshDownload
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_downloaded:
if (freshDownloadView.using()) return;
new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i <= 100; i++) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message message = Message.obtain();
message.obj = i;
handler.sendMessage(message);
showDialog();
}
}
}).start();
break;
case R.id.bt_reset:
freshDownloadView.reset();
break;
case R.id.bt_download_error:
if (freshDownloadView.using()) return;
new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i <= 30; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message message = Message.obtain();
if (i == 30) {
message.what = FLAG_SHOW_ERROR;
}
message.obj = i;
handler.sendMessage(message);
}
}
}).start();
break;
}
}
public void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(R.string.dialog_title)
.setMessage(R.string.download_app)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.create().show();
}
protected void onPause() {
// unregisterReceiver(receiver);
super.onPause();
}
protected void onResume() {
// registerReceiver(receiver, new IntentFilter(
// WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
}
I suggest you use AsyncTask for this. You can initiate the download in the doInBackground method and show the alert dialog (as needed) in the onPostExecute method. This will also free you from using Thread.sleep(100) which isn't a good practice on Android.
However, if you still prefer to use the FreshDownloadView please update your question with the code for FreshDownloadView and we can suggest something.
I am creating this application which has three tabs. Tab1 is used to handle bluetooth incoming and outgoing connections. The major problem comes here is once i click the connect button the connection is created but when i switch tabs and then jump back to tab1 everything is lost as the tab is reinitialized. I want to stop this from happening. Please suggest me the correction in my code.
Here is the MainActivity.java file
public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener{
private TabLayout tabLayout;
StringBuilder recDataString = new StringBuilder();
int handlerState = 0;
private ViewPager viewPager;
int initialize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing the tablayout
tabLayout = (TabLayout)findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Manual"));
tabLayout.setSelectedTabIndicatorColor(Color.BLACK);
tabLayout.addTab(tabLayout.newTab().setText("Status"));
tabLayout.addTab(tabLayout.newTab().setText("Database"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager)findViewById(R.id.pager);
Pager adapter = new Pager(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
tabLayout.setOnTabSelectedListener(this);
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String id = intent.getStringExtra("BS");
Log.d("********", "ID = " + id);
/*if (id.equalsIgnoreCase("F")) {
sendToConnectedThread(id);
}*/
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.nitesh.finaltab.DATA_BROADCAST");
getApplicationContext().registerReceiver(broadcastReceiver,filter);
}
public int getInitialize(){
return initialize;
}
public void setInitialize(int m){
this.initialize = m;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Here is the Pager.java file
public class Pager extends FragmentStatePagerAdapter {
int tabcount;
public Pager(FragmentManager fm, int tabcount){
super(fm);
this.tabcount = tabcount;
}
#Override
public Fragment getItem(int position){
switch (position){
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
case 2:
Tab3 tab3 = new Tab3();
return tab3;
default:
return null;
}
}
#Override
public int getCount(){return tabcount;}
}
And here is the Tab1.java file
public class Tab1 extends Fragment {
SQLiteDatabase alexadb,activitydb;
MainActivity mainActivity= new MainActivity();
StringBuilder recDataString = new StringBuilder();
String address = "98:D3:32:20:5A:57";
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
int handlerState = 0;
public boolean isBtConnected = false;
ProgressDialog progressDialog;
int initialize = 0;
Handler bluetoothIn;
BluetoothAdapter myBluetooth;
BluetoothSocket bluetoothSocket;
ConnectedThread connectedThread ;
Button connect,forward,reverse,left,right,stop;
int speed;
String datatoSend;
private final long REPEAT_DELAY = 50;
boolean autoIncreament,autoDecreament;
View view;
private Handler repeatUpdateHandler = new Handler();
private Handler senddataUpdatehandler = new Handler();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
createDatabase();
view = inflater.inflate(R.layout.tab1, container, false);
forward = (Button) view.findViewById(R.id.bforward);
reverse = (Button) view.findViewById(R.id.breverse);
left = (Button) view.findViewById(R.id.bleft);
stop = (Button) view.findViewById(R.id.bstop);
connect = (Button)view.findViewById(R.id.buttonConnect);
right = (Button) view.findViewById(R.id.bright);
Toast.makeText(getContext(), "Tab1 Initiated", Toast.LENGTH_SHORT).show();
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
alertDialogBuilder.setMessage("Ready to connect?");
handler();
class RepetitiveUpdater implements Runnable {
#Override
public void run() {
if (autoIncreament) {
increment();
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
} else if (autoDecreament) {
decrement();
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
}
}
}
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Process Initiated", Toast.LENGTH_SHORT).show();
new CheckBT().execute();
}
});
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// bluetoothConnect.sendData("R");
Log.d("Right", "Button is clicked");
sendData("R");
insertIntoActivityDB("Right Button is clicked");
}
});
left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendData("L");
insertIntoActivityDB("Left Button is clicked");
}
});
reverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendData("B");
insertIntoActivityDB("Reverse Button is clicked");
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
autoDecreament = false;
autoIncreament = false;
sendData("S");
insertIntoActivityDB("Stop Button is clicked");
}
});
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increment();
sendData("F");
insertIntoActivityDB("Forward Button is clicked");
}
});
forward.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
autoIncreament = true;
autoDecreament = false;
repeatUpdateHandler.post(new RepetitiveUpdater());
return false;
}
});
forward.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP && autoIncreament) {
autoIncreament = false;
autoDecreament = true;
sendData("D");
repeatUpdateHandler.post(new RepetitiveUpdater());
}
return false;
}
});
return view;
}
public void handler() {
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
String readMessage = (String) msg.obj;
recDataString.append(readMessage);
int endofLineIndex = recDataString.indexOf("~");
if (endofLineIndex > 0) {
// String dataInPrint = recDataString.substring(0,endofLineIndex);
String data = recDataString.substring(1, endofLineIndex);
Log.d("Received Text", "" + data);
String first = recDataString.substring(0, 1);
Log.d("First letter ", "Hello" + first);
if (first.equalsIgnoreCase("P")) {
insertIntoAlexaDB(data);
}
if (first.equalsIgnoreCase("V")) {
insertIntoAlexaDB(data);
} else {
}
recDataString.delete(0, recDataString.length());
// dataInPrint = " ";
data = "";
first = " ";
}
}
}
};
}
public void increment(){
speed++;
sendData("F");
Log.d("Increasing Speed"," "+speed);
}
public void decrement() {
if (speed > 0) {
speed--;
sendData("D");
Log.d("Decreasing Speed", " " + speed);
}
}
public class CheckBT extends AsyncTask<Void, Void, Void>//UI Thread
{
private boolean ConnectSuccess = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(getContext(), "Connecting you", "From Alexa");
Toast.makeText(getContext(),"Conneting",Toast.LENGTH_SHORT).show();
}
#Override
protected Void doInBackground(Void... params) {
try {
if (bluetoothSocket == null || !isBtConnected) {
myBluetooth = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = myBluetooth.getRemoteDevice(address);
bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(myUUID); //Create RFCOMM connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
bluetoothSocket.connect();
}
} catch (IOException e) {
ConnectSuccess = false;
Toast.makeText(getContext(), "HC-05 didn't respond", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!ConnectSuccess) {
Toast.makeText(getContext(), "Connection Failed. Try Again", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Connected", Toast.LENGTH_SHORT).show();
isBtConnected = true;
connectedThread = new ConnectedThread(bluetoothSocket);
connectedThread.start();
}
progressDialog.dismiss();
}
}
private class ConnectedThread extends Thread{
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the thread
public ConnectedThread(BluetoothSocket bluetoothSocket){
InputStream tmpIn = null;
OutputStream tmpOut = null;
try{
//create I/O streams for connection
tmpIn = bluetoothSocket.getInputStream();
tmpOut = bluetoothSocket.getOutputStream();
}catch (IOException
e){}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public boolean getBluetoothStatus() {
Toast.makeText(getContext(),"Bluetooth Status from thread"+isBtConnected,Toast.LENGTH_SHORT).show();
return isBtConnected;
}
public void run(){
byte[] buffer = new byte[256];
int bytes;
//keep looping ot listen for received messages
while(true){
try{
Log.d("Running"," Connected_Thread");
isBtConnected = true;
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer,0,bytes);
//Send the obtained bytes to the UIActivity via handler
bluetoothIn.obtainMessage(handlerState,bytes,-1,readMessage).sendToTarget();
}catch (IOException e){
break;
}
}
}
}
public void sendData(String data) {
try {
bluetoothSocket.getOutputStream().write(data.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
/**Creation of DATABASE**/
public void createDatabase(){
alexadb = getContext().openOrCreateDatabase("AlexaDB", Context.MODE_PRIVATE,null);
activitydb= getContext().openOrCreateDatabase("ActivityDB",Context.MODE_PRIVATE,null);
alexadb.execSQL("CREATE TABLE IF NOT EXISTS alexa(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,data VARCHAR);");
activitydb.execSQL("CREATE TABLE IF NOT EXISTS activity(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,data VARCHAR);");
}
public boolean insertIntoAlexaDB( String data){
if (data.equalsIgnoreCase(" ")) {
return false;
} else {
String query = "INSERT INTO alexa(data)VALUES('" + data + "');";
alexadb.execSQL(query);
return true;
}
}
public boolean insertIntoActivityDB(String data){
if (data.equalsIgnoreCase(" ")) {
return false;
} else {
String query = "INSERT INTO activity(data)VALUES('" + data + "');";
activitydb.execSQL(query);
return true;
}
}
}
Is this happening only when you select the last tab? Take a look at the offscreen page limit parameter: basically you can set the number of pages to retain in memory when you scroll the ViewPager. In your case, an offscreen page limit of 2 should be enough to always keep all the pages in memory.
I am trying to create a music player in ViewPager when the user swipes, the player should play the next song. The views are updating correctly but the song is not sync with them. For example, it's playing the second song in the first fragment. I tried a lot of things but I'm not able to find where is the issue. Please anyone give me a solution. Thanks in advance.
public class AudioActivity extends AppCompatActivity {
List<PlayerModel> audioList;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio);
audioList=getIntent().getParcelableArrayListExtra(getString(R.string.SONG_LIST));
position=getIntent().getIntExtra(getString(R.string.SONG_POSITION),0);
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
}
AudioActivity.ViewPagerAdapter adapter;
private void setupViewPager(ViewPager viewPager) {
adapter = new AudioActivity.ViewPagerAdapter(getSupportFragmentManager());
AudioPlayerAdapter audioPlayerAdapter=new AudioPlayerAdapter();
for(int i=0;i<audioList.size();i++) {
adapter.addFragment(audioPlayerAdapter.newInstance(audioList, i), AppConstants.AUDIO_PLAYER);
}
viewPager.setAdapter(adapter);
viewPager.setPageTransformer(true, new CubeInTransformer());
}
class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void setFragment(Fragment fragment, int position,String title) {
mFragmentList.set(position,fragment);
mFragmentTitleList.set(position,title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
My Fragment
public class AudioPlayerAdapter extends Fragment implements SeekBar.OnSeekBarChangeListener {
Button btnStart, btnStop, btnBind, btnUnbind, btnUpby1, btnUpby10;
TextView textStatus, textIntValue, textStrValue;
Messenger mService = null;
boolean mIsBound;
public static Handler messageHandler;
long duration, currSongPosition;
ImageView displayArt;
TextView playerName;
TextView totTime;
TextView fromTime;
List<PlayerModel> songList;
RecyclerView songRecyclerView;
ImageButton showList;
ImageButton playAudio;
ImageButton pauseAudio;
ImageButton stepForward;
ImageButton stepBackward;
ImageButton shuffleAudio;
ImageButton volumeAudio;
ImageButton repeatAudio;
int songPosition;
SeekBar songProgressBar;
SeekBar volumeSeekBar;
private Intent playIntent;
//binding
private boolean musicBound = false;
private float x1, x2;
static final int MIN_DISTANCE = 150;
//activity and playback pause flags
private boolean paused = false, playbackPaused = false;
private Handler mHandler = new Handler();
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private boolean isShuffle = false;
private boolean isRepeat = false;
public AudioPlayerAdapter newInstance(List<PlayerModel> playerList, int position) {
AudioPlayerAdapter fragment = new AudioPlayerAdapter();
Bundle b = new Bundle();
b.putParcelableArrayList(AppConstants.SONG_LIST, (ArrayList<? extends Parcelable>) playerList);
b.putInt(AppConstants.SONG_POSITION, position);
fragment.setArguments(b);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.activity_music_player, container, false);
songList = getArguments().getParcelableArrayList(getString(R.string.SONG_LIST));
songPosition = getArguments().getInt(getString(R.string.SONG_POSITION), 0);
LogUtil.error("Song Position",songPosition+"-->"+songList.get(songPosition).getPlayerTitle());
FieldIntialization(view);
if (playIntent == null) {
playIntent = new Intent(getActivity(), MusicService.class);
playIntent.setAction(String.valueOf(MusicService.MSG_FOREGROUND));
playIntent.putParcelableArrayListExtra(getString(R.string.SONG_LIST), (ArrayList<? extends Parcelable>) songList);
playIntent.putExtra(getString(R.string.SONG_POSITION), songPosition);
getActivity().startService(playIntent);
}
DataInitialization(songPosition);
messageHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MusicService.MSG_SET_INT_VALUE:
break;
case MusicService.MSG_PLAY:
LogUtil.error("Pause", "Pause");
playAudio.setImageResource(R.drawable.ic_pause_white_24dp);
break;
case MusicService.MSG_PAUSE:
LogUtil.error("Play", "Play");
playAudio.setImageResource(R.drawable.ic_play_white_24dp);
break;
case MusicService.MSG_NEXT:
songPosition = msg.getData().getInt(getString(R.string.SONG_POSITION));
LogUtil.error("SonPos", String.valueOf(songPosition));
updatePlayerView(songPosition);
break;
case MusicService.MSG_PREVIOUS:
songPosition = msg.getData().getInt(getString(R.string.SONG_POSITION));
LogUtil.error("SonPos", String.valueOf(songPosition));
updatePlayerView(songPosition);
break;
case MusicService.MSG_UPDATE_SEEKBAR:
duration = msg.getData().getLong(getString(R.string.SONG_DURATION));
currSongPosition = msg.getData().getLong(getString(R.string.SONG_CURR_DURATION));
break;
case MusicService.MSG_SHUFFLE_OFF:
Toast.makeText(getActivity(), "Shuffle Off", Toast.LENGTH_SHORT).show();
break;
case MusicService.MSG_SHUFFLE_ON:
Toast.makeText(getActivity(), "Shuffle On", Toast.LENGTH_SHORT).show();
break;
case MusicService.MSG_REPEAT_ON:
Toast.makeText(getActivity(), "Repeat On", Toast.LENGTH_SHORT).show();
break;
case MusicService.MSG_REPEAT_OFF:
Toast.makeText(getActivity(), "Repeat Off", Toast.LENGTH_SHORT).show();
break;
case MusicService.MSG_CLOSE:
getActivity().finish();
break;
case MusicService.MSG_STOP:
break;
default:
super.handleMessage(msg);
}
}
};
return view;
}
/* #Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
*//* outState.putString("textStatus", textStatus.getText().toString());
outState.putString("textIntValue", textIntValue.getText().toString());
outState.putString("textStrValue", textStrValue.getText().toString());*//*
}
private void restoreMe(Bundle state) {
if (state != null) {*//*
textStatus.setText(state.getString("textStatus"));
textIntValue.setText(state.getString("textIntValue"));
textStrValue.setText(state.getString("textStrValue"));*//*
}
}*/
public void stopService() {
getActivity().stopService(new Intent(getActivity(), MusicService.class));
}
private void sendMessageToService(int action) {
Intent startIntent = new Intent(getActivity(), MusicService.class);
startIntent.setAction(String.valueOf(action));
getActivity().startService(startIntent);
}
private void sendMessageToServiceWithData(int action, int currPosition) {
Intent startIntent = new Intent(getActivity(), MusicService.class);
startIntent.setAction(String.valueOf(action));
startIntent.putExtra(getString(R.string.SEEK_POSITION), currPosition);
getActivity().startService(startIntent);
}
private void FieldIntialization(View view) {
songProgressBar = (SeekBar) view.findViewById(R.id.seekBar);
volumeSeekBar = (SeekBar) view.findViewById(R.id.volumeSeekBar);
displayArt = (ImageView) view.findViewById(R.id.songImage);
playerName = (TextView) view.findViewById(R.id.songName);
totTime = (TextView) view.findViewById(R.id.endTime);
fromTime = (TextView) view.findViewById(R.id.startTime);
songRecyclerView = (RecyclerView) view.findViewById(R.id.songRecyclerView);
showList = (ImageButton) view.findViewById(R.id.showList);
stepForward = (ImageButton) view.findViewById(R.id.step_next);
stepBackward = (ImageButton) view.findViewById(R.id.step_prev);
shuffleAudio = (ImageButton) view.findViewById(R.id.shuffle);
repeatAudio = (ImageButton) view.findViewById(R.id.repeat);
playAudio = (ImageButton) view.findViewById(R.id.play_pause);
volumeAudio = (ImageButton) view.findViewById(R.id.speaker);
playAudio.setImageResource(R.drawable.ic_pause_white_24dp);
songRecyclerView.addItemDecoration(new MarginDecoration(getActivity()));
songRecyclerView.setHasFixedSize(true);
songRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.HORIZONTAL, false));
SongRecyclerAdapter songRecyclerAdapter = new SongRecyclerAdapter(songList,
getActivity()
);
if (songList.size() > 0) {
LinearLayout.LayoutParams lp =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
songRecyclerView.setLayoutParams(lp);
} else {
LinearLayout.LayoutParams lp =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
songRecyclerView.setLayoutParams(lp);
}
songRecyclerView.setAdapter(songRecyclerAdapter);
songRecyclerAdapter.setOnDataChangeListener(new onRefreshFavListener() {
#Override
public void onFavRefresh(int position) {
playIntent = new Intent(getActivity(), MusicService.class);
playIntent.setAction(String.valueOf(MusicService.MSG_FOREGROUND));
playIntent.putParcelableArrayListExtra(getString(R.string.SONG_LIST), (ArrayList<? extends Parcelable>) songList);
playIntent.putExtra(getString(R.string.SONG_POSITION), position);
getActivity().startService(playIntent);
updatePlayerView(position);
}
});
}
private void DataInitialization(final int position) {
showList.setBackgroundResource(R.drawable.ic_up_white_24dp);
showList.setTag(R.drawable.ic_up_white_24dp);
songRecyclerView.setVisibility(View.GONE);
LogUtil.error("Update",position+"-->"+songList.get(position));
updatePlayerView(position);
showList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((int) showList.getTag() == R.drawable.ic_up_white_24dp) {
showList.setBackgroundResource(R.drawable.ic_down_white_24dp);
showList.setTag(R.drawable.ic_down_white_24dp);
songRecyclerView.setVisibility(View.VISIBLE);
} else {
showList.setBackgroundResource(R.drawable.ic_up_white_24dp);
showList.setTag(R.drawable.ic_up_white_24dp);
songRecyclerView.setVisibility(View.GONE);
}
}
});
songProgressBar.setOnSeekBarChangeListener(this);
final AudioManager audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
volumeSeekBar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekBar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
playAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
sendMessageToService(MusicService.MSG_CHECK_PLAYING_STATUS);
}
});
stepForward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToService(MusicService.MSG_NEXT);
}
});
stepBackward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToService(MusicService.MSG_PREVIOUS);
}
});
shuffleAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToService(MusicService.MSG_SHUFFLE);
}
});
repeatAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToService(MusicService.MSG_REPEAT);
}
});
}
public void updatePlayerView(int songIndex) {
playAudio.setImageResource(R.drawable.ic_pause_white_24dp);
LogUtil.error("Song List",songIndex+"-->"+songList.get(songIndex).getPlayerTitle());
playerName.setText(songList.get(songIndex).getPlayerTitle());
totTime.setText(Utility.convertDuration(Long.parseLong(songList.get(songIndex).getPlayerDuration())));
Cursor cursor = getActivity().getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART},
MediaStore.Audio.Albums._ID + "=?",
new String[]{String.valueOf(songList.get(songIndex).getPlayerAlbumId())},
null);
cursor.moveToFirst();
displayArt.setScaleType(ImageView.ScaleType.FIT_XY);
displayArt.setImageBitmap(Constants.getDefaultAlbumArt(getActivity(), songList.get(songIndex).getPlayerAlbumId()));
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
}
public void updateProgressBar() {
// mHandler.postDelayed(mUpdateTimeTask, 100);
}
/**
* Background Runnable thread
*/
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
sendMessageToService(MusicService.MSG_UPDATE_SEEKBAR);
// Displaying Total Duration time
totTime.setText("" + Utility.milliSecondsToTimer(duration));
// Displaying time completed playing
fromTime.setText("" + Utility.milliSecondsToTimer(currSongPosition));
// Updating progress bar
int progress = (int) (Utility.getProgressPercentage(currSongPosition, duration));
//Log.d("Progress", ""+progress);
songProgressBar.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
}
/**
* When user starts moving the progress handler
*/
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// remove message Handler from updating progress bar
// mHandler.removeCallbacks(mUpdateTimeTask);
}
/**
* When user stops moving the progress hanlder
*/
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// mHandler.removeCallbacks(mUpdateTimeTask);
int currentPosition = Utility.progressToTimer(seekBar.getProgress(), (int) duration);
sendMessageToServiceWithData(MusicService.MSG_SEEK, currentPosition);
// update timer progress again
updateProgressBar();
}
}
I'm trying to update my listview after I change the 'dataset' but it doesn't, unless I manually refresh the view or refresh the activity.
This doesn't work:
runOnUiThread(new Runnable() {
public void run() {
entriesListAdapter.notifyDataSetChanged();
}
});
While this does:
handler.postDelayed(new Runnable() {
#Override
public void run() {
onCreate(null);
entriesListAdapter.notifyDataSetChanged();
}
}, 1000);
But this is absolutely not the right way to do it. Am I using notifydatasetchanged wrong?
My whole activity:
package app.wordpress;
import app.wordpress.service.FetcherService;
import someontherimports
public class EntriesListActivity extends ListActivity {
private static final int CONTEXTMENU_REFRESH_ID = 4;
private static final int CONTEXTMENU_MARKASREAD_ID = 6;
private static final int ACTIVITY_APPLICATIONPREFERENCES_ID = 1;
private static final Uri CANGELOG_URI = Uri.parse("http://wordpress.com");
private static final int CONTEXTMENU_MARKASUNREAD_ID = 7;
private static final int CONTEXTMENU_DELETE_ID = 8;
private static final int CONTEXTMENU_COPYURL = 9;
private static final int DIALOG_ABOUT = 7;
public static final String EXTRA_SHOWREAD = "show_read";
public static final String EXTRA_SHOWFEEDINFO = "show_feedinfo";
public static final String EXTRA_AUTORELOAD = "autoreload";
private static final String[] FEED_PROJECTION = {FeedData.FeedColumns.NAME,
FeedData.FeedColumns.URL,
FeedData.FeedColumns.ICON
};
private Uri uri;
private EntriesListAdapter entriesListAdapter;
private byte[] iconBytes;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (MainTabActivity.isLightTheme(this)) {
setTheme(R.style.Theme_Light);
}
super.onCreate(savedInstanceState);
String title = null;
iconBytes = null;
Intent intent = getIntent();
long feedId = intent.getLongExtra(FeedData.FeedColumns._ID, 0);
if (feedId > 0) {
Cursor cursor = getContentResolver().query(FeedData.FeedColumns.CONTENT_URI(feedId), FEED_PROJECTION, null, null, null);
if (cursor.moveToFirst()) {
title = cursor.isNull(0) ? cursor.getString(1) : cursor.getString(0);
iconBytes = cursor.getBlob(2);
}
cursor.close();
}
if (!MainTabActivity.POSTGINGERBREAD && iconBytes != null && iconBytes.length > 0) { // we cannot insert the icon here because it would be overwritten, but we have to reserve the icon here
if (!requestWindowFeature(Window.FEATURE_LEFT_ICON)) {
iconBytes = null;
}
}
setContentView(R.layout.entries);
uri = intent.getData();
entriesListAdapter = new EntriesListAdapter(this, uri, intent.getBooleanExtra(EXTRA_SHOWFEEDINFO, false), intent.getBooleanExtra(EXTRA_AUTORELOAD, false));
setListAdapter(entriesListAdapter);
if (title != null) {
setTitle(title);
}
if (iconBytes != null && iconBytes.length > 0) {
int bitmapSizeInDip = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24f, getResources().getDisplayMetrics());
Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length);
if (bitmap != null) {
if (bitmap.getHeight() != bitmapSizeInDip) {
bitmap = Bitmap.createScaledBitmap(bitmap, bitmapSizeInDip, bitmapSizeInDip, false);
}
if (MainTabActivity.POSTGINGERBREAD) {
CompatibilityHelper.setActionBarDrawable(this, new BitmapDrawable(bitmap));
} else {
setFeatureDrawable(Window.FEATURE_LEFT_ICON, new BitmapDrawable(bitmap));
}
}
}
if (RSSOverview.notificationManager != null) {
RSSOverview.notificationManager.cancel(0);
}
getListView().setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
menu.setHeaderTitle(((TextView) ((AdapterView.AdapterContextMenuInfo) menuInfo).targetView.findViewById(android.R.id.text1)).getText());
menu.add(0, CONTEXTMENU_REFRESH_ID, Menu.NONE, R.string.contextmenu_refresh);
menu.add(0, CONTEXTMENU_MARKASREAD_ID, Menu.NONE, R.string.contextmenu_markasread).setIcon(android.R.drawable.ic_menu_manage);
menu.add(0, CONTEXTMENU_MARKASUNREAD_ID, Menu.NONE, R.string.contextmenu_markasunread).setIcon(android.R.drawable.ic_menu_manage);
menu.add(0, CONTEXTMENU_DELETE_ID, Menu.NONE, R.string.contextmenu_delete).setIcon(android.R.drawable.ic_menu_delete);
menu.add(0, CONTEXTMENU_COPYURL, Menu.NONE, R.string.contextmenu_copyurl).setIcon(android.R.drawable.ic_menu_share);
}
});
}
#Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
TextView textView = (TextView) view.findViewById(android.R.id.text1);
textView.setTypeface(Typeface.DEFAULT);
textView.setEnabled(false);
view.findViewById(android.R.id.text2).setEnabled(false);
entriesListAdapter.neutralizeReadState();
startActivity(new Intent(Intent.ACTION_VIEW, ContentUris.withAppendedId(uri, id)).putExtra(EXTRA_SHOWREAD, entriesListAdapter.isShowRead()).putExtra(FeedData.FeedColumns.ICON, iconBytes));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.entrylist, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.setGroupVisible(R.id.menu_group_0, entriesListAdapter.getCount() > 0);
return true;
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_markasread: {
new Thread() { // the update process takes some time
public void run() {
getContentResolver().update(uri, RSSOverview.getReadContentValues(), null, null);
}
}.start();
entriesListAdapter.markAsRead();
break;
}
case R.id.menu_markasunread: {
new Thread() { // the update process takes some time
public void run() {
getContentResolver().update(uri, RSSOverview.getUnreadContentValues(), null, null);
}
}.start();
entriesListAdapter.markAsUnread();
break;
}
case R.id.menu_hideread: {
if (item.isChecked()) {
item.setChecked(false).setTitle(R.string.contextmenu_hideread).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
entriesListAdapter.showRead(true);
} else {
item.setChecked(true).setTitle(R.string.contextmenu_showread).setIcon(android.R.drawable.ic_menu_view);
entriesListAdapter.showRead(false);
}
break;
}
case R.id.menu_deleteread: {
new Thread() { // the delete process takes some time
public void run() {
String selection = Strings.READDATE_GREATERZERO+Strings.DB_AND+" ("+Strings.DB_EXCUDEFAVORITE+")";
getContentResolver().delete(uri, selection, null);
FeedData.deletePicturesOfFeed(EntriesListActivity.this, uri, selection);
runOnUiThread(new Runnable() {
public void run() {
entriesListAdapter.getCursor().requery();
}
});
}
}.start();
break;
}
case R.id.menu_deleteallentries: {
Builder builder = new AlertDialog.Builder(this);
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle(R.string.contextmenu_deleteallentries);
builder.setMessage(R.string.question_areyousure);
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new Thread() {
public void run() {
getContentResolver().delete(uri, Strings.DB_EXCUDEFAVORITE, null);
runOnUiThread(new Runnable() {
public void run() {
entriesListAdapter.getCursor().requery();
}
});
}
}.start();
}
});
builder.setNegativeButton(android.R.string.no, null);
builder.show();
break;
}
case CONTEXTMENU_MARKASREAD_ID: {
long id = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id;
getContentResolver().update(ContentUris.withAppendedId(uri, id), RSSOverview.getReadContentValues(), null, null);
entriesListAdapter.markAsRead(id);
break;
}
case CONTEXTMENU_MARKASUNREAD_ID: {
long id = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id;
getContentResolver().update(ContentUris.withAppendedId(uri, id), RSSOverview.getUnreadContentValues(), null, null);
entriesListAdapter.markAsUnread(id);
break;
}
case CONTEXTMENU_DELETE_ID: {
long id = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id;
getContentResolver().delete(ContentUris.withAppendedId(uri, id), null, null);
FeedData.deletePicturesOfEntry(Long.toString(id));
entriesListAdapter.getCursor().requery(); // he have no other choice
break;
}
case CONTEXTMENU_COPYURL: {
((ClipboardManager) getSystemService(CLIPBOARD_SERVICE)).setText(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).targetView.getTag().toString());
break;
}
case R.id.menu_settings: {
startActivityForResult(new Intent(this, ApplicationPreferencesActivity.class), ACTIVITY_APPLICATIONPREFERENCES_ID);
break;
}
case R.id.menu_about: {
showDialog(DIALOG_ABOUT);
break;
}
case R.id.menu_refresh: {
new Thread() {
public void run() {
sendBroadcast(new Intent(Strings.ACTION_REFRESHFEEDS).putExtra(Strings.SETTINGS_OVERRIDEWIFIONLY, PreferenceManager.getDefaultSharedPreferences(EntriesListActivity.this).getBoolean(Strings.SETTINGS_OVERRIDEWIFIONLY, false)));
}
}.start();
runOnUiThread(new Runnable() {
public void run() {
entriesListAdapter.notifyDataSetChanged();
}
});
break;
}
}
return true;
}
#Override
protected void onResume()
{
super.onResume();
setProgressBarIndeterminateVisibility(isCurrentlyRefreshing());
registerReceiver(refreshReceiver, new IntentFilter("app.wordpress.REFRESH"));
}
#Override
protected void onPause()
{
unregisterReceiver(refreshReceiver);
super.onPause();
}
private BroadcastReceiver refreshReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
setProgressBarIndeterminateVisibility(true);
}
};
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
switch (id) {
case DIALOG_ABOUT: {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setTitle(R.string.menu_about);
MainTabActivity.INSTANCE.setupLicenseText(builder);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setNeutralButton(R.string.changelog, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Intent.ACTION_VIEW, CANGELOG_URI));
}
});
return builder.create();
}
default: dialog = null;
}
return dialog;
}
private boolean isCurrentlyRefreshing()
{
ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service: manager.getRunningServices(Integer.MAX_VALUE)) {
if (FetcherService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
Are you referring to this block of code in your Activity?
case R.id.menu_refresh: {
new Thread() {
public void run() {
sendBroadcast(new Intent(Strings.ACTION_REFRESHFEEDS).putExtra(Strings.SETTINGS_OVERRIDEWIFIONLY, PreferenceManager.getDefaultSharedPreferences(EntriesListActivity.this).getBoolean(Strings.SETTINGS_OVERRIDEWIFIONLY, false)));
}
}.start();
runOnUiThread(new Runnable() {
public void run() {
entriesListAdapter.notifyDataSetChanged();
}
});
break;
If so, the problem is likely that the call to runOnUiThread() is not actually inside of the Thread you created, it's called on the main thread.
The way this code is structured, upon selecting refresh, the background thread is created to fire a broadcast Intent (not necessary, BTW, because that is also an asynchronous process...it returns immediately) and then notifyDataSetChanged() is immediately run after that (because runOnUiThread() when called from the main thread just executes the Runnable right away).
So you are sending a broadcast and updating the adapter at basically the same time...not much time for anything to have actually changed in that period. If you were expecting sendBroadcast() to block and return after some receiver had processed it, this is not the case.
In you contentProvider, you should call contentResolver.notifyChange to notify the adapter that there have been a change to the data provided by the contentResolver, this will update the listView for you.