Hey guys I have a class called UserData consisting of static fields, which is as follows:
public class UserData {
private static JSONObject fbProfilePicture;
private static boolean loggedOut=false;
private static Integer commonFriendID;
private static Integer userID1;
private static Integer UserID2;
private static JSONObject stolenTrio=null;
}
Actually the class contains alot more fields but I decided to show you a small version of my class.
In my app, I've a feature to delete account and create a new one, when I choose to do that, my app goes back to the sign up process, but there's a problem, I want to clear all fields of that class after deleting user.
How can I do that?
If you think you need a static / singleton kind of instance of UserData, I suggest doing it like this:
public class UserDataSingleton {
public static UserData userdata;
}
and make your UserData a simple Pojo with non-static fields.
This way you can reset your data with
UserDataSingleton.userData = new UserData()
Create a method that reset your values. You might want later to do more things into that method. Ex inform a listener that your object has been cleared.
Related
I have studied data hiding in java theoretically but don't know what is happening inside. Every tutorial, states that unauthorized persons cant access the data of others.
Can anyone please give an example of what will happen without and with data hiding with two or three users programmatically?
Data Hiding is hiding internal data from outside users. This is achieved by making the attributes of your class private and not letting the objects of the class access it directly, instead we create getters and setters to access the private attributes.
Example:
//Without Data Hiding
public class Model{
public String name;
}
public class JavaApp{
public static void main(String args[]){
Model mObj = new Model();
mObj.name="abc"; // name = "abc"
}
}
//With Data Hiding
public class Model{
private String name; //private name
}
public class JavaApp{
public static void main(String args[]){
Model mObj = new Model();
mObj.name="abc"; // Error
}
}
I remember a couple years ago I was using static initializers to call class-level setup operations. I remember it having very bizarre behaviors and I just decided to steer clear from them. Maybe it was because I was messing up the top-bottom order or being a newbie. But I am encountering a need to revisit them and I want to make sure there is not a better way that is just as concise.
I know it is not fashionable, but I often have data-driven classes that maintain a static list of instances imported from a database.
public class StratBand {
private static volatile ImmutableList<StratBand> stratBands = importFromDb();
private final int minRange;
private final int maxRange;
private static ImmutableList<StratBand> importFromDb() {
//construct list from database here
}
//constructors, methods, etc
}
When I have dozens of table-driven classes like this one, this pattern is very concise (yes I know it tightly couples the class with one source of data/instances).
However, when I discovered the goodness of Google Guava I want to use the EventBus to update the static list when a certain event posted. I would create a static final boolean variable just to call a static method that initialized the registration.
public class StratBand {
private static volatile ImmutableList<StratBand> stratBands = importFromDb();
private static final boolean subscribed = subscribe();
private final int minRange;
private final int maxRange;
private static ImmutableList<StratBand> importFromDb() {
//construct list from database here
}
//constructors, methods, etc
private static boolean subscribe() {
MyEventBus.get().register(new Object() {
#Subscribe
public void refresh(ParameterRefreshEvent e) {
stratBands = importFromDb();
}
});
return true;
}
}
This got annoying very quickly, because the compiler would throw warnings over the subscribed variable never being used. Also, it just added clutter. So I'm wondering if it is kosher to use the static initializer, and there really is no better way if I do not decouple this into two or more classes. Thoughts?
public class StratBand {
private static volatile ImmutableList<StratBand> stratBands = importFromDb();
static {
MyEventBus.get().register(new Object() {
#Subscribe
public void refresh(ParameterRefreshEvent e) {
stratBands = importFromDb();
}
});
}
private final int minRange;
private final int maxRange;
private static ImmutableList<StratBand> importFromDb() {
//construct list from database here
}
//constructors, methods, etc
}
So I'm wondering if it is kosher to use the static initializer
The funny thing is that
private static final boolean subscribed = subscribe();
and
private static final boolean subscribed;
static {
subscribed = subscribe();
}
get compiled to exactly the same bytecode. So using the needless static variable is strictly worse.
But until we are ready to scale up to a DI-driven framework,
Discover Guice. Don't call it framework (though it is). It's easy to use and let's you get rid of static.
Or do it manually. Rewrite your class by dropping all static modifiers and pass it everywhere you need it. It's rather verbose sometimes, but stating dependencies explicitly allows you to test classes in isolation.
The way it is, you can't test StratBand without hitting the database, no matter how trivial the method under test is. The problem is the coupling of every StratBand instance to the list of all StratBands.
Moreover, you can't test the behavior dependent on the stratBands contents as it always get loaded from the DB (sure, you can fill your DB correspondingly, but it's a big pain).
For starters, I'd create StratBandManager (or StratBands or whatever name you like) and move all the static functionality to it. In order to easy the transition, I'd create a temporary class with static helpers like
private static StratBandManager stratBandManager = new StratBandManager();
public static ImmutableList<StratBand> stratBands() {
return stratBandManager.stratBands();
}
Then deprecate it all and replace it by DI (using Guice or doing it manually).
I find Guice useful even for small projects. The overhead is tiny as often there's no or hardly any configuration.
In C# I can assign the name of a class to a local static variable like this.
public class MyClass
{
private static string TAG = typeof(MyClass).Name;
}
I've found this very useful, because the value of the string automatically updated if the class is refactored to another name. Handy for tagging debug messages and such.
Is something like this possible in Java?
public class MyClass
{
private static String TAG = ????;
}
I know I could use getClass().getName() but that requires a reference to an object. Is there a way to do this on a static variable?
You don't need to assign the name of a class to field instead of writing.
MyClass.TAG
you can write
MyClass.class.getName();
If you really need to you can assign this to TAG but I don't see the point.
A trick is also available that does not require programmer's knowledge of the class name beforehand:
public class MyClass
{
private static String TAG =
new Object() { }.getClass().getEnclosingClass().getName();
}
This trick uses a nested anonymous Object subclass to get hold of the execution context. It has a benefit of being copy/paste safe in case of cloning your code across different classes...
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;
}
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.