How to use non static method (observer method) in static main - java

want to use non static method in static main, but i cant. I know this problem but, because i use INotificationObserver, i cant make registerObserver as static. So i could solve my problem.
How can i solve this problem ?? Thanks .
non-static variable this cannot be referenced from a static context
Test
public class PushTest implements INotificationObserver{
NotificationService ns = NotificationService.getInstance();
public static void main(String[] args) {
try {
ns.registerObserver(this); // How can i register ???
Interface
public interface INotificationSubject {
public void registerObserver(INotificationObserver o);
public void removeObserver(INotificationObserver o);
public void notifyObserver(PushedNotification notification);
}
*NotificationService *
public class NotificationService implements INotificationSubject{
protected static final Logger logger = Logger.getLogger(NotificationService.class);
private volatile static NotificationService uniqueFactory;
private ArrayList observers;
private NotificationService() {
observers = new ArrayList();
}
public static NotificationService getInstance() {
if (uniqueFactory == null) {
synchronized (NotificationService.class) {
if (uniqueFactory == null) {
uniqueFactory = new NotificationService();
}
}
}
return uniqueFactory;
}
public static INotification GetNotificationObject(DeviceTypes Types) {
INotification messageSender = null;
if (Types == Types.IOS) {
messageSender = new IosNotification();
}
return messageSender;
}
public void registerObserver(INotificationObserver o) {
observers.add(o);
}
public void removeObserver(INotificationObserver o) {
int i =
observers.indexOf(o);
if (i >= 0) {
observers.remove(i);
}
}
public void notifyObserver(PushedNotification notification) {
for (int i = 0; i < observers.size(); i++) {
INotificationObserver observer = (INotificationObserver) observers.get(i);
observer.update(notification);
}
}
public void messageSendInfo(PushedNotification notification) {
notifyObserver(notification);
}
public void showSentInfo(PushedNotification notification) {
messageSendInfo(notification);
}
}

You need an instance:
INotificationObserver ino = new PushTest();
ns.registerObserver(ino);
Therefor, you don't need the ns attribute.

typical solution for this is initialize your class in the main method:
public class PushTest implements INotificationObserver{
NotificationService ns = NotificationService.getInstance();
public static void main(String[] args) {
PushTest pushTest = new Pushtest();
...
etc etc

Related

Use an object in other methods of a test class

I have a test class in Android test package. There is a class that I've create an object in it. But other method of this test class can not use this object and can not recognize the result of that method. Why and what should I do? I used static too but can't...
#RunWith(AndroidJUnit4.class)
public class PatientDaoTest {
private static int newRowId;
public static PatientRecordEntity newPatient1;
public void generationRecord(){
newRowId = 0;
PatientRecordEntity newPatient1 = new PatientRecordEntity();
newPatient1.setPatient_db_ID("23456");
newPatient1.setPatient_race("Chines");
newRowId = (int) patientDao.addNewPatient(newPatient1);
newPatient1.setPid(newRowId);
}
#Test
public void addNewPatient() throws Exception {
boolean pin = false;
if (0 != newRowId) {
pin = true;
}
assertTrue("addNewPatient is not true", pin);
}
use the annotation #Before.
like:
public class HTest {
public static Integer i;
#Before
public void before(){
i = 10;
}
#Test
public void print() {
System.out.println(i);
}
}
This before method will be executed before print and i will be Initialized.

Calling static variable from another static variable constructor

In my Android application I have to initialize a lot of static Objects before the first Activity starts. From what I know, static variables are initialized when classes are loaded. So, with time the amount of static objects in project began to grow and now I'm getting NullPointerExceptions. In my case static objects may call other static objects in their constructors. So my question is: could some static variables be initialized before variables they depend on and thus cause NullPointersExceptions? Is that possible?
Code example :
private static class HardwareManagersHolder implements HardwareManagers, IManagers {
private final AtomicBoolean senderAcquire = new AtomicBoolean(false);
private final AtomicInteger receiverAcquire = new AtomicInteger(0);
public IAudioManager audioManager;
public IVideoManager videoManager;
public IVibrationManager vibrationManager;
public IBatteryHelper batteryHelper;
#Override
public void configureManager() {
audioManager = AudioHelper.getInstance();
vibrationManager = VibrationManager.getInstance();
videoManager = VideoManager.getInstance();
batteryHelper = BatteryHelper.getInstance();
}
And an Object Holder:
public class VideoManager implements IVideoManager {
private static class VideoManagerHolder {
public static final VideoManager VIDEO_MANAGER_INSTANCE = new VideoManager();
}
public static VideoManager getInstance() {
return VideoManagerHolder.VIDEO_MANAGER_INSTANCE;
}
}
I tried to reconstruct your exception with the snippets you provided. I used the following code:
public interface IVideoManager {}
public class VideoManager implements IVideoManager {
private static class HardwareManagersHolder {
public IVideoManager videoManager;
public void configureManager() {
videoManager = VideoManager.getInstance();
}
}
private static class VideoManagerHolder {
public static final VideoManager VIDEO_MANAGER_INSTANCE = new VideoManager();
}
public static VideoManager getInstance() {
return VideoManagerHolder.VIDEO_MANAGER_INSTANCE;
}
public static void main(String[] arg) {
System.out.println("Start test");
HardwareManagersHolder h = new HardwareManagersHolder();
h.configureManager();
if (h.videoManager == null) {
System.out.println("VideoManager is null");
}
System.out.println("Test finished");
}
}
This code works on my machine. If this code is not working on yours, there is some other fault.
Are you initializing them in a static constructor? They would get called first for precisely this reason.
static
{
VIDEO_MANAGER_INSTANCE = new VideoManager();
}

java multithreaded lazily initialized singleton which approach?

Are both the below approaches for lazy-initializing thread-safe singleton in java correct? Is there any performance difference? If not then why do we use the Holder pattern(Singleton2) instead of keeping it simple as in Singleton1 ?
Thanks in advance.
class Singleton1 {
private Singleton1() {
System.out.println("Singleton1-Constructor");
}
private static final Singleton1 inst1 = new Singleton1();
public static Singleton1 getInst1() {
return inst1;
}
}
class Singleton2 {
private Singleton2() {
System.out.println("Singleton2-Constructor");
}
public static class Holder {
private static final Singleton2 holderInst = new Singleton2();
}
public static Singleton2 getInst2() {
return Holder.holderInst;
}
}
public class App {
public static void main(String[] args) {
Singleton1.getInst1(); // without this statement the Singleton1 constructor doesnt get called.
Singleton2.getInst2(); // without this statement the Singleton2 constructor doesnt get called.
}
}
Singleton1 is not truly lazy, since if you add any other method to Singleton1 and call it from the main class, then the static inst1 will be initialized.
Try this:
public class Singleton1 {
private Singleton1() {
System.out.println("Singleton1-Constructor");
}
private static final Singleton1 inst1 = new Singleton1();
public static Singleton1 getInst1() {
return inst1;
}
public static void foo() {
}
}
public class Singleton2 {
private Singleton2() {
System.out.println("Singleton2-Constructor");
}
public static class Holder {
private static final Singleton2 holderInst = new Singleton2();
}
public static Singleton2 getInst2() {
return Singleton2.Holder.holderInst;
}
public static void bar() {
}
}
public class LazyInitializationApp {
public static void main(String[] args) {
Singleton1.foo();
Singleton2.bar();
}
}
Now running the app will print:
Singleton1-Constructor
But it will not print Singleton2-Constructor, because it is truly lazy.

How to refactor a class with multiple Lists + getters and setters for each list

I have the following class:
public class RefactorMe {
private static List<Event<Apple>> mAppleEventList = new ArrayList<Event<Apple>>();
private static List<Event<Banana>> mBananaEventList = new ArrayList<Event<Banana>>();
private static List<Event<Orange>> mOrangeEventList = new ArrayList<Event<Orange>>();
public static List<Event<Apple>> getAppleList() {
return mAppleEventList;
}
public static List<Event<Banana>> getBananaEventList() {
return mBananaEventList;
}
public static List<Event<Orange> getOrangeList() {
return mOrangeEventList;
}
public static void addAppleEvent(Event<Apple> pEvent) {
mAppleEventList.add(pEvent);
}
public static void addBananaEvent(Event<Banana> pEvent) {
mBananaEventList.add(pEvent);
}
public static void addOrangeEvent(Event<Orange> pEvent) {
mOrangeEventList.add(pEvent);
}
}
I tried refactoring it using the Visitor pattern but could not get it to work because of the generics.. Is there a better way to do this?
Following on #user902383 by using the Map here is a solution for you in Java 7:
public class RefactorMe {
class Event<K> {
public K getNewObject() {
return null;
}
}
private static Map<Class<?>, List<Event<?>>> eventLists = new HashMap<>();
public static <E> List<Event<E>> getEventList(Class<E> clazz) {
return (List) eventLists.get(clazz);
}
public static <E extends Event<E>> void addEvent(Event<E> pEvent) {
Class<E> key = (Class<E>) pEvent.getNewObject().getClass();
List<Event<?>> events = eventLists.get(key);
if (events == null) {
events = new ArrayList<>();
eventLists.put(key, events);
}
events.add(pEvent);
}
}

Android send broadcast via interface

I want to share some data between class with interface
I developed some codes like this :
public interface Transmission
{
public void onBroadcastReceived(String key, String value);
}
public class Events implements Transmission
{
protected static Events instance;
public static Events getInstance()
{
if(instance == null)
{
instance = new Events();
}
return instance;
}
public void addBroadcast(String key, string value)
{
onBroadcastReceived(key, value);
}
#override
public void onBroadcastReceived(String key, String value)
{
}
}
public class A
{
public A()
{
Events.getInstance().addBroadcast("Hello", "say hello");
}
}
public class B implements Transmission
{
#override
public void onBroadcastReceived(String key, String value)
{
Log.d(key,value);
}
}
B b = new B();
A a = new A();
I am trying to transfer some data with interface , is this possible ?
Is this solution true ?
Will be log key and value in B class ?
Please advise
You need to make the following changes to get it work.
public interface Transmission
{
public void onBroadcastReceived(String key, String value);
}
public class Events {
protected static Events instance;
public static Events getInstance()
{
if(instance == null)
{
instance = new Events();
}
return instance;
}
public void addBroadcast(String key, string value,Transmission recever)
{
recever.onBroadcastReceived(key, value);
}
}
public class A
{
public A()
{
B b = new B();
Events.getInstance().addBroadcast("Hello", "say hello",b);
}
}
public class B implements Transmission
{
#override
public void onBroadcastReceived(String key, String value)
{
Log.d(key,value);
}
}
A a = new A();

Categories

Resources