Unity Ads 3.0.0 show banner ads in Android - android

I want to show Unity banner ads (Unity ads 3.0.0) for my Java Android app.
I have read https://unityads.unity3d.com/help/android/integration-guide-android
According to the guide lines the following code has to be added to get banner ads.
public class UnityBannerExample extends Activity {
private View bannerView;
private Button bannerButton;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.unityads_example_layout);
final Activity myActivity = this;
final IUnityBannerListener unityBannerListener = new UnityBannerListener ();
final IUnityMonetizationListener unityMonetizationListener = new UnityMonetizationListener ();
UnityBanners.setBannerListener (unityBannerListener);
bannerButton = (Button) findViewById (R.id.unityads_example_banner_button);
bannerButton.setEnabled (true);
bannerButton.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick (View v) {
if (bannerView == null) {
UnityBanners.loadBanner (myActivity, "banner");
} else {
UnityBanners.destroy ();
}
}
});
final Button initializeButton = (Button) findViewById (R.id.unityads_example_initialize_button);
initializeButton.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick (View v) {
UnityMonetization.initialize (myActivity, "1234567", unityMonetizationListener, true);
}
});
}
private class UnityBannerListener implements IUnityBannerListener {
#Override
public void onUnityBannerLoaded (String placementId, View view) {
bannerView = view;
((ViewGroup) findViewById (R.id.unityads_example_layout_root)).addView (view);
}
#Override
public void onUnityBannerUnloaded (String placementId) {
bannerView = null;
}
#Override
public void onUnityBannerShow (String placementId) {
}
#Override
public void onUnityBannerClick (String placementId) {
}
#Override
public void onUnityBannerHide (String placementId) {
}
#Override
public void onUnityBannerError (String message) {
}
}
private class UnityMonetizationListener implements IUnityMonetizationListener {
#Override
public void onPlacementContentReady (String placementId, PlacementContent placementContent) {
}
#Override
public void onPlacementContentStateChange (String placementId, PlacementContent placementContent, UnityMonetization.PlacementContentState previousState, UnityMonetization.PlacementContentState newState) {
}
#Override
public void onUnityServicesError (UnityServices.UnityServicesError error, String message) {
}
}
}
There are two buttons bannerButton and initializeButton.
But I don't want to show buttons to the user to initialize and show the banner ad. I want to show the ads in the on start method of the activity.
What is the proper way to show the banner ads without bannerButton and initializeButton.

You can just use OnResume method of your activity:
#Override
protected void onResume() {
....
....
UnityMonetization.initialize (myActivity, "1234567", unityMonetizationListener, true);
if (bannerView != null) {
UnityBanners.destroy ();
}
UnityBanners.loadBanner (myActivity, "banner");
}
But it is not the end. You should also take care about Banner visibility and refresh.

#Override
public void onPlacementContentReady (String placementId, PlacementContent placementContent) {
UnityBanners.loadBanner (myActivity, "banner");
}

Related

libgdx how to implement admob rewarded video since RewardedVideoAdListener became deprecated

Can someone tell how to implement admob rewarded video in libgdx since RewardedVideoAdListener became depricated, please?
AndroidLauncher:
public class AndroidLauncher extends AndroidApplication implements AdsController {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
game = new MyGame(this);
View gameView = initializeForView(game, config);
layout = new RelativeLayout(this);
layout.addView(gameView, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
rewardedAd = new RewardedAd(this, "ca-app-pub-3940256099942544/5224354917");
RewardedAdLoadCallback adLoadCallback = new RewardedAdLoadCallback() {
#Override
public void onRewardedAdLoaded() {
// Ad successfully loaded.
}
#Override
public void onRewardedAdFailedToLoad(LoadAdError adError) {
// Ad failed to load.
}
};
rewardedAd.loadAd(new AdRequest.Builder().build(), adLoadCallback);
}
and show() method as admob docs:
#Override
public void showRewardedVideo() {
if (rewardedAd.isLoaded()) {
Activity activityContext = MainActivity.this
RewardedAdCallback adCallback = new RewardedAdCallback() {
#Override
public void onRewardedAdOpened() {
// Ad opened.
}
#Override
public void onRewardedAdClosed() {
// Ad closed.
}
#Override
public void onUserEarnedReward(#NonNull RewardItem reward) {
// User earned reward.
}
#Override
public void onRewardedAdFailedToShow(AdError adError) {
// Ad failed to display.
}
};
rewardedAd.show(activityContext, adCallback);
}
}
How to get that Activity to pass it in ad.show() method or what the other ways to show ad?
Problem solved
#Override
public void showRewardedVideo() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (rewardedAd.isLoaded()) {
Activity activityContext = getParent();
RewardedAdCallback adCallback = new RewardedAdCallback() {
#Override
public void onRewardedAdOpened() {
// Ad opened.
}
#Override
public void onRewardedAdClosed() {
// Ad closed.
}
#Override
public void onUserEarnedReward(#NonNull RewardItem reward) {
// User earned reward.
}
#Override
public void onRewardedAdFailedToShow(AdError adError) {
// Ad failed to display.
}
};
rewardedAd.show(activityContext, adCallback);
} else {
loadRewardedVideoAd();
}
}
});
}

