I use this code to play the full-screen video but I have a problem when it is video playing and moving from the main activity to the full-screen activity occurs freezing of the video for 2-3 seconds This problem occurs only with the releases after 2.8.3 only but with 2.8.0 works Video is smooth
code full: https://github.com/MATPOCKIH/ExoPlayerFullscreen
PlayerViewManager
public class PlayerViewManager {
private static final String TAG = "ExoPlayerViewManager";
public static final String EXTRA_VIDEO_URI = "video_uri";
private static Map<String, PlayerViewManager> instances = new HashMap<>();
private Uri videoUri;
public boolean isPlayerPlaying;
private boolean isMustPlaying;
private UniversalPlayerView universalPlayer;
public static PlayerViewManager getInstance(String videoUri) {
PlayerViewManager instance = instances.get(videoUri);
if (instance == null) {
instance = new PlayerViewManager(videoUri);
instances.put(videoUri, instance);
}
return instance;
}
private PlayerViewManager(String videoUri) {
this.videoUri = Uri.parse(videoUri);
}
public void preparePlayer(PlayerHolderView playerHolderView) {
if (playerHolderView == null) {
return;
}
if (universalPlayer == null) {
universalPlayer = createPlayer(playerHolderView.getContext());
isPlayerPlaying = true;
isMustPlaying = true;
}
universalPlayer.initialize(videoUri, playerHolderView);
}
public void releaseVideoPlayer() {
if (universalPlayer != null) {
universalPlayer.release();
}
universalPlayer = null;
}
public void goToBackground() {
if (universalPlayer != null /*&& !isMustPlaying*/) {
//isPlayerPlaying = player.getPlayWhenReady();
universalPlayer.pause();
}
}
public void goToForeground() {
if (universalPlayer != null && isMustPlaying) {
universalPlayer.play();
}
}
public void pausePlayer(){
if (universalPlayer != null) {
universalPlayer.pause();
isPlayerPlaying = false;
isMustPlaying = false;
}
}
public void playPlayer(){
if (universalPlayer != null) {
universalPlayer.play();
isPlayerPlaying = true;
isMustPlaying = true;
}
}
private UniversalPlayerView createPlayer(Context context){
if (videoUri.getScheme().startsWith("http")){
return new FaceterExoPlayerView(context);
}
return new FaceterExoPlayerView(context);
}
}
FaceterExoPlayerView
public class FaceterExoPlayerView extends UniversalPlayerView {
private Uri videoUri;
private DefaultDataSourceFactory dataSourceFactory;
private SimpleExoPlayer player;
private PlayerView exoPlayerView;
private Context context;
public FaceterExoPlayerView(Context context) {
this.context = context;
}
#Override
public void initialize(Uri videoUri, PlayerHolderView playerHolderView) {
if (playerHolderView == null || videoUri == null)
return;
exoPlayerView = playerHolderView.findViewById(R.id.exo_player);
if (player == null) {
player = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector());
dataSourceFactory = new DefaultDataSourceFactory(context,
Util.getUserAgent(context, "faceter"));
MediaSource videoSource = buildMediaSource(videoUri, null);
player.prepare(videoSource);
}
player.clearVideoSurface();
player.setVideoTextureView((TextureView) exoPlayerView.getVideoSurfaceView());
exoPlayerView.setPlayer(player);
exoPlayerView.hideController();
setResizeModeFill(playerHolderView.isResizeModeFill());
}
#Override
public void play() {
player.setPlayWhenReady(true);
}
#Override
public void pause() {
player.setPlayWhenReady(false);
}
#SuppressWarnings("unchecked")
private MediaSource buildMediaSource(Uri uri, #Nullable String overrideExtension) {
int type = Util.inferContentType(uri, overrideExtension);
switch (type) {
/*case C.TYPE_DASH:
return new DashMediaSource.Factory(
new DefaultDashChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false))
.setManifestParser(
new FilteringManifestParser<>(
new DashManifestParser(), (List<RepresentationKey>) getOfflineStreamKeys(uri)))
.createMediaSource(uri);
case C.TYPE_SS:
return new SsMediaSource.Factory(
new DefaultSsChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false))
.setManifestParser(
new FilteringManifestParser<>(
new SsManifestParser(), (List<StreamKey>) getOfflineStreamKeys(uri)))
.createMediaSource(uri);*/
case C.TYPE_HLS:
return new HlsMediaSource.Factory(dataSourceFactory)
/*.setPlaylistParser(
new FilteringManifestParser<>(
new HlsPlaylistParser(), (List<RenditionKey>) getOfflineStreamKeys(uri)))*/
.createMediaSource(uri);
case C.TYPE_OTHER:
return new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
default: {
throw new IllegalStateException("Unsupported type: " + type);
}
}
}
#Override
public void release() {
if (player != null) {
player.release();
}
player = null;
}
#Override
public void setResizeModeFill(boolean isResizeModeFill) {
if (isResizeModeFill) {
exoPlayerView.setResizeMode(RESIZE_MODE_FILL);
} else {
exoPlayerView.setResizeMode(RESIZE_MODE_FIT);
}
}
}
PlayerHolderView.java
public class PlayerHolderView extends FrameLayout {
private String videoUrl;
private boolean isResizeModeFill = true;
private OnUserInteractionListener onUserInteractionListener;
public PlayerHolderView(#NonNull Context context) {
super(context);
init();
}
public PlayerHolderView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public PlayerHolderView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
LayoutInflater.from(getContext()).inflate(R.layout.layout_player, this, true);
View controlView = this.findViewById(R.id.exo_controller);
controlView.findViewById(R.id.exo_play)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(videoUrl).playPlayer();
}
});
controlView.findViewById(R.id.exo_pause)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(videoUrl).pausePlayer();
}
});
controlView.findViewById(R.id.exo_fullscreen_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), FullscreenVideoActivity.class);
intent.putExtra(PlayerViewManager.EXTRA_VIDEO_URI, videoUrl);
getContext().startActivity(intent);
}
});
MainActivity
public class MainActivity extends AppCompatActivity {
private List<PlayerHolderView> playerHolders = new ArrayList<>();
private List<TextView> links = new ArrayList<>();
private List<String> mVideoUrls = new ArrayList<>(
Arrays.asList(
//"http://10.110.3.30/api/Playlists/6a3ecad7-e744-446f-9341-0e0ba834de63?from=2018-09-20&to=2018-09-21"
"https://commondatastorage.googleapis.com/gtv-videos-bucket/CastVideos/hls/TearsOfSteel.m3u8",
"http://redirector.c.youtube.com/videoplayback?id=604ed5ce52eda7ee&itag=22&source=youtube&sparams=ip,ipbits,expire,source,id&ip=0.0.0.0&ipbits=0&expire=19000000000&signature=513F28C7FDCBEC60A66C86C9A393556C99DC47FB.04C88036EEE12565A1ED864A875A58F15D8B5300&key=ik0",
"https://html5demos.com/assets/dizzy.mp4"
//"https://cdn.faceter.io/hls/ab196789-8876-4854-82f3-087e5682d013",
//"https://cdn.faceter.io/hls/65d1c673-6a63-44c8-836b-132449c9462a"
)
);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
playerHolders.add((PlayerHolderView) findViewById(R.id.holder1));
playerHolders.add((PlayerHolderView) findViewById(R.id.holder2));
playerHolders.add((PlayerHolderView) findViewById(R.id.holder3));
links.add((TextView) findViewById(R.id.title1));
links.add((TextView) findViewById(R.id.title2));
links.add((TextView) findViewById(R.id.title3));
}
#Override
public void onResume() {
super.onResume();
int i = 0;
for (final String videoUrl : mVideoUrls) {
playerHolders.get(i).setupPlayerView(videoUrl);
playerHolders.get(i).setOnUserInteractionListener(this);
links.get(i).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onVideoTitleClicked(videoUrl);
}
});
i++;
}
}
#Override
public void onPause() {
super.onPause();
for (String videoUrl : mVideoUrls) {
PlayerViewManager.getInstance(videoUrl).goToBackground();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
for (String videoUrl : mVideoUrls) {
PlayerViewManager.getInstance(videoUrl).releaseVideoPlayer();
}
}
public void onVideoTitleClicked(String videoUrl) {
Intent intent = new Intent(getBaseContext(), DetailActivity.class);
intent.putExtra(PlayerViewManager.EXTRA_VIDEO_URI, videoUrl);
startActivity(intent);
}
}
FullscreenVideoActivity
public class FullscreenVideoActivity extends AppCompatActivity {
/**
* Some older devices needs a small delay between UI widget updates
* and a change of the status and navigation bar.
*/
private static final int UI_ANIMATION_DELAY = 300;
private final Handler mHideHandler = new Handler();
private View mContentView;
private final Runnable mHidePart2Runnable = new Runnable() {
#SuppressLint("InlinedApi")
#Override
public void run() {
// Delayed removal of status and navigation bar
// Note that some of these constants are new as of
// API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
private final Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
hide();
}
};
private String mVideoUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_video);
mContentView = findViewById(R.id.enclosing_layout);
PlayerHolderView playerHolderView = findViewById(R.id.player_holder);
playerHolderView.setResizeModeFill(false);
mVideoUri = getIntent().getStringExtra(PlayerViewManager.EXTRA_VIDEO_URI);
PlayerViewManager.getInstance(mVideoUri).preparePlayer(playerHolderView);
/*
// Set the fullscreen button to "close fullscreen" icon
View controlView = playerView.findViewById(R.id.exo_controller);
ImageView fullscreenIcon = controlView.findViewById(R.id.exo_fullscreen_icon);
fullscreenIcon.setImageResource(R.drawable.exo_controls_fullscreen_exit);
controlView.findViewById(R.id.exo_fullscreen_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
controlView.findViewById(R.id.exo_play)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(mVideoUri).playPlayer();
}
});
controlView.findViewById(R.id.exo_pause)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(mVideoUri).pausePlayer();
}
});*/
}
#Override
public void onResume() {
super.onResume();
PlayerViewManager.getInstance(mVideoUri).goToForeground();
}
#Override
public void onPause() {
super.onPause();
PlayerViewManager.getInstance(mVideoUri).goToBackground();
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide();
}
private void hide() {
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}
/**
* Schedules a call to hide() in delay milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide() {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, 100);
}
}
Just try out this code for video freeze problem:
#Override
public void play() {
player.setPlayWhenReady(true);
player.getPlaybackState();
}
#Override
public void pause() {
player.setPlayWhenReady(false);
player.getPlaybackState();
}
Here player.getPlaybackState(); is help full to get it to back state.
Related
The problem is that I am trying to pass the name of the user when the adReward is complete to another activity. But I'm stuck in this activity, even though the video ad is loaded. (and it works well while there are no video ad to show). Here is my code:
My java.class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
Vibrator vibrator;
private RewardedVideoAd HDay1;
int currentActivity = 0;
boolean flag;
private EditText vname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_day1);
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
MobileAds.initialize(this,
"ca-app-pub-3940256099942544/6300978111");
///ADD BAN
AdView mAdView = findViewById(R.id.banner1);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
///////////////////////////////////
//VIDEO
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
loadRewardedVideoDAY1();
vname = findViewById(R.id.name);
final ImageView nm = findViewById(R.id.ID);
nm.setVisibility(View.INVISIBLE);
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
nm.setColorFilter(filter);
final Button closeAd = findViewById(R.id.closeDay1);
closeAd.setVisibility(View.INVISIBLE);
///////////////////////////////////////////////////////////////////////////////////////////
closeAd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vibrator.vibrate(50);
loadRewardedVideoDAY1();
if (HDay1.isLoaded()) {
HDay1.show();
setCurrent(1);
}
String name = vname.getText().toString();
getusername(name);
}
});
}
////////////////////////////////////////////////////////////////
private void Day1() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
private void getusername(String name) {
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void loadRewardedVideoDAY1() {
if (!HDay1.isLoaded()) {
HDay1 = null;
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
///////////////TEST ID//////////////////
HDay1.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
}
#Override
public void onRewardedVideoAdLoaded() {
Log.d("LOADED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdOpened() {
Log.d("OPENED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoStarted() {
Log.d("STARTED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoDAY1();
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewarded(RewardItem rewardItem) {
loadRewardedVideoDAY1();
flag = true;
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}
#Override
protected void onPause() {
HDay1.pause(this);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public void setCurrent(int val){
currentActivity = val;
}
Any idea what the problem could be? Thanks in advance
Try below code. Update ProcessData with your intent logic and update oncreate with other data required in your class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
private RewardedVideoAd mRewardedVideoAd;
private Boolean bRewardVideo = false;
#Override
public void onResume() {
super.onResume();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.resume(this);
}
}
#Override
public void onPause() {
super.onPause();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.pause(this);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.destroy(this);
}
}
#Override
public void onRewardedVideoCompleted() {
//Toast.makeText(this, "onRewardedVideoCompleted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdLoaded() {
//Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
//Toast.makeText(this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoStarted() {
//Toast.makeText(this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
//Toast.makeText(this, "Reward Video Closed", Toast.LENGTH_SHORT).show();
// Load the next rewarded video ad.
if (bRewardVideo) {
ProcessData();
} else {
Toast.makeText(this, "Please View Reward Video to get Reward Points", Toast.LENGTH_LONG).show();
}
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(this, "Now you can close Ad to Process", Toast.LENGTH_LONG).show();
bRewardVideo = true;
}
#Override
public void onRewardedVideoAdLeftApplication() {
//Toast.makeText(this, "onRewardedVideoAdLeftApplication",Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Toast.makeText(this, "Fail to Load Reward Video. Please try again!", Toast.LENGTH_SHORT).show();
}
private void loadRewardedVideoAd() {
bRewardVideo = false;
mRewardedVideoAd.loadAd(BuildConfig.REWARDVIDEOID,
new AdRequest.Builder().build());
}
private void ProcessData() {
Snackbar.make(findViewById(R.id.drawer_layout_law), "Please wait while we process the request... ", Snackbar.LENGTH_INDEFINITE).show();
//WRITE YOUR INTENT CODE HERE
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void ShowRewardVideoDialog() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
} else {
loadRewardedVideoAd();
Toast.makeText(mctx, "Fail to Load Reward Video : Please try again", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
}
I'm setting a new app and want to disable hardware key like home,back and recent key in my app. I found some code in stackoverflow but none of them work.
Is it possible to disable hardware key?
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
}
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();
}
}
do nothing in onBackPressed()
#Override
public void onBackPressed() {
}
add this in manifest
<uses-permission android:name="android.permission.REORDER_TASKS" />
and add this in onPause()
#Override
protected void onPause() {
super.onPause();
ActivityManager activityManager = (ActivityManager) getApplicationContext()
.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.moveTaskToFront(getTaskId(), 0);
}
In your MainActivity -
#Override
public void onBackPressed() {
// super.onBackPressed(); commented this line in order to disable back press
//Write your code here
Toast.makeText(getApplicationContext(), "Back press disabled!", Toast.LENGTH_SHORT).show();
}
You can not block Recent and Home but you can restart activity if user click on Home.
Here is example
HomeWatcher Class
public class HomeWatcher {
static final String TAG = "hg";
private Context mContext;
private IntentFilter mFilter;
private OnHomePressedListener mListener;
private InnerRecevier mRecevier;
public HomeWatcher(Context context) {
mContext = context;
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}
public void setOnHomePressedListener(OnHomePressedListener listener) {
mListener = listener;
mRecevier = new InnerRecevier();
}
public void startWatch() {
if (mRecevier != null) {
mContext.registerReceiver(mRecevier, mFilter);
}
}
public void stopWatch() {
if (mRecevier != null) {
mContext.unregisterReceiver(mRecevier);
}
}
class InnerRecevier extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
final String SYSTEM_DIALOG_REASON_LONG_PRESS = "assist";
final String SYSTEM_DIALOG_REASON_VOICE_INTERACTION = "voiceinteraction";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null) {
Log.e(TAG, "action:" + action + ",reason:" + reason);
if (mListener != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
mListener.onHomePressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
mListener.onHomeLongPressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_LONG_PRESS)) {
mListener.onHomeLongPressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_VOICE_INTERACTION)) {
mListener.onHomeLongPressed();
}
}
}
}
}
}
OnHomePressedListener interface
public interface OnHomePressedListener {
void onHomePressed();
void onHomeLongPressed();
}
In Your Main Activity
HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
#Override
public void onHomePressed() {
Log.d("Pressed", "Home Button Pressed");
}
#Override
public void onHomeLongPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Log.d("LongPressed", "Home Long Button Pressed");
}
});
mHomeWatcher.startWatch();
I'm loading json file from online and saving it on Sqlite such that when app is offline...Then still user will be able to see the data.
It works fine in MainActivity.
But when I try to covert it into fragment, I'm getting errors of Fragment cannot be cast in to FlowerAdapter$FlowerClickListener
Here is the error file
My Fragment name is nepali.
Here is the Mainactivity
public class MainActivity extends AppCompatActivity implements FlowerAdapter.FlowerClickListener, FlowerFetchListener {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView mRecyclerView;
private RestManager mManager;
private FlowerAdapter mFlowerAdapter;
private FlowerDatabase mDatabase;
private Button mReload;
private ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
configViews();
mManager = new RestManager();
mDatabase = new FlowerDatabase(this);
loadFlowerFeed();
mReload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadFlowerFeed();
}
});
}
private void loadFlowerFeed() {
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Loading Flower Data...");
mDialog.setCancelable(true);
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setIndeterminate(true);
mFlowerAdapter.reset();
mDialog.show();
if (getNetworkAvailability()) {
getFeed();
} else {
getFeedFromDatabase();
}
}
private void getFeedFromDatabase() {
mDatabase.fetchFlowers(this);
}
private void configViews() {
mReload = (Button) findViewById(R.id.reload);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
mFlowerAdapter = new FlowerAdapter(this);
mRecyclerView.setAdapter(mFlowerAdapter);
}
#Override
public void onClick(int position) {
}
public void getFeed() {
Call<List<Flower>> listCall = mManager.getFlowerService().getAllFlowers();
listCall.enqueue(new Callback<List<Flower>>() {
#Override
public void onResponse(Call<List<Flower>> call, Response<List<Flower>> response) {
if (response.isSuccessful()) {
List<Flower> flowerList = response.body();
for (int i = 0; i < flowerList.size(); i++) {
Flower flower = flowerList.get(i);
SaveIntoDatabase task = new SaveIntoDatabase();
task.execute(flower);
mFlowerAdapter.addFlower(flower);
}
} else {
int sc = response.code();
switch (sc) {
case 400:
Log.e("Error 400", "Bad Request");
break;
case 404:
Log.e("Error 404", "Not Found");
break;
default:
Log.e("Error", "Generic Error");
}
}
mDialog.dismiss();
}
#Override
public void onFailure(Call<List<Flower>> call, Throwable t) {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public boolean getNetworkAvailability() {
return Utils.isNetworkAvailable(getApplicationContext());
}
#Override
public void onDeliverAllFlowers(List<Flower> flowers) {
}
#Override
public void onDeliverFlower(Flower flower) {
mFlowerAdapter.addFlower(flower);
}
#Override
public void onHideDialog() {
mDialog.dismiss();
}
public class SaveIntoDatabase extends AsyncTask<Flower, Void, Void> {
private final String TAG = SaveIntoDatabase.class.getSimpleName();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Flower... params) {
Flower flower = params[0];
try {
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
return null;
}
}
}
and FlowerDatabase class is
public class FlowerDatabase extends SQLiteOpenHelper {
private static final String TAG = FlowerDatabase.class.getSimpleName();
public FlowerDatabase(Context context) {
super(context, Constants.DATABASE.DB_NAME, null, Constants.DATABASE.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(Constants.DATABASE.CREATE_TABLE_QUERY);
} catch (SQLException ex) {
Log.d(TAG, ex.getMessage());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(Constants.DATABASE.DROP_QUERY);
this.onCreate(db);
}
public void addFlower(Flower flower) {
Log.d(TAG, "Values Got " + flower.getName());
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Constants.DATABASE.PRODUCT_ID, flower.getProductId());
values.put(Constants.DATABASE.CATEGORY, flower.getCategory());
values.put(Constants.DATABASE.PRICE, Double.toString(flower.getPrice()));
values.put(Constants.DATABASE.INSTRUCTIONS, flower.getInstructions());
values.put(Constants.DATABASE.NAME, flower.getName());
try {
db.insert(Constants.DATABASE.TABLE_NAME, null, values);
} catch (Exception e) {
}
db.close();
}
public void fetchFlowers(FlowerFetchListener listener) {
FlowerFetcher fetcher = new FlowerFetcher(listener, this.getWritableDatabase());
fetcher.start();
}
public class FlowerFetcher extends Thread {
private final FlowerFetchListener mListener;
private final SQLiteDatabase mDb;
public FlowerFetcher(FlowerFetchListener listener, SQLiteDatabase db) {
mListener = listener;
mDb = db;
}
#Override
public void run() {
Cursor cursor = mDb.rawQuery(Constants.DATABASE.GET_FLOWERS_QUERY, null);
final List<Flower> flowerList = new ArrayList<>();
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
Flower flower = new Flower();
flower.setFromDatabase(true);
flower.setName(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.NAME)));
flower.setPrice(Double.parseDouble(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.PRICE))));
flower.setInstructions(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.INSTRUCTIONS)));
flower.setCategory(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.CATEGORY)));
flower.setProductId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.PRODUCT_ID))));
flowerList.add(flower);
publishFlower(flower);
} while (cursor.moveToNext());
}
}
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
mListener.onDeliverAllFlowers(flowerList);
mListener.onHideDialog();
}
});
}
public void publishFlower(final Flower flower) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
mListener.onDeliverFlower(flower);
}
});
}
}
}
and FlowerAdapter Class is
public class FlowerAdapter extends RecyclerView.Adapter<FlowerAdapter.Holder> {
private static final String TAG = FlowerAdapter.class.getSimpleName();
private final FlowerClickListener mListener;
private List<Flower> mFlowers;
public FlowerAdapter(FlowerClickListener listener) {
mFlowers = new ArrayList<>();
mListener = listener;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item, null, false);
return new Holder(row);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
Flower currFlower = mFlowers.get(position);
holder.mName.setText(currFlower.getName());
holder.minstruction.setText(currFlower.getInstructions());
}
#Override
public int getItemCount() {
return mFlowers.size();
}
public void addFlower(Flower flower) {
mFlowers.add(flower);
notifyDataSetChanged();
}
/**
* #param position
* #return
*/
public Flower getSelectedFlower(int position) {
return mFlowers.get(position);
}
public void reset() {
mFlowers.clear();
notifyDataSetChanged();
}
public class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView mName, minstruction;
public Holder(View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.flowerName);
minstruction = (TextView) itemView.findViewById(R.id.flowerPrice);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
mListener.onClick(getLayoutPosition());
}
}
public interface FlowerClickListener {
void onClick(int position);
}
}
My fragment class is that I try to convert above Mainactivity code into Frament class is
public class nepali extends Fragment {
private static final String TAG = nepali.class.getSimpleName();
private RecyclerView mRecyclerView;
private RestManager mManager;
private FlowerAdapter mFlowerAdapter;
private FlowerDatabase mDatabase;
private Button mReload;
private ProgressDialog mDialog;
View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_data, container, false);
configViews();
mManager = new RestManager();
mDatabase = new FlowerDatabase(getActivity());
loadFlowerFeed();
mReload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadFlowerFeed();
}
});
return view;
}
private void loadFlowerFeed() {
mDialog = new ProgressDialog(getActivity());
mDialog.setMessage("Loading Flower Data...");
mDialog.setCancelable(true);
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setIndeterminate(true);
mFlowerAdapter.reset();
mDialog.show();
if (getNetworkAvailability()) {
getFeed();
} else {
getFeedFromDatabase();
}
}
private void getFeedFromDatabase() {
mDatabase.fetchFlowers(this);
}
private void configViews() {
mReload = (Button) view.findViewById(R.id.reload);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
mFlowerAdapter = new FlowerAdapter((FlowerAdapter.FlowerClickListener) this);;
mRecyclerView.setAdapter(mFlowerAdapter);
}
public void getFeed() {
Call<List<Flower>> listCall = mManager.getFlowerService().getAllFlowers();
listCall.enqueue(new Callback<List<Flower>>() {
#Override
public void onResponse(Call<List<Flower>> call, Response<List<Flower>> response) {
if (response.isSuccessful()) {
List<Flower> flowerList = response.body();
for (int i = 0; i < flowerList.size(); i++) {
Flower flower = flowerList.get(i);
SaveIntoDatabase task = new SaveIntoDatabase();
task.execute(flower);
mFlowerAdapter.addFlower(flower);
}
} else {
int sc = response.code();
switch (sc) {
case 400:
Log.e("Error 400", "Bad Request");
break;
case 404:
Log.e("Error 404", "Not Found");
break;
default:
Log.e("Error", "Generic Error");
}
}
mDialog.dismiss();
}
#Override
public void onFailure(Call<List<Flower>> call, Throwable t) {
mDialog.dismiss();
Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public boolean getNetworkAvailability() {
return Utils.isNetworkAvailable(getActivity());
}
public void onDeliverFlower(Flower flower) {
mFlowerAdapter.addFlower(flower);
}
public void onHideDialog() {
mDialog.dismiss();
}
public class SaveIntoDatabase extends AsyncTask<Flower, Void, Void> {
private final String TAG = SaveIntoDatabase.class.getSimpleName();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Flower... params) {
Flower flower = params[0];
try {
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
return null;
}
}
}
Lastly the FlowerService class is
public interface FlowerService {
#GET("/routine/first.json")
Call<List<Flower>> getAllFlowers();
}
and FlowerFetchListener Class is
public interface FlowerFetchListener {
void onDeliverAllFlowers(List<Flower> flowers);
void onDeliverFlower(Flower flower);
void onHideDialog();
}
Please Help....and Thanks in advance.
You should not call db and network from activity or fragment. Try to learn MVVM architecture and use ViewModel to store the data from db or network. You may put a lot of effort making your app work but it will still lead to crashes (especially after you introduce fragment and call db and API from there). You will need to handle your data state during configuration changes. Listen to this talk and start writing clean code https://m.youtube.com/watch?v=5qlIPTDE274
The error you get is because you pass wrong parameter into adapter constructor ‘new FlowerAdapter((FlowerAdapter.FlowerClickListener) this)’. If you want to pass a listener to the adapter you need to pass the class which implements the listener: either activity - then pass getActivity(), or fragment ‘this’ - then make fragment implement implements FlowerAdapter.FlowerClickListener.Be aware that it can be null when fragment is not attached to activity, eg configuration change.
I'm trying play an audio file with the mediacontroler in my android application. When playing audio the seekbar does not move.I looked mediacontroler function. But I could not find a function for updating seekbar.
please advice.
public class Show_subject_Activity extends Activity
implements MediaController.MediaPlayerControl, MediaPlayer.OnBufferingUpdateListener {
private RatingBar box_litner;
private MediaController mController;
private MediaPlayer mPlayer;
private Cursor cur;
int bufferPercent = 0;
DB_Nabege_helper db_nabege = new DB_Nabege_helper(this);
private String voicefileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_subject);
box_litner = (RatingBar) findViewById(R.id.ratingBar1);
mController = (MediaController) findViewById(R.id.mediaController_voice);
mController.setAnchorView(null);
db_nabege.open();
cur = db_nabege.getSubject(Intent_values.id_subject);
voicefileName = getVoiceFileName();
db_nabege.close();
}
#Override
public void onResume() {
super.onResume();
mPlayer = new MediaPlayer();
// Set the audio data source
try {
mPlayer.setDataSource(this, getUriVoice());
mPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
}
// Set an image for the album cover
// coverImage.setImageResource(R.drawable.icon);
mController.setMediaPlayer(this);
mController.setEnabled(true);
}
private Uri getUriVoice() {
File voiceFile = null;
try {
voiceFile = new File(Environment.getExternalStorageDirectory().getPath() + "/nabege" + File.separator
+ "audio" + File.separator + voicefileName);
} catch (Exception e) {
Log.d("log", e.toString());
}
Uri voiceUri = Uri.fromFile(voiceFile);
return voiceUri;
}
#Override
public void onPause() {
super.onPause();
mPlayer.release();
mPlayer = null;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mController.show();
return super.onTouchEvent(event);
}
// MediaPlayerControl Methods
#Override
public int getBufferPercentage() {
return bufferPercent;
}
#Override
public int getCurrentPosition() {
return mPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mPlayer.isPlaying();
}
#Override
public void pause() {
mPlayer.pause();
}
#Override
public void seekTo(int pos) {
mPlayer.seekTo(pos);
}
#Override
public void start() {
mPlayer.start();
}
// BufferUpdateListener Methods
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
bufferPercent = percent;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
}
You can update the seekbar yourself, e.g.:
final Handler mHandler = new Handler();
final Runnable mUpdateSeekbar = new Runnable() {
public void run() {
mSeekBar.setProgress(mMediaPlayer.getCurrentPosition());
mSeekBar.setMax(mMediaPlayer.getDuration());
mHandler.postDelayed(this, 1000);
}
};
Post the runnable in onResume and mHandler.removeCallbacks(mUpdateSeekbar) in onPause.
I have a listview with 400 items, however, when I'm on item 100 etc, I press down it would go down and all that neat stuff, but the viewing goes back to the top while keeping my item 100 selected... Here is what it's doing: http://im.ezgif.com/tmp/ezgif-2788305924.gif
How do I prevent his? Here is what I have:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
try{
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
} catch (Exception e){
Log.e("Menu", "Full screen not supported under API 19 (4.4 KitKat)");
}
mainLinearLayout = (LinearLayout) findViewById(R.id.mainLinearLayout);
listView = (ListView) findViewById(R.id.listView);
listView.setItemsCanFocus(false);
listView.setDivider(null);
listView.setFocusable(false);
listView.setDividerHeight(0);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Channel channel = channels.get(position);
if (position == menuAdapter.getSelectedPosition()) {
if ((new Random(System.currentTimeMillis())).nextBoolean()) {
openChannel(channel);
} else {
tempChannel = channel;
Log.i("Menu", "Playing ad");
if (interstitialAd.isLoaded())
interstitialAd.show();
}
} else {
menuAdapter.setSelectedPosition(position, listView);
}
Picasso.with(mainActivity).load(channel.artUrl).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
BitmapDrawable bmDrawable = new BitmapDrawable(getResources(), bitmap);
if (bmDrawable != null)
bmDrawable.setAlpha(80);
mainLinearLayout.setBackground(bmDrawable);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
});
mainActivity = this;
bannerAd = new AdView(this);
bannerAd.setAdSize(AdSize.BANNER);
bannerAd.setAdUnitId(getAdmobBannerId());
AdRequest adRequest = new AdRequest.Builder().build();
bannerAd.loadAd(adRequest);
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(getAdmobIntersitialId());
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
openChannel(tempChannel);
}
});
interstitialAd.loadAd((new AdRequest.Builder()).build());
mainLinearLayout.addView(bannerAd, 0);
new WebServiceJob().execute();
}
public String getAdmobBannerId() {
SharedPreferences preferences = getSharedPreferences("YTApp", MODE_PRIVATE);
String result = preferences.getString("admob_banner", null);
if (result == null) {
String defaultID = "ca-app-pub-";
preferences.edit().putString("admob_banner", defaultID).apply();
return defaultID;
}
return result;
}
public String getAdmobIntersitialId() {
SharedPreferences preferences = getSharedPreferences("YTApp", MODE_PRIVATE);
String result = preferences.getString("admob_intersitial", null);
if (result == null) {
String defaultID = "ca-app-pub4";
preferences.edit().putString("admob_intersitial", defaultID).apply();
return defaultID;
}
return result;
}
public void artDownloaded(){
numArtDownloaded++;
if(numArtDownloaded == channels.size())
updateUIWithScroll();
}
public void updateUIWithScroll(){
updateUI();
if(!menuAdapter.isScrolling) {
menuAdapter.isScrolling = true;
listView.post(new Runnable() {
#Override
public void run() {
Log.i("Menu", "Scrolling");
listView.smoothScrollToPosition(menuAdapter.getSelectedPosition());
menuAdapter.isScrolling = false;
}
});
}
}
public void updateUI() {
try {
ArrayList<String> channelNames = new ArrayList<>();
for (Channel channel : channels)
channelNames.add(channel.title);
menuAdapter = new MenuAdapter(this, R.layout.listitemright, channelNames, getSharedPreferences("YTApp", MODE_PRIVATE).getInt("selectedChannelNr", -1));
listView.setAdapter(menuAdapter);
if (menuAdapter.getSelectedPosition() != -1) {
Picasso.with(mainActivity).load(channels.get(menuAdapter.getSelectedPosition()).artUrl).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
BitmapDrawable bmDrawable = new BitmapDrawable(getResources(), bitmap);
if (bmDrawable != null)
bmDrawable.setAlpha(80);
mainLinearLayout.setBackground(bmDrawable);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
} catch (Exception e){}
}