-Github Api calling Android app
App uses Dagger and build with no error but crashes immediately on launch of app. In the stack stack trace it says that its the Injector and its null as it calls inject passing in the activity.
At first I was thinking it was Dagger but then I realised the code is getting generated for what i need so dont think its that
i then checked the manifest where I declared the name of the application as it was crashhing on launch and that what it mostly says on stackoverflow I've been there done that so it not that which leads me to being puzzled as I''m sure someone with more knowhow would see it immediately.
Activity----------------------------------------
public abstract class BaseActivity extends AppCompatActivity {
private static String INSTANCE_ID = "instance_id";
private String instanceId;
#Inject ScreenInjector screenInjector;
#Inject ScreenNavigator screenNavigator;
private Router router;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
if(savedInstanceState != null) {
instanceId = savedInstanceState.getString(INSTANCE_ID);
} else {
instanceId = UUID.randomUUID().toString();
}
Injector.inject(this);
setContentView(layoutRes());
ViewGroup screenContainer = findViewById(R.id.screen_container);
if(screenContainer == null) {
throw new NullPointerException("Activity must have a view with the id of screen_container");
}
router = Conductor.attachRouter(this, screenContainer, savedInstanceState);
screenNavigator.initializeWithRouter(router, initialScreen());
monitorBackStack();
super.onCreate(savedInstanceState);
}
#LayoutRes
protected abstract int layoutRes();
protected abstract Controller initialScreen();
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(INSTANCE_ID, instanceId);
}
#Override
public void onBackPressed() {
if(!screenNavigator.pop()) {
super.onBackPressed();
}
}
public String getInstanceId() {
return instanceId;
}
#Override
protected void onDestroy() {
super.onDestroy();
screenNavigator.clear();
if(isFinishing()) {
Injector.clearComponent(this);
}
}
public ScreenInjector getScreenInjector() {
return screenInjector;
}
private void monitorBackStack() {
router.addChangeListener(new ControllerChangeHandler.ControllerChangeListener() {
#Override
public void onChangeStarted(#Nullable Controller to,
#Nullable Controller from,
boolean isPush,
#NonNull ViewGroup container,
#NonNull ControllerChangeHandler handler) {
}
#Override
public void onChangeCompleted(#Nullable Controller to,
#Nullable Controller from,
boolean isPush,
#NonNull ViewGroup container,
#NonNull ControllerChangeHandler handler) {
if(!isPush && from != null) {
Injector.clearComponent(from);
}
}
});
}
}
Injector-----------------------------------
public class Injector {
private Injector() {
}
public static void inject(Activity activity) {
ActivityInjector.get(activity).inject(activity);
}
public static void clearComponent(Activity activity) {
ActivityInjector.get(activity).clear(activity);
}
public static void inject(Controller controller) {
ScreenInjector.get(controller.getActivity()).inject(controller);
}
public static void clearComponent(Controller controller) {
ScreenInjector.get(controller.getActivity()).clear(controller);
}
}
ActivityInjector-----------------------------------
public class ActivityInjector {
private final Map<Class<? extends Activity>, Provider<AndroidInjector.Factory<? extends Activity>>> activityInjectors;
private final Map<String, AndroidInjector<? extends Activity>> cache = new HashMap<>();
#Inject
ActivityInjector(Map<Class<? extends Activity>, Provider<AndroidInjector.Factory<?extends Activity>>> activityInjectors) {
this.activityInjectors = activityInjectors;
}
void inject(Activity activity) {
if(!(activity instanceof BaseActivity)) {
throw new IllegalArgumentException("Activity must extend BaseActivity");
}
String instanceId = ((BaseActivity) activity).getInstanceId();
if(cache.containsKey(instanceId)) {
((AndroidInjector<Activity>) cache.get(instanceId)).inject(activity);
return;
}
AndroidInjector.Factory<Activity> injectorFactory =
(AndroidInjector.Factory<Activity>) activityInjectors.get(activity.getClass()).get();
AndroidInjector<Activity> injector = injectorFactory.create(activity);
cache.put(instanceId, injector);
injector.inject(activity);
}
void clear(Activity activity) {
if(!(activity instanceof BaseActivity)) {
throw new IllegalArgumentException("Activity must extend BaseActivity");
}
cache.remove(((BaseActivity) activity).getInstanceId());
}
static ActivityInjector get(Context context) {
return ((MyApplication)context.getApplicationContext()).getActivityInjector();
}
}
Any elaborations would be greatly welcome links hints or any more info you need just tell me.
Github Reop
Related
I'm making a simple app that has to make a call to an API that returns an object with some attributes and is shown in a RecyclerView.
The call is being made to https://jsonplaceholder.typicode.com/photos?_start=0&_limit=5
The app doesn't crash, the recyclerview is being generated but it is empty. I used the debugger and saw that the list in the adapter of the recyclerview is empty (the size is 0).
I believe the issue is with the structure of the java objects I made but I can't confirm it for sure and I can't seem to modify my object structure to match that of the returned object. I'm not seeing an object with other objects inside of like with other apis I've worked on (when I check the above link with a json online reader).
I usually make my object and another object container (which has a list of the first object). My suspicion is that the issue is there, please help me find the problem.
Below the main activity, object, object container, adapter, retrofit object, object dao and object controller.
Activity:
public class PhotoActivity extends AppCompatActivity implements AdapterPhotoRecyclerView.SelectedPhotoListener {
private AdapterPhotoRecyclerView adapterPhotoRecyclerView;
private RecyclerView recyclerView;
private ProgressBar progressBar;
private LinearLayoutManager linearLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
progressBar = findViewById(R.id.photo_activity_progress_bar);
makeCall("photos?_start=0&_limit=5");
adapterPhotoRecyclerView = new AdapterPhotoRecyclerView(this);
recyclerView = findViewById(R.id.photo_activity_recyclerview);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapterPhotoRecyclerView);
}
public void makeCall(String fixedUrl) {
MyPhotoController myPhotoController = new MyPhotoController();
myPhotoController.getPhotos(fixedUrl, new ResultListener<MyPhotoContainer>() {
#Override
public void finish(MyPhotoContainer result) {
progressBar.setVisibility(View.VISIBLE);
adapterPhotoRecyclerView.setMyPhotoList(result.getmPhotoList());
progressBar.setVisibility(View.GONE);
}
});
}
#Override
public void selectePhoto(Integer position, List<MyPhoto> myPhotoList) {
MyPhoto clickedPhoto = myPhotoList.get(position);
Toast.makeText(this, clickedPhoto.getTitle(), Toast.LENGTH_SHORT).show();
}
}
Adapter of the RecyclerView
public class AdapterPhotoRecyclerView extends RecyclerView.Adapter<AdapterPhotoRecyclerView.PhotoViewHolder> {
private List<MyPhoto> myPhotoList;
private SelectedPhotoListener selectedPhotoListener;
public AdapterPhotoRecyclerView(SelectedPhotoListener selectedPhotoListener) {
myPhotoList = new ArrayList<>();
this.selectedPhotoListener = selectedPhotoListener;
}
public void setMyPhotoList(List<MyPhoto> myPhotoList) {
this.myPhotoList = myPhotoList;
notifyDataSetChanged();
}
public List<MyPhoto> getMyPhotoList() {
return myPhotoList;
}
#NonNull
#Override
public PhotoViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_cell_photo, parent, false);
PhotoViewHolder photoViewHolder = new PhotoViewHolder(view);
return photoViewHolder;
}
#Override
public void onBindViewHolder(#NonNull PhotoViewHolder holder, int position) {
MyPhoto myPhoto = myPhotoList.get(position);
holder.bindPhoto(myPhoto);
}
#Override
public int getItemCount() {
if (myPhotoList == null){
return 0;
} else {
return myPhotoList.size();
}
}
public class PhotoViewHolder extends RecyclerView.ViewHolder {
private ImageView thumbnail;
private TextView title;
public PhotoViewHolder(#NonNull View itemView) {
super(itemView);
this.thumbnail = itemView.findViewById(R.id.recyclerview_cell_photo_thumbnail);
this.title = itemView.findViewById(R.id.recyclerview_cell_photo_title);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedPhotoListener.selectePhoto(getAdapterPosition(), myPhotoList);
}
});
}
public void bindPhoto(MyPhoto myPhoto) {
Glide.with(itemView).load(myPhoto.getThumbnailUrl()).placeholder(R.mipmap.ic_launcher).into(thumbnail);
title.setText(myPhoto.getTitle());
}
}
public interface SelectedPhotoListener {
public void selectePhoto(Integer position, List<MyPhoto> myPhotoList);
}
}
Object dao
public class MyPhotoDao extends MyRetrofit {
private JsonPlaceholderService service;
public MyPhotoDao() {
super("https://jsonplaceholder.typicode.com/");
service = retrofit.create(JsonPlaceholderService.class);
}
public void getPhotos(String fixedUrl, final ResultListener<MyPhotoContainer> listenerOfTheController) {
Call<MyPhotoContainer> call = service.jsonPlaceholderPhoto(fixedUrl);
call.enqueue(new Callback<MyPhotoContainer>() {
#Override
public void onResponse(Call<MyPhotoContainer> call, Response<MyPhotoContainer> response) {
MyPhotoContainer myPhotoContainer = response.body();
listenerOfTheController.finish(myPhotoContainer);
}
#Override
public void onFailure(Call<MyPhotoContainer> call, Throwable t) {
}
});
}
public void getAlbum(String fixedUrl, final ResultListener<List<Album>> listenerOfTheController){
Call<List<Album>> call = service.jsonPlaceholderAlbum(fixedUrl);
call.enqueue(new Callback<List<Album>>() {
#Override
public void onResponse(Call<List<Album>> call, Response<List<Album>> response) {
List<Album> albumList = response.body();
listenerOfTheController.finish(albumList);
}
#Override
public void onFailure(Call<List<Album>> call, Throwable t) {
}
});
}
}
Object controller
public class MyPhotoController {
public void getPhotos(String fixedUrl, final ResultListener<MyPhotoContainer> listenerOfTheView) {
MyPhotoDao myPhotoDao = new MyPhotoDao();
myPhotoDao.getPhotos(fixedUrl, new ResultListener<MyPhotoContainer>() {
#Override
public void finish(MyPhotoContainer result) {
listenerOfTheView.finish(result);
}
});
}
public void getAlbums(String fixedUrl, final ResultListener<List<Album>> listenerOfTheView){
MyPhotoDao myPhotoDao = new MyPhotoDao();
myPhotoDao.getAlbum(fixedUrl, new ResultListener<List<Album>>() {
#Override
public void finish(List<Album> result) {
listenerOfTheView.finish(result);
}
});
}
}
Retrofit object
public abstract class MyRetrofit {
protected Retrofit retrofit;
public MyRetrofit(String baseUrl) {
OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient.build())
.addConverterFactory(GsonConverterFactory.create());
retrofit = builder.build();
}
}
Object I'm trying to GET
public class MyPhoto implements Serializable {
#SerializedName("AlbumId")
private Integer albumNumber;
#SerializedName("id")
private Integer photoId;
private String title;
#SerializedName("url")
private String photoUrl;
private String thumbnailUrl;
public Integer getAlbumNumber() {
return albumNumber;
}
public Integer getPhotoId() {
return photoId;
}
public String getTitle() {
return title;
}
public String getPhotoUrl() {
return photoUrl;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
}
Object container
public class MyPhotoContainer implements Serializable {
#SerializedName("array")
private List<MyPhoto> mPhotoList;
public List<MyPhoto> getmPhotoList() {
return mPhotoList;
}
}
If there is anything missing please let me know.
Any help and comments are apreciated!
JSON payload does not fit to POJO classes. You do not need to use MyPhotoContainer class at all. Response JSON is a JSON Array with directly placed JSON Objects. getPhotos method should look similar to getAlbum method. Try:
public void getPhotos(String fixedUrl, final ResultListener<List<MyPhoto>> listenerOfTheView)
I'm trying to integrate the altbeacon function in a java class in android studio, but I'm getting an error because of the getActivity. I want to created an object from this class in onahter Activities..
so any idea how could it work?
It works perfect, when I add the altbeacon class in a activity under protected void onCreate(Bundle savedInstanceState).
public class detectRoom implements BeaconConsumer {
private List <IBeaconSensor> beaconList = new ArrayList <IBeaconSensor> ();
private BeaconManager beaconManager;
public detectRoom() {
name="detectRoom";
}
private String detectRoomName(String raum) {
return raum;
}
public void detectRoomMet () {
for (int i = 0;i< beaconList.size() ;i++){
if(beaconList.get(i).getName().equals("45")) { // 6 = Minor of Ibeacon
detectRoomName("Room3");
}
if(beaconList.get(i).getName().equals("55")) {
detectRoomName("Room2");
}
if(beaconList.get(i).getName().equals("85")) {
detectRoomName("Room1");
}
else {
detectRoomName("UnknowRoom");
}
}
}
#Override
public void onBeaconServiceConnect() {
beaconManager = new BeaconManager(getApplicationContext());
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
this.beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
if (beacons.size() > 0) {
beaconList.clear();
for(Iterator<Beacon> iterator = beacons.iterator(); iterator.hasNext();) {
beaconList.add(new IBeaconSensor (iterator.next().getId3().toString()));
}
}
}
});
try {
this.beaconManager.startRangingBeaconsInRegion(new Region("MyRegionId", null, null, null));
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public Context getApplicationContext() {
return null;
}
#Override
public void unbindService(ServiceConnection serviceConnection) {
this.beaconManager.unbind(this);
}
#Override
public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
return false;
}
public void bindBeacon() {
beaconManager.bind(this);
}
public void unBindBeacon() {
beaconManager.unbind(this);
}
}
When making a POJO that extends BeaconConsumer you must do two things:
Pass a reference to an Android Context to the POJO.
Chain the methods bindService, unbindService, getApplicationContext to the Context above.
Like this:
public class Pojo extends BeaconConsumer() {
private Context mContext;
public Pojo(Context context) {
mContext = context;
}
#Override
public Context getApplicationContext() {
return mContext.getApplicationContext();
}
#Override
public void unbindService(ServiceConnection serviceConnection) {
mContext.unbindService(serviceConnection);
}
#Override
public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
return mContext.bindService(intent, serviceConnection, i);
}
...
}
I'm not experienced in Java development and migrating from Eclipse. I don't know how to use the nested classes in my case where I need to extend AppCompactActivity and IOIOActivity. Considering, I have another inner class Looper already extending another class. The code below isn't running what is inside Testing class. Can someone help me about how to execute my inner class, which is Testing class.
My code:
public class MainActivity extends AppCompatActivity {
private class Testing extends IOIOActivity {
private ToggleButton button_;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_ = (ToggleButton) findViewById(R.id.toggleButton);
}
class Looper extends BaseIOIOLooper {
/** The on-board LED. */
private DigitalOutput led_;
#Override
protected void setup() throws ConnectionLostException {
showVersions(ioio_, "IOIO connected!");
led_ = ioio_.openDigitalOutput(0, true);
enableUi(true);
}
#Override
public void loop() throws ConnectionLostException, InterruptedException {
led_.write(!button_.isChecked());
Thread.sleep(100);
}
#Override
public void disconnected() {
enableUi(false);
toast("IOIO disconnected");
}
#Override
public void incompatible() {
showVersions(ioio_, "Incompatible firmware version!");
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
private void showVersions(IOIO ioio, String title) {
toast(String.format("%s\n" +
"IOIOLib: %s\n" +
"Application firmware: %s\n" +
"Bootloader firmware: %s\n" +
"Hardware: %s",
title,
ioio.getImplVersion(IOIO.VersionType.IOIOLIB_VER),
ioio.getImplVersion(IOIO.VersionType.APP_FIRMWARE_VER),
ioio.getImplVersion(IOIO.VersionType.BOOTLOADER_VER),
ioio.getImplVersion(IOIO.VersionType.HARDWARE_VER)));
}
private void toast(final String message) {
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
});
}
private int numConnected_ = 0;
private void enableUi(final boolean enable) {
// This is slightly trickier than expected to support a multi-IOIO use-case.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (enable) {
if (numConnected_++ == 0) {
button_.setEnabled(true);
}
} else {
if (--numConnected_ == 0) {
button_.setEnabled(false);
}
}
}
});
}
}
}
Thankss
I found my answer and I would like to share it with you all for the future. This is for starting a new IOIOActivity in Android Studio. IOIO developers haven't written the official IOIO code for AppCompactActivity yet. After couple of days trying, its finally tested and working with IOIO led.
Create a new Class file called AppCompactIOIOActivity (I just like that name) in your package. Note: all credits to Ytai. IOIO code from App507
public class AppCompactIOIOActivity extends AppCompatActivity implements IOIOLooperProvider {
private final IOIOAndroidApplicationHelper helper_ = new IOIOAndroidApplicationHelper(this, this);
public AppCompactIOIOActivity() {
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.helper_.create();
}
protected void onDestroy() {
this.helper_.destroy();
super.onDestroy();
}
protected void onStart() {
super.onStart();
this.helper_.start();
}
protected void onStop() {
this.helper_.stop();
super.onStop();
}
#SuppressLint("WrongConstant")
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if((intent.getFlags() & 268435456) != 0) {
this.helper_.restart();
}
}
protected IOIOLooper createIOIOLooper() {
throw new RuntimeException("Client must override one of the createIOIOLooper overloads!");
}
public IOIOLooper createIOIOLooper(String connectionType, Object extra) {
return this.createIOIOLooper();
}
}
Then in your MainActivity
public class MainActivity extends AppCompactIOIOActivity {
private ToggleButton button_;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_ = (ToggleButton) findViewById(R.id.toggleButton);
}
class Looper extends BaseIOIOLooper {
/** The on-board LED. */
private DigitalOutput led_;
#Override
protected void setup() throws ConnectionLostException {
showVersions(ioio_, "IOIO connected!");
led_ = ioio_.openDigitalOutput(0, true);
enableUi(true);
}
#Override
public void loop() throws ConnectionLostException, InterruptedException {
led_.write(!button_.isChecked());
Thread.sleep(100);
}
#Override
public void disconnected() {
enableUi(false);
toast("IOIO disconnected");
}
#Override
public void incompatible() {
showVersions(ioio_, "Incompatible firmware version!");
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
private void showVersions(IOIO ioio, String title) {
toast(String.format("%s\n" +
"IOIOLib: %s\n" +
"Application firmware: %s\n" +
"Bootloader firmware: %s\n" +
"Hardware: %s",
title,
ioio.getImplVersion(IOIO.VersionType.IOIOLIB_VER),
ioio.getImplVersion(IOIO.VersionType.APP_FIRMWARE_VER),
ioio.getImplVersion(IOIO.VersionType.BOOTLOADER_VER),
ioio.getImplVersion(IOIO.VersionType.HARDWARE_VER)));
}
private void toast(final String message) {
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
});
}
private int numConnected_ = 0;
private void enableUi(final boolean enable) {
// This is slightly trickier than expected to support a multi-IOIO use-case.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (enable) {
if (numConnected_++ == 0) {
button_.setEnabled(true);
}
} else {
if (--numConnected_ == 0) {
button_.setEnabled(false);
}
}
}
});
}
}
Don't forget to add your resources and dependances from IOIO developers. Good luck!
For demonstration purposes, the app has one activity that simply offers this:
You click a button, view a rewarded video, and you are rewarded with whatever.
The Problem
How can I load the videos? From what I have seen you can only call mAd.loadAd() once. There are 3 videos, each with their own AD UNIT ID. Each ad unit can have its own listener, but only one video loads so it doesn't matter...
When trying to load multiple videos
For example:
mAd1.loadAd("AD_UNIT_1", new AdRequest.Builder().build());
mAd2.loadAd("AD_UNIT_2", new AdRequest.Builder().build());
mAd3.loadAd("AD_UNIT_3", new AdRequest.Builder().build());
results in only the last video being loaded and this in log:
W/Ads: Loading already in progress, saving this object for future refreshes.
onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAd1 = MobileAds.getRewardedVideoAdInstance(this);
mAd2 = MobileAds.getRewardedVideoAdInstance(this);
mAd3 = MobileAds.getRewardedVideoAdInstance(this);
listeners...
mAd1.loadAd() etc
}
Thank you for your help
Edit: It's clear I am thinking about this problem wrong. I have 5+ ad zones that each will play a rewarded video and give a different reward (for example, one gives coins, one gives a level up, and so on..). There is no reason to load 5 videos. I should load one in onCreate(), so it's ready when needed, then load it again after the item is rewarded so it's ready for next time.
So the question remains, if there is just the one video, and thus one ad zone, being loaded onCreate() then how can I track what reward to give?
Here's a simple solution...
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAd = MobileAds.getRewardedVideoAdInstance(this);
mAd.setRewardedVideoAdListener(new RewardedVideoAdListener() {
#Override
public void onRewarded(RewardItem rewardItem) {
switch(Constants.currentAd) {
case("REWARD1"):
//do something
Constants.currentAd = "";
break;
case("REWARD2"):
//do something
Constants.currentAd = "";
break;
case("REWARD3"):
//do something
Constants.currentAd = "";
break;
}
}
});
mAd.loadAd("REWARDED_VIDEO_UNIT_ID", new AdRequest.Builder().build());
}
public void showRewardedVideo() {
if (mAd.isLoaded()) {
mAd.show();
}
}
Constants.java
public class Constants {
public static String currentAd = "";
}
Showing the ad after button click
rewardButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Constants.currentAd = "REWARD1";
dismiss();
((MainActivity) getActivity()).showRewardedVideo();
}
});
REWARDED_VIDEO_UNIT_ID is one ad unit for rewarded video in AdMob...remove the rest. No need for other units, you can track whatever you like in the listener.
Other simple soluction...
AbstractRewardVideo.java
public abstract class AbstractRewardVideo {
private RewardedVideoAd mAd;
private String adId = "ca-app-pub...";
private Activity activity;
abstract protected RewardedVideoAdListener getListener();
public void init(Activity activity) {
this.activity = activity;
mAd = MobileAds.getRewardedVideoAdInstance(activity);
setAdId(adId);
loadRewardedVideoAd();
}
public Activity getActivity(){
return this.activity;
}
public void loadRewardedVideoAd() {
mAd.loadAd(adId, new AdRequest.Builder().build());
}
public void showVideo(){
setListener(getListener());
if (mAd.isLoaded()) {
mAd.show();
} else {
Utils.exibirToast("Don't loaded!");
}
}
public void setAdId(#NonNull String id){
this.adId = id;
}
public void setListener(RewardedVideoAdListener listener){
mAd.setRewardedVideoAdListener(listener);
}
}
Reward1.java
public class Reward1 extends AbstractRewardVideo {
public Reward1(Activity activity) {
init(activity);
}
#Override
protected RewardedVideoAdListener getListener() {
return new Listener();
}
private class Listener implements RewardedVideoAdListener {
#Override
public void onRewarded(RewardItem rewardItem) {
//Do something...
}
public void onRewardedVideoAdLoaded() {}
public void onRewardedVideoAdOpened() {}
public void onRewardedVideoStarted() {}
public void onRewardedVideoAdClosed() { loadRewardedVideoAd(); }
public void onRewardedVideoAdLeftApplication() {}
public void onRewardedVideoAdFailedToLoad(int i) {}
}
}
Reward2.java
public class Reward2 extends AbstractRewardVideo {
public Reward2(Activity activity) {
init(activity);
}
#Override
protected RewardedVideoAdListener getListener() {
return new Listener();
}
private class Listener implements RewardedVideoAdListener {
#Override
public void onRewarded(RewardItem rewardItem) {
//Do something...
}
public void onRewardedVideoAdLoaded() {}
public void onRewardedVideoAdOpened() {}
public void onRewardedVideoStarted() {}
public void onRewardedVideoAdClosed() { loadRewardedVideoAd(); }
public void onRewardedVideoAdLeftApplication() {}
public void onRewardedVideoAdFailedToLoad(int i) {}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity{
Reward1 reward1;
Reward2 reward2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
reward1 = new Reward1(this);
reward2 = new Reward1(this);
...
reward1.showVideo();
...
reward2.showVideo();
}
}
MobileAds.initialize ( this, "ca-app-pub-4761500786576152~8215465788" );
RewardedVideoAd mAd = MobileAds.getRewardedVideoAdInstance(this);
mAd.setRewardedVideoAdListener(Video_Ad.this);
}
#Override
public void onRewardedVideoAdLoaded() {
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
}
#Override
public void onRewarded(RewardItem rewardItem) {
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}
public interface DownloadListener {
public void onDownloaded();
}
public class DownloadManager {
private static DownloadManager instance;
private DownloadListener mDownloadListener;
public static synchronized DownloadManager getInstance(){
if(instance == null)
instance = new DownloadManager();
return instance;
}
private DownloadManager() {
myHandler.sendEmptyMessageDelayed(29, 3 * 1000);
}
public void registerDownloadListener(DownloadListener downloadListener) {
mDownloadListener = downloadListener;
}
Handler myHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
if (msg.what == 29) {
mDownloadListener.onDownloaded();
return true;
}
return false;
}
});
}
public class I implements DownloadListener {
public I() {
DownloadManager.getInstance().registerDownloadListener(this);
}
#Override
public void onDownloaded() {
Log.e("TAG", "I onDownloaded");
}
}
public class You implements DownloadListener {
public You() {
DownloadManager.getInstance().registerDownloadListener(this);
}
#Override
public void onDownloaded() {
Log.e("TAG", "You onDownloaded");
}
}
public class PATTERNSActivity extends Activity implements DownloadListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new I();
new You();
DownloadManager.getInstance().registerDownloadListener(this);
}
#Override
public void onDownloaded() {
Log.e("TAG","PATTERNSActivity onDownloaded");
}
}
I am expecting to get:
I onDownloaded
You onDownloaded
PATTERNSActivity onDownloaded
But I am getting only:
PATTERNSActivity onDownloaded
What could it be the problem?
You keep registered downloaders in a single instance property:
// Last call's downloadListener wins.
public void registerDownloadListener(DownloadListener downloadListener) {
mDownloadListener = downloadListener;
}
The last one registered is the activity's:
new I(); // First set singleton's property to an instance of I...
new You(); // ...then to an instance of You...
// ...then to the current instance.
DownloadManager.getInstance().registerDownloadListener(this);
Edit based on your comment.
public void registerDownloadListener(DownloadListener downloadListener) {
mDownloadListeners.add(downloadListener);
}
...
public boolean handleMessage(Message msg) {
if (msg.what != 29) {
return false;
}
for (DownloadListener listener : mDownloadListeners) {
listener.onDownloaded();
}
return true;
}
In your code, this gets executed by calling mDownloadListener.onDownloaded(); in the DownloadManager class.
#Override
public void onDownloaded() {
Log.e("TAG","PATTERNSActivity onDownloaded");
}
In don't see why the onDownloaded methods of the I and YOU class should be executed, they're never called. Only the OnDownloaded method of your Listener is called.
For starters, I think you are not using a list. You just override the value so you will always get the last one:
public void registerDownloadListener(DownloadListener downloadListener) {
mDownloadListener = downloadListener;
}