android viewpager2 page buton controller

if the page is loaded, the button is active, if not, how can I do passive control?
What I want to do is, if the Viewpager Page is loaded, the button is active, if not, the Button is Passive. But I couldn't do any kind.
Is there anyone who can help?
If viewpager2 is installed Button enabled, if viewpager2 is not installed button false;
List<Movie> movieList = new ArrayList<>();
private ImageButton btn_down, btn_fav;
private Button btn_setter;
private DatabaseReference movies;
private IFirebaseLoadDone iFirebaseLoadDone;
public CartoonFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cartoon, container, false);
movies = FirebaseDatabase.getInstance().getReference("Sports");
movies.keepSynced(true);
iFirebaseLoadDone = this;
loadMovie();
viewPager2 = view.findViewById(R.id.viewPager2_);
btn_down = view.findViewById(R.id.btn_down);
btn_setter = view.findViewById(R.id.btn_setter);
btn_fav = view.findViewById(R.id.btn_fav);
btn_down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveToGallery();
}
});
btn_setter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
btn_fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
private void loadMovie() {
movies.addValueEventListener(this);
}
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
}
#Override
public void onFirebasLoadFailed(String message) {
}
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot moviesSnapShot : dataSnapshot.getChildren())
movieList.add(moviesSnapShot.getValue(Movie.class));
Collections.reverse(movieList);
iFirebaseLoadDone.onFirebaseLoadSuccess(movieList);
viewPagerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadDone.onFirebasLoadFailed(databaseError.getMessage());
}
#Override
public void onDestroy() {
movies.removeEventListener(this);
super.onDestroy();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStop() {
movies.removeEventListener(this);
super.onStop();
}
}
Replace your methods with mine.
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
Firebase methods
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
if(movieList!=null && !movieList.isEmpty()){
btn_down.setEnabled(true);
btn_fav.setEnabled(true);
btn_setter.setEnabled(true);
}
}
#Override
public void onFirebasLoadFailed(String message) {
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
There was an error loading
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setEnabled(boolean)' on a null object reference
at com.example.duvarlar.Fragment.CartoonFragment.loadMovie(CartoonFragment.java:386)
at com.example.duvarlar.Fragment.CartoonFragment.onCreateView(CartoonFragment.java:90)

how to write a variable from a singleton in firebase

There is a program where I can change a variable using a singleton. Created 2 activites, where users can change this variable. How to write the variable that is being changed to the Firebase database. I tried to use the addValueEventListener (new ValueEventListener () method.
Where do I use the firebase methods? In the main class or in singleton? And how to write a variable?
main activity
public class MainActivity extends AppCompatActivity {
private BubbleWrap bubbleWrap;
private TextView txtintent;
final int REQUEST_CODE_661_1 = 1;
private int bbbbb;
private TextView txt;
private String bubul;
FirebaseDatabase database=FirebaseDatabase.getInstance();
final DatabaseReference AllFacebase =database.getReference("всего").child("йй");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt=findViewById(R.id.textView);
bubbleWrap=BubbleWrap.getInstance();
setupAddMoreButton();
setupPopActivityButton();
setupCocActivityButton();
txtintent=(TextView)findViewById(R.id.txtintent);
AllFacebase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
bubul=String.valueOf(dataSnapshot.getValue());
txtintent.setText(bubul);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
protected void onResume() {
super.onResume();
updateUI();
}
private void setupAddMoreButton(){
Button btn=findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bubbleWrap.addMoreBubbles();
updateUI();
}
});
}
private void setupPopActivityButton(){
Button btn=findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void setupCocActivityButton(){
Button btn=findViewById(R.id.buttoncoc);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void updateUI(){
txtintent.setText(String.format(Locale.getDefault(),"%d",
bubbleWrap.getNumBubbles()));
}
}
second activity
activity, where I change the variable, I want to write to Firebase
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop);
bubbleWrap=BubbleWrap.getInstance();
final TextView txt=findViewById(R.id.textView2);
setupPopButton();
updateUI();
Intent intent=new Intent();
intent.putExtra("bubles", bubbleWrap.getNumBubbles());
}
private void setupPopButton(){
Button btn=findViewById(R.id.cocbtb);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bubbleWrap.popBubble();
updateUI();
}
});
}
private void updateUI(){
TextView txt=findViewById(R.id.textView2);
txt.setText(String.format(Locale.getDefault(),
"Bubbles left: %d",
bubbleWrap.getNumBubbles()));
}
}
Singleton
public class BubbleWrap {
private static final int ADD_MORE_BUBBLES = 10;
private int numBubbles;
private static BubbleWrap instance;
private BubbleWrap(){
}
public static BubbleWrap getInstance(){
if(instance==null){
instance=new BubbleWrap();
}
return instance;
}
public int getNumBubbles() {
return numBubbles;
}
public void addMoreBubbles(){
numBubbles+=ADD_MORE_BUBBLES;
}
public void popBubble() {
numBubbles--;
}
public void saveintent(){
}
}

