Android-AltBeacon-library intergration in a java class - java

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

Related

Tricky Null Pointer exception on an Injector in BaseActivity

-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

IOIOActivity and AppCompactActivity

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!

Loading multiple AdMob videos

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() {
}

How to send Parcelable Object that contains doubly nested Parcelable arrays

I am trying to write an object in my startup activty to Parcel then send it to my Main activity using an intent. However I get a null pointer exception when retrieving the ParacelableArrayExtra in my Main activity. So i put in a check for null to handle the the null condition. However, the forecast Object does have data before being put into the intent so this condition should not be met.
I seems as though the Array of objects never gets put inside the intent. I this because I have my data being parceled incorrectly?
StartUpActivity.java
public class StartUpActivity extends AppCompatActivity {
public static final String FORECAST_KEY = "FORECAST_KEY";
private Forecast[] mForecasts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new BackgroundTask(this).execute();
}
#Override
public void startActivityForResult(Intent intent, int requestCode) {
super.startActivityForResult(intent, requestCode);
}
private class BackgroundTask extends AsyncTask {
private Intent mIntent;
private Context mContext;
private static final String TAG = "BACKGROUND_TASK";
public BackgroundTask(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mIntent = new Intent(StartUpActivity.this, MainActivity.class);
}
#Override
protected Object doInBackground(Object[] params) {
mForecasts = getForecasts();
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
// mForecasts is populated and does contain data
mIntent.putExtra(StartUpActivity.FORECAST_KEY, mForecasts);
// mForecasts in not located in mIntent
startActivity(mIntent);
finish();
}
// Other methods omitted
}
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
intent.getParcelableArrayExtra(StartUpActivity.FORECAST_KEY);
Parcelable[] allForecastParcelables = getIntent().getParcelableArrayExtra(StartUpActivity.FORECAST_KEY);
if (allForecastParcelables != null) {
mForecasts = new Forecast[allForecastParcelables.length];
for (int i = 0 ; i < allForecastParcelables.length; i++) {
mForecasts[i] = (Forecast) allForecastParcelables[i];
}
}
else {
mForecasts = null;
}
setupSlidingTabs();
}
Here are my Model objects that implement Parcelable
Forecast.java
public class Forecast implements Parcelable{
Day[] mDays;
public Day[] getDailyForecast() {
return mDays;
}
public void setDailyForecast(Day[] days) {
mDays = days;
}
#Override
public int describeContents() {
return 0;
}
public Forecast() {}
private Forecast(Parcel in) {
in.readTypedArray(mDays, Day.CREATOR);
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedArray(mDays, flags);
}
public static final Creator<Forecast> CREATOR = new Creator<Forecast>() {
#Override
public Forecast createFromParcel(Parcel source) {
return new Forecast(source);
}
#Override
public Forecast[] newArray(int size) {
return new Forecast[size];
}
};
}
Day.java
public class Day implements Parcelable {
private Hour[] mHours;
private Average mAverage;
public Hour[] getHourlyForecast() {
return mHours;
}
public void setHourlyForecast(Hour[] hours) {
mHours = hours;
}
public Average getAverageForecast() {
return mAverage;
}
public void setAverageForecast(Average average) {
mAverage = average;
}
#Override
public int describeContents() {
return 0;
}
public Day() {}
private Day(Parcel in) {
in.readTypedArray(mHours, Hour.CREATOR);
mAverage = in.readParcelable(getClass().getClassLoader());
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedArray(mHours, flags);
dest.writeParcelable(mAverage, flags);
}
public static final Creator<Day> CREATOR = new Creator<Day>() {
#Override
public Day createFromParcel(Parcel source) {
return new Day(source);
}
#Override
public Day[] newArray(int size) {
return new Day[size];
}
};
}
Average.java
public class Average implements Parcelable {
private String mWindCompassDireciton;
public String getWindCompassDireciton() {
return mWindCompassDireciton;
}
public void setWindCompassDireciton(String windCompassDireciton) {
mWindCompassDireciton = windCompassDireciton;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mWindCompassDireciton);
}
public Average() {}
private Average(Parcel in) {
mWindCompassDireciton = in.readString();
}
public static final Creator<Average> CREATOR = new Creator<Average>() {
#Override
public Average createFromParcel(Parcel source) {
return new Average(source);
}
#Override
public Average[] newArray(int size) {
return new Average[size];
}
};
}
And Hour is similar to average.java
Is there anything I am overlooking?
Each ArrayList and object inside the parcelable object should be peaceable too, Check this example. but i recommend you to send GSON and convert it to String and send it between activities as a string and convert it again to your object, Check this example.

Why aren't all my listeners registered?

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

Categories

Resources