In this project I am displaying scores from database. When I change the value of scores from the database it changes there but when I check in the app, it doesn't show the change there, and whenever the points gets added through rewarded video ad it doesnt show in the scores.
We need to restart the app to see the video ads point added, and when I change the values from database, it never shows on the app, I think its solution is easy and I am just a beginner.
public class Home_page extends AppCompatActivity implements RewardedVideoAdListener {
TextView score_text;
LinearLayout spin_button, logout_button, redeem_button, watch_video_buuton,share_id,rate_button;
;
private RewardedVideoAd mRewardedVideoAd;
int myIntValue;
DatabaseReference user_id_child;
String user_id;
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
MobileAds.initialize(getApplicationContext(), "ca-app-pub-3940256099942544/5224354917");
databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
FirebaseAuth mAuth = FirebaseAuth.getInstance();
user_id = mAuth.getCurrentUser().getUid();
user_id_child = databaseReference.child(user_id);
getSupportActionBar().setTitle("Earn Money");
// Admob video ads
MobileAds.initialize(getApplicationContext(), "ca-app-pub-3940256099942544/5224354917");
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
spin_button = (LinearLayout) findViewById(R.id.spin_linear_id);
redeem_button = (LinearLayout) findViewById(R.id.linear_redeem_id);
logout_button = (LinearLayout) findViewById(R.id.linear_logout_id);
watch_video_buuton = (LinearLayout) findViewById(R.id.linear_watch_video_id);
share_id = (LinearLayout)findViewById(R.id.linear_share_id);
score_text = (TextView) findViewById(R.id.wallet_text_score_id);
rate_button = (LinearLayout)findViewById(R.id.linear_rate_id);
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
myIntValue = sp.getInt("your_int_key", 0);
rate_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uri = Uri.parse("https://www.instagram.com/dhruv__bhati/");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
watch_video_buuton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
else {
loadRewardedVideoAd();
Toast.makeText(Home_page.this , "video ad not loaded ", Toast.LENGTH_LONG).show();
}
}
});
redeem_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Home_page.this, Redeem.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_right, R.anim.slide_left);
}
});
logout_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
diaglog();
}
});
spin_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Home_page.this, Spinwheel.class);
intent.putExtra("INT",myIntValue);
startActivity(intent);
overridePendingTransition(R.anim.slide_right, R.anim.slide_left);
}
});
share_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
share(view);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);//Menu Resource, Menu
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.logout_id: {
logout();
}
return true;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(Home_page.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
#Override
public void finish() {
super.finish();
finish();
}
#Override
public void onRewardedVideoAdLoaded() {
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(Home_page.this,"Congratulations, you will get 1000 points next time you open the app ", Toast.LENGTH_LONG).show();
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
int n = myIntValue+1000;
editor.putInt("your_int_key", n);
editor.commit();
user_id_child.child("scores").setValue(+n);
watch_video_buuton.setEnabled(false);
final long startTime= Calendar.getInstance().getTime().getTime();
final Timer timer=new Timer();
TimerTask task=new TimerTask() {
#Override
public void run() {
long curentTime=Calendar.getInstance().getTime().getTime();
long elapsedTime=curentTime-startTime;
ToastTime(10*60*1000, elapsedTime);
if(curentTime-startTime>=10*60*1000){ //10 minutes in millisecond
timer.cancel();
watch_video_buuton.setEnabled(true);
}
}
};
timer.schedule(task, 500, 2000);
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
private void loadRewardedVideoAd() {
if(!mRewardedVideoAd.isLoaded()){
mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",
new AdRequest.Builder().build());
}
}
#Override
public void onResume() {
mRewardedVideoAd.resume(this);
super.onResume();
}
#Override
public void onPause() {
mRewardedVideoAd.pause(this);
super.onPause();
}
#Override
public void onDestroy() {
mRewardedVideoAd.destroy(this);
super.onDestroy();
}
#Override
protected void onStart() {
super.onStart();
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
myIntValue = sp.getInt("your_int_key", 0);
String s = String.valueOf(myIntValue);
score_text.setText(s);
loadRewardedVideoAd();
}
public void share(View view){
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Earn Money");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Earn unlimited money by simple tasks"+" "+"https://play.google.com/store/apps/details?id=wheel.top.best.online.money.make.techyunk.com.earningwheel");
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
public void diaglog(){
final Dialog dialog = new Dialog(Home_page.this);
dialog.setContentView(R.layout.custom_logout);
Button no = (Button) dialog.findViewById(R.id.no_id);
Button yes = (Button)dialog.findViewById(R.id.yes_id);
// if button is clicked, close the custom dialog
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
logout();
}
});
dialog.show();
}
private void ToastTime(long totalTime, long elapsedTime) {
final int remainInSec = (int) (totalTime - elapsedTime) / 1000;
if (remainInSec > 0) {
final Activity activity = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, String.valueOf(remainInSec) + " seconds to enable video button", Toast.LENGTH_SHORT).show();
}
});
}
}
}
As I can see you didn't attach any listener to the Firebase, in your case you need to use addChildEventListener : ChildEventListener.
Be careful and only call this listener once in the onCreate method, If you call it more than once it attaches a new listener then you have two listeners and duplicated data.
UPDATE:
This is the user class you get from the firebase :
public class User {
private String email;
private String name;
private String scores;
public User() {
}
public User(String email, String name, String scores) {
this.email = email;
this.name = name;
this.scores = scores;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScores() {
return scores;
}
public void setScores(String scores) {
this.scores = scores;
}
}
Now let's fetch the data :
firebaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// Here you can handle the new added items.
// if you added a new user you will see it here
User user = dataSnapshot.getValue(User.class);
// Now For example let's log the result
Log.d(TAG, "the user score is : " + user.getScore());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// If you change the score this will appear here :
User user = dataSnapshot.getValue(User.class);
// Here is the new score you can use to update the score in the view
String score = user.getScore();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Now go and try this and you will get it.
Related
I am trying to update the location in the background and foreground so first, I have defined two buttons like update and remove button. so when I click update then it will update the location in the background and remove for removing location listener.
but after some time I want to remove those buttons and when I open that activity then it should update location automatically without button click.
so I decided to remove code from the update button (Start location update) and copy-paste into oncreate method. so that it will update whenever activity opened without clicking on the button. now I'm getting null pointer exception pls someone helps me
I am attaching my complete code.
public class UserLocation extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
DatabaseReference publiclocation;
private static final int MY_PERMISSION_REQUEST_CODE = 7171;
private static final int PLAY_SERVICES_RES_REQUEST = 7172;
private LocationRequest mlocationRequest;
String uid;
SharedPreferences settings;
Button requestLocation, removeLocation;
MyBackgroundService mService = null;
boolean mBound = false;
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
MyBackgroundService.LocalBinder binder = (MyBackgroundService.LocalBinder) iBinder;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
mBound = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_location);
publiclocation = FirebaseDatabase.getInstance().getReference(Common.PUBLIC_LOCATION);
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
settings = getSharedPreferences(PREFS_NAME, 0);
String user_uid = settings.getString("uid", "Null");
uid = firebaseUser.getUid();
//Run time permission
Dexter.withActivity(this)
.withPermissions(Arrays.asList(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_BACKGROUND_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
))
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
requestLocation = (Button) findViewById(R.id.request_location_updates_button);
removeLocation = (Button) findViewById(R.id.remove_location_updates_button);
//Update location when i click on button
requestLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mService.requestLocationUpdates();
}
});
//Remove location when i click remove button
removeLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mService.removeLocationUpdates();
}
});
setButtonState(Common.requestingLocationUpdates(UserLocation.this));
bindService(new Intent(UserLocation.this,
MyBackgroundService.class),
mServiceConnection,
Context.BIND_AUTO_CREATE
);
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
}
})
.check();
}
#Override
protected void onStart() {
super.onStart();
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
EventBus.getDefault().register(this);
}
#Override
protected void onStop() {
if (mBound) {
unbindService(mServiceConnection);
mBound = false;
}
PreferenceManager.getDefaultSharedPreferences(this)
.unregisterOnSharedPreferenceChangeListener(this);
EventBus.getDefault().unregister(this);
super.onStop();
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
if (s.equals(Common.KEY_REQUESTING_LOCATION_UPDATES)) {
setButtonState(sharedPreferences.getBoolean(Common.KEY_REQUESTING_LOCATION_UPDATES, false));
}
}
private void setButtonState(boolean isRequestEnable) {
if (isRequestEnable) {
requestLocation.setEnabled(false);
removeLocation.setEnabled(true);
} else {
requestLocation.setEnabled(true);
removeLocation.setEnabled(false);
}
}
#Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onListenLocation(SendLocationToActivity event) {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
settings = getSharedPreferences(PREFS_NAME, 0);
String user_uid = settings.getString("uid", "Null");
uid = firebaseUser.getUid();
if (event != null) {
String data = new StringBuilder()
.append(event.getLocation().getLatitude())
.append("/")
.append(event.getLocation().getLongitude())
.toString();
Toast.makeText(mService, data, Toast.LENGTH_SHORT).show();
// Location location = event.getLastLocation();
Locations location = new Locations();
location.setLat(event.getLocation().getLatitude());
location.setLon(event.getLocation().getLongitude());
if (Common.currentUser != null) {
publiclocation.child(firebaseUser.getUid()).setValue(location);
} else {
publiclocation.child(user_uid).setValue(location);
}
}
}
}
so below is MyLocationService.java
public void requestLocationUpdates() {
Toast.makeText(getApplicationContext(),"Came",Toast.LENGTH_SHORT).show();
Common.setRequestingLocationUpdates(this, true);
startService(new Intent(getApplicationContext(), MyBackgroundService.class));
try {
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
} catch (SecurityException e) {
Log.e("FunDrive", "Lost location permissions.could not request it" + e);
}
}
Common java
public static final String KEY_REQUESTING_LOCATION_UPDATES = "LocationUpdatedEnable";
SharedPreferences settings;
public static final int TIME_DISPLAY_SLOT_TOTAL = 20;
//Current User
public static User currentUser;
public static String PUBLIC_LOCATION="PublicLocation";
public static boolean isTimeSelected = false;
public static void setRequestingLocationUpdates(Context context,boolean value) {
PreferenceManager.
getDefaultSharedPreferences(context)
.edit()
.putBoolean(KEY_REQUESTING_LOCATION_UPDATES,value)
.apply();
}
public static boolean requestingLocationUpdates(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(KEY_REQUESTING_LOCATION_UPDATES,false);
}
public static CharSequence getLocationTitle(com.example.fundrive.MyBackgroundService myBackgroundService) {
return String.format("Location Updated :%1$s", DateFormat.getDateInstance().format(new Date()));
}
below is what I tried in oncreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mService.requestLocationUpdates();
}
beacon manager.addMonitorNotifier(new MonitorNotifier()
in this method, there are two methods and both are not running .... it is a small app of beacon I want to show the alert .... and that alert in my method in if condition ... but it is not running I did debugger but it is not working
import java.util.Collection;
public class WebViewScreen extends AppCompatActivity implements BeaconConsumer {
public static final String TAG="MainActivity";
private Button startbtn,stopbtn;
private BeaconManager beaconManager=null;
private static final String ALTBEACON_LAYOUT="m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25";
private Region beaconRegion=null;
private void ShowAlert(final String title, final String message){
runOnUiThread (new Thread(new Runnable() {
public void run() {
AlertDialog alertDialog = new AlertDialog.Builder(WebViewScreen.this).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}));
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
Log.d(TAG,"on create called");
startbtn=findViewById(R.id.startButton);
stopbtn=findViewById(R.id.stopButton);
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},1234);
beaconManager=BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout(ALTBEACON_LAYOUT));
beaconManager.bind(this);
startbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startBiconMonitoring();
}
});
stopbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopBiconMonitoring();
}
});
}
private boolean entryMessageRaised=false;
private boolean exitMessageRaised=false;
private boolean rangingMessageRaised=false;
private void stopBiconMonitoring() {
Log.d(TAG,"Stop Beacon Monitering");
try {
beaconManager.stopMonitoringBeaconsInRegion(beaconRegion);
beaconManager.stopRangingBeaconsInRegion(beaconRegion);
}catch (RemoteException e){
e.printStackTrace();
}
}
private void startBiconMonitoring() {
Log.d(TAG,"Start Beacon Monitering");
try {
beaconRegion = new Region("My Bicons",Identifier.parse("B9407F30-F5F8-466E-AFF9-25556B57FE6D"),Identifier.parse("4"),Identifier.parse("200"));
beaconManager.startMonitoringBeaconsInRegion(beaconRegion);
beaconManager.startRangingBeaconsInRegion(beaconRegion);
}catch (RemoteException e){
e.printStackTrace();
}
}
private void findID() {
}
#Override
public void onBeaconServiceConnect() {
beaconManager.addMonitorNotifier(new MonitorNotifier() {
#Override
public void didEnterRegion(Region region) {
if (!entryMessageRaised){
showAlert("didEnterRegion","Entering Region"+region.getUniqueId()+"Beacon Detected UUID/Major/Minor:"+region.getId1()+"/"+region.getId2()+"/"+region.getId3());
entryMessageRaised=true;
}
else {
Log.d(TAG,"somrething go wrong");
}
}
#Override
public void didExitRegion(Region region) {
if (!exitMessageRaised){
showAlert("didExitRegion","Exiting Region"+region.getUniqueId()+"Beacon Detected UUID/Major/Minor:"+region.getId1()+"/"+region.getId2()+"/"+region.getId3());
exitMessageRaised=true;
}
}
#Override
public void didDetermineStateForRegion(int i, Region region) {
}
});
beaconManager.addRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> collection, Region region) {
if (rangingMessageRaised && collection != null && !collection.isEmpty()){
for (Beacon beacon:collection){
showAlert("didExitRegion","Ranging Region"+region.getUniqueId()+"Beacon Detected UUID/Major/Minor:"+beacon.getId1()+"/"+beacon.getId2()+"/"+beacon.getId3());
}
rangingMessageRaised=true;
}
}
});
}
}
I want to show the alert if the device will found bacon
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;
}
My code is here
I have test it on my device I also integrate this app on firebase.
but it never go to onRewarded it always call onRewardedFaild why sir?
can anyone help me.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize the Mobile Ads SDK.
MobileAds.initialize(this,APP_ID);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
// Create the "retry" button, which tries to show an interstitial between game plays.
mRetryButton = ((Button) findViewById(R.id.retry_button));
mRetryButton.setVisibility(View.INVISIBLE);
mRetryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startGame();
}
});
// Create the "show" button, which shows a rewarded video if one is loaded.
mShowVideoButton = ((Button) findViewById(R.id.watch_video));
mShowVideoButton.setVisibility(View.INVISIBLE);
mShowVideoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showRewardedVideo();
}
});
// Display current coin count to user.
mCoinCountText = ((TextView) findViewById(R.id.coin_count_text));
mCoinCount = 0;
mCoinCountText.setText("Coins: " + mCoinCount);
startGame();
}
#Override
public void onPause() {
super.onPause();
pauseGame();
mRewardedVideoAd.pause(this);
}
#Override
public void onResume() {
super.onResume();
if (!mGameOver && mGamePaused) {
resumeGame();
}
mRewardedVideoAd.resume(this);
}
private void pauseGame() {
mCountDownTimer.cancel();
mGamePaused = true;
}
private void resumeGame() {
createTimer(mTimeRemaining);
mGamePaused = false;
}
private void loadRewardedVideoAd() {
if (!mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.loadAd(AD_UNIT_ID, new AdRequest.Builder().build());
/* AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("40C4DDA8F53FFA9BA5B61261E0CA28AB") // Test devices don't work work with rewarded video ads.
.build();
mRewardedVideoAd.loadAd(AD_UNIT_ID, adRequest);*/
}
}
private void addCoins(int coins) {
mCoinCount = mCoinCount + coins;
mCoinCountText.setText("Coins: " + mCoinCount);
}
private void startGame() {
// Hide the retry button, load the ad, and start the timer.
mRetryButton.setVisibility(View.INVISIBLE);
mShowVideoButton.setVisibility(View.VISIBLE);
loadRewardedVideoAd();
createTimer(COUNTER_TIME);
mGamePaused = false;
mGameOver = false;
}
// Create the game timer, which counts down to the end of the level
// and shows the "retry" button.
private void createTimer(long time) {
final TextView textView = ((TextView) findViewById(R.id.timer));
if (mCountDownTimer != null) {
mCountDownTimer.cancel();
}
mCountDownTimer = new CountDownTimer(time * 1000, 50) {
#Override
public void onTick(long millisUnitFinished) {
mTimeRemaining = ((millisUnitFinished / 1000) + 1);
textView.setText("seconds remaining: " + mTimeRemaining);
}
#Override
public void onFinish() {
if (mRewardedVideoAd.isLoaded()) {
mShowVideoButton.setVisibility(View.VISIBLE);
}
textView.setText("You Lose!");
addCoins(GAME_OVER_REWARD);
mRetryButton.setVisibility(View.VISIBLE);
mGameOver = true;
}
};
mCountDownTimer.start();
}
private void showRewardedVideo() {
mShowVideoButton.setVisibility(View.INVISIBLE);
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
Toast.makeText(this, "onRewardedVideoAdLeftApplication", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
Toast.makeText(this, "onRewardedVideoAdClosed", Toast.LENGTH_SHORT).show();
// Preload the next video ad.
loadRewardedVideoAd();
}
#Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {
Toast.makeText(this, "onRewardedVideoAdFailedToLoad", 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 onRewarded(RewardItem reward) {
Toast.makeText(this,
String.format(" onRewarded! currency: %s amount: %d", reward.getType(),
reward.getAmount()),
Toast.LENGTH_SHORT).show();
addCoins(reward.getAmount());
}
#Override
public void onRewardedVideoStarted() {
Toast.makeText(this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
}
I am using my Ad_Unit_ID Live not tested Device ID
This is my SplashActivity class.
In my Android app I've used a splash screen. But as splash screen disappears, then next screen becomes black before switching to main activity. So, how can I prevent that black screen?
public class SplashScreen extends Activity {
RegisterGCM registerGCM;
private GpsTracker1 mGps;
boolean canLocate;
public static boolean appVisible = false;
public static String lat;
public static String lon;
public static String addr;
public static String addr1;
public static String city;
public static String state;
public static String pin;
public static String country;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
this.mGps = new GpsTracker1(this);
canLocate = mGps.canGetLocation();
if (!canLocate)
{
this.mGps.showSettingsAlert();
}
else
{
getGpsInfo();
}
}
public void getGpsInfo()
{
registerGCM = new RegisterGCM(getApplicationContext());
String regId = registerGCM.getRegistrationId();
if (TextUtils.isEmpty(regId))
{
registerGCM.registerGCM();
}
lat = this.mGps.getLatitude();
lon = this.mGps.getLongitude();
addr = this.mGps.getAddress();
addr1 = this.mGps.getAddress1();
city = this.mGps.getCity();
state = this.mGps.getState();
pin = this.mGps.getPostalcode();
country = this.mGps.getCountry();
Thread timerThread = new Thread()
{
public void run()
{
try
{
sleep(2000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
finally
{
Intent intent = new Intent(SplashScreen.this, Category_Activity.class);
startActivity(intent);
finish();
}
}
};
timerThread.start();
}
#Override
public void onStart()
{
super.onStart();
}
public void onStop()
{
super.onStop();
}
public void onResume()
{
super.onResume();
appVisible = true;
}
public void onPause()
{
super.onPause();
appVisible = false;
}
}
Why don't you post your runnable instead of blocking a thread?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashScreen.this, Category_Activity.class);
startActivity(intent);
finish();
}
}, 2000);
// Other details
}
It starts your activity in the main thread.