I'm working in a application which has many activities and most of the activities share more than one objects, So I created MyApplication class by extending android Application class to store selected objects to share. But I feel quit uncomfortable while accessing those objects inside provider/helper classes b'coz context is needed in providers to get instance of Application.
So I planned to create static class called SelectionProvider inside MyApplication class to store selected objects, then I can access those in static way without create instance to MyApplication.
MyApplication class with static inner class as follows
class MyApplication extends Application {
public static final String TAG = "MyApplication";
public static class SelectionProvider {
private static UserObj userObj;
private static TownObj townObj;
private static StoreObj storeObj;
public static UserObj getUserObj() {
return userObj;
}
public static setUserObj(UserObj userObj) {
this.userObj = userObj;
}
public static TownObj getTownObj() {
return townObj;
}
public static setTownObj(TownObj townObj) {
this.townObj = townObj;
}
public static StoreObj getStoreObj() {
return storeObj;
}
public static setStoreObj() {
this.storeObj = storeObj;
}
}
}
Is it right approach? if not why?
Will reside the selected objects (which are stored in inner class) in entire application life or will it destroyed anywhere?
This method or a static value elsewhere should work fine and last for the lifetime of the application as long as you don't have multiple processes running that need access to this object. If that's the case, you should use a Service to handle transactions.
I would not design it as an inner class. I would create SelectionProvider (and any other classes you need) as its own separate class, and instantiate it in your MyApplication class' onCreate method.
You should not instantiate the application object as it can be accessed at any time by calling getApplication() and casting it to your application class (e.g. (MyApplication)getApplication(); Then you can access any objects created by the class.
If data persistence is an issue with these classes, consider storing their values in SQLLite or as a Shared Preference, as Android may terminate your application at any time when it is in the background if it needs the resources.
I would create a singleton class of my own:
public class Data {
/* Start of singleton block */
private static Data data = new Data();
private Data(){
}
public static Data getInstance(){
}
/* End of singleton block */
private SelectionProvider selectionProvider;
public SelectionProvider getSelectionProvider(){
return selectionProvider;
}
/* other necessary methods (get, set) and classes below */
}
This way you can access your objects with Data.getInstance().getSelectionProvider().
This will be available during an active application, though you might want to build in some persistant storing of your data for when the user leaves the app for some time to come back later:
public SelectionProvider getSelectionProvider(){
if(selectionProvider == null)
selectionProvider = readSelectionProviderFromPersistantStorage();
return selectionProvider;
}
Related
i have an activity say A that is extended by many other activities , i have a variable in activity A which is used by all other sub activities(classes) extending it. I want to know if i can set a value for that variable from a sub-activity such that the change will reflect in all the other subclasses extending Activity A.
i know its a basic question ,i am new to this any help is appreciated.
eg:
Activity A has
public String global = "ABC"
Activity B extent A
display(global); ---> ABC
Activity C extent A
display(global); ---> ABC
Activity D extent A
display(global); ---> ABC
now how can i change global in Activity D such that Activity B and C should also be affected.
Seems like you want a variable whos value persists and remains same throughout.
But since you only want to your inherited classes to be able to update or read the variable, you can do something like this:
class A
{
private static int your_var = 0;
public int get()
{
return your_var;
}
public void set(int a)
{
your_var = a;
}
}
class B extends A
{
}
class C extends A
{
}
In your static void main:
new B().set(101);
new C().get() // this will return value 101.
Note: Here only one copy of variable your_var is created. And since it is private, only the non static getter setter methods will be able to read or modify it. Thus making it accessible only by either the containing class itself or the child class objects.
You need to create a static variable in Activity A.
A static variable is a variable of the class and not of the objects.
You can have a singleton class which can hold global data and when need you can fetch the data from the single commonly shared instance of the singleton class. But there is another better way.
You need a class which sits on top of your activities. In any app we usually do have one such class (may be some Initilizer or main or manager class ) which wires the entities and initiates our application.
In android we have Application class which can hold global data. For reference see Android global variable
try the following:
in class A
public static String global = "ABC";
in class B
public class B extends A {
public static void main(String[] args) {
B b = new B();
A a = new A();
System.out.println(b.global);
System.out.println(a.global);
System.out.println(global);
}
}
alternatively you could try to work with encapsulation: mark the string as private and make the "global" string available through getters and setters. This is often a more flexible solution then working with static variables
http://www.tutorialspoint.com/java/java_encapsulation.htm
So I have a concrete class and an abstract class and I am trying to access methods from the concrete class from the abstract one. Store currently contains many getters that the member class needs. Currently get null pointer exception.
public abstract class members{
// Trying to refrence the store object
Store store;
public void someMethod(){
// I want to be able to access all the methods from the store class
// eg
store.showVideoCollection();
}
}
public class store {
// This class has already been instantiated, just one object for it.
public void showVideoCollection(){
// Stuff here
}
public void otherMethod(){
// Stuff here
}
}
EDIT:
In the main method
public class start {
public start() {
store = new Store(); // Don't want to create more than 1 store object.
}
Thanks
In order to store a Store instance you must instantiate it. As is, you declare the variable store but you never initialize it (so it's null). I think you wanted something like
// Trying to refrence the store object
Store store = new Store(); // <-- create a Store and assign it to store.
Alternatively, you could make Store a Singleton. The linked Wikipedia page says (in part) the singleton pattern is a design pattern that restricts the instantiation of a class to one object.
public final class Store {
public static Store getInstance() {
return _instance;
}
private static final Store _instance = new Store();
private Store() {
}
public void showVideoCollection(){
// Stuff here
}
public void otherMethod(){
// Stuff here
}
}
I want to avoid code duplication in next situation: I have two classes NewTx and GetTx, first represents new transaction, second represent a transaction, that joins current. The goal is to make CRUD code as compact as possible, so classes are usually used as:
List<Users> users = NewTx.loadList("select u from User u");
Student s = GetTx.find(Student.class, '02d7c3fe-e9cf-11e4-8ceb-c7b1b9baf140');
These classes actually differ only in a way they obtain a transaction, but all their methods are static, so it seems impossible to move logic to parent class.
Now I have
public final class NewTx extends Tx {
public static <T> List<T> loadList(String query) {
return tx().call(Tx.<T>getLoadListCallable(query));
}
static Transaction tx() {
return DataSource.createTransaction();
}
As I said before, only tx() method is different for NewTx and GetTx classes, other methods just obtain transaction and than delegate job to parent Tx class.
So the goal is to move all CRUD methods like loadList to parent class Tx.
Restriction: method calls must look like before: NewTx.load(..., not NewTx.get().load(..
Any ideas?
Your goal isn't going to happen with the current restrictions you've given. If you were willing to change the method calls, there are multiple ways, but moving common static calls into a shared class doesn't work because static methods can't be inherited in java, only shadowed. Consider the following:
public static class StaticParent
{
public static void commonMethod(){
System.out.println(getOutput());
}
public static String getOutput(){
return "Parent";
}
}
public static class StaticChildA extends StaticParent
{
public static String getOutput(){
return "ChildA";
}
}
public static class StaticChildB extends StaticParent
{
public static String getOutput(){
return "ChildB";
}
}
StaticChildA.commonMethod() and StaticChildB.commonMethod() will both print "Parent" because commonMethod is being shadowed and has no way of knowing that the calling code was from StaticChildA or StaticChildB. If we print the stack trace inside commonMethod, we see the following from both calls:
testpackage.UnitTester$StaticParent.commonMethod(UnitTester.java:4497)
testpackage.UnitTester.main(UnitTester.java:4526)
With no this or difference in the stack, there's no way to even branch inside the code manually to pick an implementation of your tx().
i have my DTO class that is :
public class EmailResponse {
// Make public to avoid getters and setters
public Email email;
public RequestData reqData;
public EmailResponse() {
super();
}
}
and i want to implement to it this interface:
public interface IAssertionErrorDo {
public void onErrorDo();
}
but i want to do it during execution, i don't want to touch "EmailResponse" because it would not be ok to make it implements that interface due they don't belong to the same layer, i mean, EmailResponse would belong to service layer and IAssertionError would belong to test layer. I am using TestNG.
Do you know how i could do this? Regards
EDIT:
My implementation is this:
EmailResponse emailResponse = emailService.getUserEmail(userId);
And the reason i want to do this "injection" is because i have
public class LoggingAssert
extends Assertion {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggingAssert.class);
private IAssertionErrorDo dataE;
#Override
public void onAssertFailure(IAssert a, AssertionError ex) {
LOGGER.info("[ERROR] " + a.getMessage());
if (this.dataE != null) {
this.dataE.onErrorDo();
}
}
public LoggingAssert setOnErrorDo(IAssertionErrorDo object) {
this.object = object;
return this;
}
}
loggingAssert.setOnErrorDo(emailResponse).assertNotNull(emailResponse.getEmail().getId(),
"Checking created email doesn't exists");
So i want to if assert fails execute method onErrorDo() from emailResponse
You could do
public class MyEmailResponse extends EmailResponse implements IAssertionErrorDo {
...
}
implementation calls in interfaces, you can call more than 1 interface if you want by adding commas to separate them..
to call interface methods you simply just use the method's name.
like this:
public class MyEmailResponse implements IAssertionErrorDo
{
public void onErrorDo() {//define it's behavior}
}
if you extend a class you use:
super.MyMethod()
to call the a method inside the extended class, but if you already have an extended class and want a method from another class you have to create an object for that class first then call it, thus:
MyClass mc = new MyClass();
if it is in a different package then
myPackage.MyClass mc = new myPackage.MyClass();
then you call your method from that class using the object you created, which is in this case mc.. so:
mc.MyMethod();
if you want it to return a variable then you will need to add a return statement in that method with the variable you want it to return.
interfaces are usually used for global an changing environments (dynamics), for example if you developed a program and it needs a driver to connect to databases then you will make an interface and send it to the database developers, and each one will fill the codes in that interface and send it back... this guarantees consistency.
when you implement an interface you have to define every method inside it (even if you leave it empty) and you cannot change the interface's methods names nor add... it is used in other areas as well, i don't think you need to use it in your case.
OK, I'm not super new to java but for some odd reason I can't figure out why this is not working for me. Basically I have 3 classes in my applet.
My main, my string constructor, and my data class.
The main class calls the string constructor, the string constructor stores its final product into the data class. Last, I'm trying to access the data class using my Main class.
The returned value to the main is always null and I can't figure out why. My suspicion is I'm somehow creating 2 separate data class objects but Ive looked at examples of code and it all seems correct. Here are the classes..
main.
public class LaneGUI extends javax.swing.JApplet {
private laneData laneData;
Timer timer;
/** Initializes the applet LaneGUI */
public void init() {
laneData = new laneData();
xmlParser.parseInputString(connection.getFinalXMLString());
System.out.println(laneData.getLaneID());
string contructor...
public class XMLParser {
private laneData laneData;
public void parseInputString(String input){
try{
/*some xmlparsing*/
laneData = new laneData();
laneData.setLaneID(string);
data class
public class laneData {
private String laneID;
public String getLaneID() {
return laneID;
}
public void setLaneID(String laneID) {
this.laneID = laneID;
}
}
There is a lot of editing here, like in the string class I took out all of the xml parsing and string editing.
Basically, when i check the getLaneID after i set it in the string constructor the value is correct. But when i call a get from the main, its null.
XMLParser and LaneGUI are referring to two different instances of laneData.
Instead of your final line in LaneGUI, which says this:
System.out.println(laneData.getLaneID());
You need something like this:
System.out.println(xmlParser.getLaneData().getLaneID());
You'll also, of couse, need to add a getLaneData() to XMLParser that returns it's laneData instance (or a deep copy thereof.)
As you rightly speculated, you have two different instances of laneData. The XMLParser class has a local instance of laneData different from the instance referenced by LaneGUI.