If Progressdialog is not showing (android) - android

I have a ProgressDialog, and I want to do something when the dialog dissappears (but I do not want put my action after the progressdialog.dismiss).
Is it possible to:
----> if No ---> Do something
Check if dialog is showing
----> if Yes
/|\ |
| \|/
--------------------- Wait
Don't think to difficult, I just want to perform an action, but only if there is no dialog, and if there is one, to perform the action when the dialog is done.
Thank you!
EDIT: My activity:
import verymuchimportshere..
public class ScroidWallpaperGallery extends Activity {
private WallpaperGalleryAdapter wallpaperGalleryAdapter;
private final WallpaperManager wallpaperManager;
private final ICommunicationDAO communicationDAO;
private final IFavouriteDAO favouriteDAO;
private final List<Integer> preloadedList;
private Wallpaper selectedWallpaper;
private static final int PICK_CONTACT = 0;
private static final int DIALOG_ABOUT = 0;
public ScroidWallpaperGallery() {
super();
if (!DependencyInjector.isInitialized()) {
DependencyInjector.init(this);
}
this.wallpaperManager = DependencyInjector.getInstance(WallpaperManager.class);
this.communicationDAO = DependencyInjector.getInstance(ICommunicationDAO.class);
this.favouriteDAO = DependencyInjector.getInstance(IFavouriteDAO.class);
this.preloadedList = new ArrayList<Integer>();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
this.initGallery();
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage(this.getString(R.string.loadingText));
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
else {
SharedPreferences settings = getSharedPreferences("firstrun", MODE_PRIVATE);
if (settings.getBoolean("isFirstRun", true)) {
new AlertDialog.Builder(this).setTitle("How to").setMessage("Long press item to add/remove from favorites.").setNeutralButton("Ok", null).show();
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isFirstRun", false);
editor.commit();
}
}
if (this.wallpaperGalleryAdapter != null) {
this.updateGalleryAdapter();
return;
}
AdView adView = (AdView)this.findViewById(R.id.adView);
adView.loadAd(new AdRequest());
new FillGalleryTask(progressDialog, this).start();
}
private void updateGalleryAdapter() {
this.updateGalleryAdapter(this.wallpaperManager.getWallpapers());
}
private synchronized void updateGalleryAdapter(Wallpaper[] wallpapers) {
this.wallpaperGalleryAdapter = new WallpaperGalleryAdapter(this, wallpapers, this.wallpaperManager);
Gallery gallery = (Gallery)this.findViewById(R.id.gallery);
gallery.setAdapter(this.wallpaperGalleryAdapter);
}
private void initGallery() {
Gallery gallery = (Gallery)this.findViewById(R.id.gallery);
gallery.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Wallpaper wallpaper = (Wallpaper)parent.getItemAtPosition(position);
showPreviewActivity(wallpaper);
}
});
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
selectedWallpaper = (Wallpaper)wallpaperGalleryAdapter.getItem(position);
new Thread(new Runnable() {
#Override
public void run() {
preloadThumbs(wallpaperGalleryAdapter.getWallpapers(), (position + 1), 3);
}
}).start();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
selectedWallpaper = null;
}
});
this.registerForContextMenu(gallery);
}
private void showPreviewActivity(Wallpaper wallpaper) {
WallpaperPreviewActivity.showPreviewActivity(this, wallpaper);
}
private void preloadThumbs(Wallpaper[] wallpapers, int index, int maxCount) {
for (int i = index; (i < (index + maxCount)) && (i < wallpapers.length); i++) {
if (this.preloadedList.contains(i)) {
continue;
}
try {
this.wallpaperManager.getThumbImage(wallpapers[i]);
this.preloadedList.add(i);
}
catch (ClientProtocolException ex) {
// nothing to do - image will be loaded on select
}
catch (IOException ex) {
// nothing to do - image will be loaded on select
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (this.selectedWallpaper == null
|| !(v instanceof Gallery)) {
return;
}
MenuInflater menuInflater = new MenuInflater(this);
menuInflater.inflate(R.menu.gallery_context_menu, menu);
if (this.favouriteDAO.isFavourite(this.selectedWallpaper.getId())) {
menu.findItem(R.id.galleryRemoveFavouriteMenuItem).setVisible(true);
}
else {
menu.findItem(R.id.galleryAddFavouriteMenuItem).setVisible(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (this.selectedWallpaper == null) {
return false;
}
switch (item.getItemId()) {
case R.id.galleryAddFavouriteMenuItem:
this.favouriteDAO.add(this.selectedWallpaper.getId());
return true;
case R.id.galleryRemoveFavouriteMenuItem:
this.favouriteDAO.remove(this.selectedWallpaper.getId());
return true;
}
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.aboutMenuItem:
this.showDialog(DIALOG_ABOUT);
return true;
case R.id.settingsMenuItem:
this.startActivity(new Intent(this, SettingsActivity.class));
return true;
case R.id.recommendMenuItem:
this.recommendWallpaper();
return true;
case R.id.favouritesMenuItem:
FavouriteListActivity.showFavouriteListActivity(this);
return true;
case R.id.closeMenuItem:
this.finish();
return true;
}
return false;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ABOUT:
return new AboutDialog(this);
default:
return null;
}
}
private void recommendWallpaper() {
if (this.selectedWallpaper == null) {
return;
}
Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
this.startActivityForResult(intent, PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_CONTACT:
this.onPickContactActivityResult(resultCode, data);
break;
}
}
private void onPickContactActivityResult(int resultCode, Intent data) {
if (resultCode == 0) {
return;
}
Communication[] communications = this.communicationDAO.getCommunications(data.getData());
if (communications.length < 1) {
AlertDialogFactory.showInfoMessage(this, R.string.infoText, R.string.noCommunicationFoundInfoText);
return;
}
CommunicationChooseDialog dialog = new CommunicationChooseDialog(this, communications, new CommunicationChosenListener() {
#Override
public void onCommunicationChosen(Communication communication) {
handleOnCommunicationChosen(communication);
}
});
dialog.show();
}
private void handleOnCommunicationChosen(Communication communication) {
Wallpaper wallpaper = this.selectedWallpaper;
if (communication.getType().equals(Communication.Type.Email)) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { communication.getValue() });
intent.putExtra(Intent.EXTRA_SUBJECT, getBaseContext().getString(R.string.applicationName));
intent.putExtra(Intent.EXTRA_TEXT, String.format(getBaseContext().getString(R.string.recommendEmailPattern),
wallpaper.getWallpaperUrl()));
intent.setType("message/rfc822");
this.startActivity(intent);
}
else if (communication.getType().equals(Communication.Type.Mobile)) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("address", communication.getValue());
intent.putExtra("sms_body", String.format(getBaseContext().getString(R.string.recommendSmsPattern),
wallpaper.getWallpaperUrl()));
intent.setType("vnd.android-dir/mms-sms");
this.startActivity(intent);
}
}
private class FillGalleryTask extends LongTimeRunningOperation<Wallpaper[]> {
private final Context context;
public FillGalleryTask(Dialog progressDialog, Context context) {
super(progressDialog);
this.context = context;
}
#Override
public void afterOperationSuccessfullyCompleted(Wallpaper[] result) {
updateGalleryAdapter(result);
}
#Override
public void handleUncaughtException(Throwable ex) {
if (ex instanceof WallpaperListReceivingException) {
AlertDialogFactory.showErrorMessage(this.context,
R.string.errorText,
ex.getMessage(),
new ShutDownAlertDialogOnClickListener());
}
else if (ex instanceof IOException) {
AlertDialogFactory.showErrorMessage(this.context,
R.string.errorText,
R.string.downloadException,
new ShutDownAlertDialogOnClickListener());
}
else {
throw new RuntimeException(ex);
}
}
#Override
public Wallpaper[] onRun() throws Exception {
// retrieving available wallpapers from server
wallpaperManager.loadAvailableWallpapers(getBaseContext());
Wallpaper[] wallpapers = wallpaperManager.getWallpapers();
// preloading first 3 thumbs
preloadThumbs(wallpapers, 0, 3);
return wallpapers;
}
}
private class ShutDownAlertDialogOnClickListener implements DialogInterface.OnClickListener {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
}
}