Firebase Recycler Adapter is not showing my Recyclerview in Fragments

Basically i followed the accepted answer of this with few changes in my Activity and it worked perfect. My problem is that I wrote the exact same codes for my Fragment. when I open my app, it doesn't show anything. Before I changed my code in my fragment from a custom Adapter to the FirebaseRecyclerAdapter, everything worked fine.
This is my Fragment class
public class HomeFragment extends BaseFragment {
public Button buttonsrch, openFreezer, openRef, openPantry, scrollToFreezer, scrollToRef, scrollToPantry;
public NestedScrollView scrollView;
public RelativeLayout mFreezerLayout,mRefrigeratorLayout, mPantryLayout;
public FloatingActionButton mAddItems;
public DatabaseReference mDatabaseFreezer;
public RecyclerView mFreezerRecyclerView;
public ArrayList<Event> mDataSet;
private FirebaseRecyclerAdapter<Event, ProductHolder> firebaseRecyclerAdapter;
#Override
public int getLayoutResId() {
return R.layout.fragment_home;
}
#Override
public View inOnCreateView(View root, #Nullable ViewGroup container, Bundle savedInstancesState) {
View view = mRoot;
buttonsrch = view.findViewById(R.id.searchButton);
openPantry = view.findViewById(R.id.ShowMorePantry);
openRef = view.findViewById(R.id.ShowMoreRefrigerator);
openFreezer = view.findViewById(R.id.ShowMoreFreezer);
scrollToFreezer = view.findViewById(R.id.bringToFreezer);
scrollToPantry = view.findViewById(R.id.bringToPantry);
scrollToRef = view.findViewById(R.id.bringToRefrigerator);
scrollView = view.findViewById(R.id.scrollViewHomeFragment);
mFreezerLayout = view.findViewById(R.id.FreezerLayout);
mPantryLayout =view.findViewById(R.id.PantryRelativeLayout);
mRefrigeratorLayout = view.findViewById(R.id.RefrigeratorRelativeLayout);
mAddItems = view.findViewById(R.id.addItems_Inventory);
mAddItems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), AddInventoryActivity.class));
}
});
buttonsrch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getActivity(), Search_Activity.class);
getActivity().startActivity(i);
}
});
openPantry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent h = new Intent(getActivity(), PantryActivity.class);
getActivity().startActivity(h);
}
});
openRef.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent g = new Intent(getActivity(), RefActivity.class);
getActivity().startActivity(g);
}
});
openFreezer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent s = new Intent(getActivity(), FreezerActivity.class);
getActivity().startActivity(s);
}
});
scrollToFreezer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FocusToFreezer();
}
});
scrollToRef.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FocusToRef();
}
});
scrollToPantry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FocusToPantry();
}
});
mDataSet = new ArrayList<>();
mFreezerRecyclerView = view.findViewById(R.id.FreezerRecyclerView);
mFreezerRecyclerView.setHasFixedSize(true);
mFreezerRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mDatabaseFreezer = FirebaseDatabase.getInstance().getReference().child("FreezerItems");
Query query = mDatabaseFreezer;
FirebaseRecyclerOptions<Event> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<Event>()
.setQuery(query, Event.class).build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Event, ProductHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(ProductHolder holder, int position, Event model) {
model = mDataSet.get(position);
holder.mItemName.setText(model.getName());
holder.mItemDate.setText(model.getDate());
final Event finalModel = model;
holder.mDeleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseFreezer.child(finalModel.get_id()).removeValue();
}
});
}
#Override
public ProductHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler_view_row_inventory,parent,false);
return new ProductHolder(view);
}
};
mDatabaseFreezer.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
HashMap<String, String> value = (HashMap<String,String>) dataSnapshot.getValue();
if (value != null) {
String name = value.get("Name");
String date = value.get("Date");
String key = value.get("Key");
mDataSet.add(new Event(name,date,null, key));
Collections.sort(mDataSet, new Comparator<Event>() {
#Override
public int compare(Event event, Event t1) {
if (event.getDate() == null || t1.getDate() == null)
return 0;
return event.getDate().compareTo(t1.getDate());
}
});
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mFreezerRecyclerView.setAdapter(firebaseRecyclerAdapter);
return root;
}
private class ProductHolder extends RecyclerView.ViewHolder{
private TextView mItemName, mItemDate;
private Button mDeleteBtn;
public ProductHolder(View itemView) {
super(itemView);
mItemName = itemView.findViewById(R.id.ItemNameTxtView);
mItemDate = itemView.findViewById(R.id.BestBeoforeTxtView);
mDeleteBtn = itemView.findViewById(R.id.deleteItem);
}
}
#Override
public void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
if (firebaseRecyclerAdapter != null){
firebaseRecyclerAdapter.startListening();
}
}
private void FocusToFreezer(){
scrollView.post(new Runnable() {
#Override
public void run() {
scrollView.smoothScrollTo(0, mFreezerLayout.getTop());
}
});
}
private void FocusToRef(){
scrollView.post(new Runnable() {
#Override
public void run() {
scrollView.smoothScrollTo(0, mRefrigeratorLayout.getTop());
}
});
}
private void FocusToPantry(){
scrollView.post(new Runnable() {
#Override
public void run() {
scrollView.smoothScrollTo(0, mPantryLayout.getTop());
}
});
}
}
The only difference I could find is OnStart() and onStop() in activity are protected while on fragments are public
EDIT I found another page with the same problem and apparently FirebaseRecyclerAdapter doesn't work well with Fragments
I finally found an answer
simply remove mFreezerRecyclerView.setHasFixedSize(true);

Issue with coding the communication between a fragment and an async task

I'm new to this concept. I read several threads but I block so thanks in advance for your patience!
In a fragment (frag1) I launch an async task. I want to prevent the user of doing anything while the task is not completed so I want to communicate the % of the task completed so the user waits informed.
I've defined an interface in a java SetVal.java:
interface SetVal {
void setVal(int val);
}
My async task:
class AsyncCounter extends AsyncTask<Void, Integer, Void> {
private SetVal sender;
public AsyncCounter(SetVal sv){
this.sender = sv;
}
#Override
protected Void doInBackground(Void... params) {
for(int i=0;i<60;i++){
publishProgress(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
Log.i("ASYNC TASK","val: "+values[0]);
sender.setVal(values[0]);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
public interface SetVal {
public void setVal(int val);
}
public void setListener(SetVal listener) {
this.sender = listener;
}
}
I'm struggling to know how to pass the interface to the task.
Is my code correct?
How do I instantiate the async task?
fragment:
public class Frag1 extends android.app.Fragment implements SetVal {
private static TextView txt;
private int counter;
SetVal listener;
public Frag1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_frag1, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txt = (TextView) getActivity().findViewById(R.id.txt);
Button btn = (Button) getActivity().findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i("Frag1", "val: " + counter);
if (counter > 0) return;
FragmentTransaction ft = getFragmentManager().beginTransaction();
Frag2 f2 = new Frag2();
ft.replace(R.id.content_frame, f2);
ft.addToBackStack("f2");
ft.commit();
}
});
Button btn2 = (Button) getActivity().findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AsyncCounter ac = new AsyncCounter(???????);
ac.execute();
}
});
}
#Override
public void setVal(int val) {
counter = val;
}
}
Not sure what and why you are trying to do that, but you can pass the Fragment :
Try to create a private method:
public void onClick(View v) {
startMyAsync();
}
private void startMyAsync() {
new AsyncCounter(this).execute();
}
finally:
public AsyncCounter(Frag1 context){
this.sender = (SetVal)context;
}

Categories

Resources