Try this,
private void doSomethingWhenProgressNotShown() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
//is running
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doSomethingWhenProgressNotShown();
}
}, 500);
}
//isnt running- do something here
}

I think you can use this code:
if (mProgressDialog != null && mProgressDialog.isShowing()) {
//is running
}
//isnt running
Or you can set listeners:
mProgressDialog.setOnCancelListener(listener);
mProgressDialog.setOnDismissListener(listener);

Related

when back to activity from click music notification when click to next music view not update

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;
}

Android Popup Message

I have created app that detects otg cable,when otg cable is plugged in or out popup message appears that says otg connected or otg disconnected.How to make that popup appears when button on toolbar is clicked,popup message should only appear in action bar when otg cable is not connected,when it's connected it's should be hidden?
public class MainActivity extends AppCompatActivity
{
private Process suProcess;
public static final String IS_CONNECTED_KEY = "isConnectedValue";
public void startOtgService()
{
startService(new Intent(MainActivity.this, OtgService.class));
}
public void stopOtgService()
{
stopService(new Intent(MainActivity.this, OtgService.class));
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button_autootg);
button.setTag(0);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
button.setText("");
final int status = (Integer) view.getTag();
switch (status)
{
case 0:
startOtgService();
button.setText("OTG Service Enabled");
button.setBackgroundColor(Color.GREEN);
view.setTag(1);
break;
case 1:
stopOtgService();
button.setText("OTG Service Disabled");
button.setBackgroundColor(Color.RED);
view.setTag(0);
break;
}
}
});
}
private void getRoot()
{
try
{
suProcess = Runtime.getRuntime().exec("su");
}
catch (IOException e)
{
}
}
#Override
protected void onNewIntent(Intent intent)
{
if (intent.getExtras() == null)
{
super.onNewIntent(intent);
Log.e("###", "No extras");
return;
}
if (intent.hasExtra(IS_CONNECTED_KEY))
{
Log.e("###", "Displaying dialog");
boolean isConnected = intent.getExtras().getBoolean(IS_CONNECTED_KEY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Otg state changed");
if (isConnected)
alertDialog.setMessage("OTG connected");
else
alertDialog.setMessage("OTG disconnected");
alertDialog.show();
}
else
{
Log.e("###", "Does not contain key");
super.onNewIntent(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
if(id == R.id.action_cable)
{
}
return super.onOptionsItemSelected(item);
}
}
public class OtgService extends Service
{
private boolean mOtgConnected = false;
private Handler mHandler;
Timer taskTimer = new Timer();
TimerTask task = new TimerTask()
{
private int last_Length = -1;
#Override
public void run()
{
Context context = OtgService.this.getBaseContext();
File directory = new File("/sys/bus/usb/devices");
File[] contents = directory.listFiles();
int conn_length = contents.length;
if(conn_length ==last_Length)
{
return;
}
else
{
last_Length = conn_length;
}
if(conn_length == 0)
{
mOtgConnected = false;
mHandler.post(flagChangedTask);
}
else if (conn_length > 0) //Might get a -1
{
mOtgConnected = true;
mHandler.post(flagChangedTask);
}
if(conn_length == 0)
{
displayDialog(false);
}
else if (conn_length > 0) //Might get a -1
{
displayDialog(true);
}
}
};
//Will post this to the main thread
Runnable flagChangedTask = new Runnable()
{
#Override
public void run()
{
if (mOtgConnected)
Toast.makeText(OtgService.this,"otg connected",Toast.LENGTH_SHORT).show();
else
Toast.makeText(OtgService.this,"otg not connected",Toast.LENGTH_SHORT).show();
}
};
public OtgService()
{
}
public void displayDialog(boolean isConnected)
{
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(MainActivity.IS_CONNECTED_KEY, isConnected);
startActivity(intent);
}
private void onStartCompat(Intent intent)
{
Log.e("###", "Starting service!");
if (mHandler == null)
mHandler = new Handler(getMainLooper());
taskTimer.scheduleAtFixedRate(task, 0, 1000);
}
// This is the old onStart method that will be called on the pre-2.0
// platform. On 2.0 or later we override onStartCommand() so this
// method will not be called.
#Override
public void onStart(Intent intent, int startId)
{
onStartCompat(intent);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
onStartCompat(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
#Override
public void onDestroy()
{
//task.cancel();
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
}
Add the following code in your code. When cable state changed, call cableStateWasChanged(boolean isConnected). This will show the popup button in your toolbar. When the button is clicked, a popup is shown and the button disappears. You can change the popup title and message depending on the cable state as you want it to be.
private boolean isCableConnected = false;
private boolean cableStateChanged = false;
private boolean popupWasShown = false;
#Override
public boolean onPrepareOptionsMenu(Menu menu){
MenuItem item = menu.findItem(R.id.action_popup);
if (cableStateChanged && !popupWasShown) {
item.setVisible(true);
cableStateChanged = false;
} else if (popupWasShown) {
item.setVisible(false);
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == ...) {
...
} else if (id == R.id.action_popup) {
popupWasShown = true;
invalidateOptionsMenu();
// You can change the popup title, message and buttons here
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(isCableConnected ? "Cable was connected" : "Cable was disconnected");
builder.setMessage("foo bar");
builder.setPositiveButton("OK", null);
builder.setNegativeButton(null, null);
builder.create().show();
}
return super.onOptionsItemSelected(item);
}
private void cableStateWasChanged(boolean isConnected) {
isCableConnected = isConnected;
cableStateChanged = true;
popupShown = false;
invalidateOptionsMenu();
}
Also I suggest you to use Handler instead of TimerTask, see this post

java.lang.classcastexception fragment cannot be cast to android.app.activity

I get error at runtime:
java.lang.classcastexception com.android.homework.AllAppsFragment cannot be cast to android.app.activity. Whats is wrong with this code?
04-26 08:42:02.065: E/AndroidRuntime(1755):
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.android.homework/com.andorid.homework.AllAppsFragment}:
java.lang.ClassCastException: com.andorid.homework.AllAppsFragment
cannot be cast to android.app.Activity
public class AllAppsFragment extends ListFragment {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
private HashMap<ApplicationInfo, Float> appRating = null;
private SharedPreferences sh = null;
private SharedPreferences.Editor preferencesEditor = null;
public static final String MY_PREFERENCES = "myPreferences";
private OnItemSelectedListener listener;
public interface OnItemSelectedListener {
public void onRssItemSelected(String link);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof OnItemSelectedListener) {
listener = (OnItemSelectedListener) activity;
} else {
throw new ClassCastException(activity.toString()
+ " must implemenet MyListFragment.OnItemSelectedListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
packageManager = getActivity().getBaseContext().getPackageManager();
new LoadApplications().execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_main, null);
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
inflater.inflate(R.menu.menu, menu);
super.onCreateOptionsMenu(menu, inflater);
// return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
boolean result = true;
switch (item.getItemId()) {
case R.id.menu_about: {
displayAboutDialog();
break;
}
default: {
result = super.onOptionsItemSelected(item);
break;
}
}
return result;
}
private void displayAboutDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity().getBaseContext());
builder.setTitle(getString(R.string.about_title));
builder.setItems(new CharSequence[] { getString(R.string.sort_lex),
getString(R.string.sortuj_lex_desc),
getString(R.string.sort_ranked),
getString(R.string.sort_ranked_desc) },
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
sh = getActivity().getBaseContext()
.getSharedPreferences(MY_PREFERENCES,
Context.MODE_PRIVATE);
preferencesEditor = sh.edit();
switch (which) {
case 0:
listadaptor.sortLex();
preferencesEditor.putInt("sort_type", 1);
preferencesEditor.commit();
dialog.cancel();
break;
case 1:
listadaptor.sortLexDesc();
preferencesEditor.putInt("sort_type", 2);
preferencesEditor.commit();
dialog.cancel();
break;
case 2:
listadaptor.sortRating();
preferencesEditor.putInt("sort_type", 3);
preferencesEditor.commit();
dialog.cancel();
break;
case 3:
listadaptor.sortRaingDesc();
preferencesEditor.putInt("sort_type", 4);
preferencesEditor.commit();
dialog.cancel();
break;
}
}
});
builder.create().show();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity().getBaseContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getActivity().getBaseContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
private List<ApplicationInfo> checkForLaunchIntent(
List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (null != packageManager
.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager
.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(
getActivity().getBaseContext(), R.layout.snippet_list_row,
applist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
sh = getActivity().getBaseContext().getSharedPreferences(
MY_PREFERENCES, Context.MODE_PRIVATE);
int sortOrder = sh.getInt("sort_type", 0);
switch (sortOrder) {
case 1:
listadaptor.sortLex();
break;
case 2:
listadaptor.sortLexDesc();
break;
case 3:
listadaptor.sortRating();
break;
case 4:
listadaptor.sortRaingDesc();
break;
default:
}
setListAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(getActivity().getBaseContext(),
null, "Ładujemy!!");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
HostActivity
public class HostActivity extends Activity implements OnItemSelectedListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_fragment);
}
#Override
public void onRssItemSelected(String link) {
// TODO Auto-generated method stub
}
}
main_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<fragment
android:id="#+id/country_fragment"
android:name="com.android.homework.AllAppsFragment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
The exception is thrown on starting the app. It attempts to start the main activity but, for some reason, is attempting to start the fragment. It casts it to an Activity but Fragment does not extend Activity. What you have done is added the fragment as an activity in the AndroidManifest.xml. Change this to HostActivity.

Listview not updating (notify datasetchanged)

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.

Getting URL of the media to play from media server with Cling

I'm working on the example upnpBrowser of Cling upnp stack on android and I browse the content of the merdia server and i can display the list of media in every folder and now i want to extract the URL of the video to play it on a player, but I'm blocked how to extract that URL !!!
UDN serverUdn = ((UpnpControlApplication)getApplicationContext()).server_udn;
//Device server = ((UpnpControlApplication)getApplicationContext()).server;
Device server = upnpService.getRegistry().getDevice(serverUdn, true);
listAdapter.clear();
if(server == null)
{
Toast.makeText(this, "pbm", Toast.LENGTH_LONG).show();
}
else
{
if(server.findService(new UDAServiceType("ContentDirectory")) == null)
Toast.makeText(this, "pbm", Toast.LENGTH_LONG).show();
upnpService.getControlPoint().execute(new Browse(server.findService(new UDAServiceType("ContentDirectory")),id, BrowseFlag.DIRECT_CHILDREN)
{
#Override
public void received(ActionInvocation actionInvocation, DIDLContent didl) {
final List<Item> items = didl.getItems();
String st=didl.getItems().get(0).getFirstResource().getValue();
public void browseServer(final String id)
{
if(((UpnpControlApplication)getApplicationContext()).server_udn == null)
{
new AlertDialog.Builder(this)
.setTitle("Bad")
.setMessage("pas de serveur sélectionné, allez à la section LAN et cliquez sur Parcourir pour sélectionner le serveur!")
.setPositiveButton("OK", new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// Some stuff to do when ok got clicked
}
})
.setNegativeButton("Annuler", new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// Some stuff to do when cancel got clicked
}
})
.show();
}
else
{
UDN serverUdn = ((UpnpControlApplication)getApplicationContext()).server_udn;
//Device server = ((UpnpControlApplication)getApplicationContext()).server;
Device server = upnpService.getRegistry().getDevice(serverUdn, true);
listAdapter.clear();
if(server == null)
{
Toast.makeText(this, "désolé", Toast.LENGTH_LONG).show();
}
else
{
if(server.findService(new UDAServiceType("ContentDirectory")) == null)
Toast.makeText(this, "pbm", Toast.LENGTH_LONG).show();
upnpService.getControlPoint().execute(new Browse(server.findService(new UDAServiceType("ContentDirectory")),id, BrowseFlag.DIRECT_CHILDREN)
{
#Override
public void received(ActionInvocation actionInvocation, DIDLContent didl) {
final List<Item> items = didl.getItems();
//String st = items.getImportUri();
//String st=didl.getItems().get(0).getFirstResource().getValue();
//Log.d("URL IS",st);
//Item item = didl.getItems().get(0);
//Item item = didl.getItems().get(0);
//String url = item.getFirstResource().getValue();
//System.out.println(" this is the url of item" +item.getTitle());
// System.out.println(" this is the url of the media");
//System.out.println(url);
/*final DIDLContent b = didl;
String str1 = "bieda";
try
{
str1 = parser.generate(b);
}
catch(Exception e)
{
str1 = "smuta";
}
final String str=str1;
runOnUiThread(new Runnable()
{
public void run()
{
adb.setTitle("XML").setMessage(str).setPositiveButton("OK", new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// Some stuff to do when ok got clicked
}
}).show();
}
});*/
runOnUiThread(new Runnable(){
public void run()
{
listAdapter.insert(new ServerContentContainer(s.peek()), 0);
}
});
final List<Container> containers = didl.getContainers();
for(final Container c: containers)
{
runOnUiThread(new Runnable(){
public void run()
{
int pos = listAdapter.getPosition(new ServerContentContainer(c));
if(pos >= 0)
{
listAdapter.remove(new ServerContentContainer(c));
listAdapter.insert(new ServerContentContainer(c), pos);
System.out.println("eulooooooooo");
}
else
listAdapter.add(new ServerContentContainer(c));
}
});
}
for(final Item i: items)
{
runOnUiThread(new Runnable(){
public void run()
{
int pos = listAdapter.getPosition(new ServerContentItem(i));
if(pos >= 0)
{
listAdapter.remove(new ServerContentItem(i));
listAdapter.insert(new ServerContentItem(i), pos);
}
else
listAdapter.add(new ServerContentItem(i));
}
});
}
}
#Override
public void updateStatus(Status arg0) {
// TODO Auto-generated method stub
}
#Override
public void failure(ActionInvocation arg0, UpnpResponse arg1,
String arg2) {
// TODO Auto-generated method stub
}
});
}
}
}
and this is the class ServerContentItem :
protected class ServerContentItem extends ServerContent
{
private Item i;
public Item getItem()
{
return i;
}
ServerContentItem(Item i)
{
this.i = i;
}
public void select()
{
if(((UpnpControlApplication)getApplicationContext()).renderer_udn != null)
{
Device renderer = upnpService.getRegistry().getDevice(((UpnpControlApplication)getApplicationContext()).renderer_udn, false);
final Service service = renderer.findService(new UDAServiceType("AVTransport"));
upnpService.getControlPoint().execute(new SetAVTransportURI(service, i.getFirstResource().getValue()){
#Override
public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
adb.setTitle("Bad").setMessage("No!")
.setPositiveButton("OK",new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// Some stuff to do when ok got clicked
}
}).show();
}
#Override
public void success(ActionInvocation invocation)
{
upnpService.getControlPoint().execute(new Play(service){
#Override
public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
adb.setTitle("Bad").setMessage("Non réussi!")
.setPositiveButton("OK",new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// Some stuff to do when ok got clicked
}
}).show();
}
});
}
});
}
else
{
adb.setTitle("Bad")
.setMessage("selection ! need a media player ")
.setPositiveButton("OK",new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// Some stuff to do when ok got clicked
Log.e("bla","blablaa");
Intent intent = new Intent().setClass(BrowseServerActivity.this, Newactivity.class);
startActivity(intent);
}
}).show();
}
}
#Override
public String toString()
{
return i.getTitle();
}
#Override
public boolean equals(Object o)
{
if(this == o)
return true;
if(getClass() != o.getClass())
return false;
return i.equals(((ServerContentItem)o).i);
}
}
I hope that's the code is clear. thx
The Cling Ressource class contains a URI field , get it and try .
Res CLING Support 1.0.5 API

Categories

Resources