how to create appliaction variable and session variable in java android? - java

In my project I am to provide some functions which can be provided using session and application variable like in c#.
MY information is confidential so can not be stored in files like xml
Thanks in advance.
Edit : 1-
Solution for session variable i've found called sharedpreference but don't know how to use please tell me
how to initiallize it and
set it from other class and
get the value from some other?
?...?...?..

First of all, your application can basically die at any time, because it can be killed off by the Android scheduler after your app sits in the background for a while and the platform needs more memory.
That being said, storing your data in a global Application class is generally considered a bit hacky. Instead, the way you use this depends on how you are going to access the application. It's a pretty commonly accepted thing that a lot of apps keep things like their OAuth tokens in SharedPreferences (though I'm not sure exactly how kosher this is). What you might do is keep your session variable in an Application class, and then -- whenever the app dies -- simply reauthenticate. This is probably good practice anyway, as after that long someone may have picked up the phone, etc...
However, you seem to be under the impression that SharedPreferences can be read by anyone. This is incorrect, see this. Now, if you have a rooted phone, sure, then there's a way around that, but this is always going to be an issue, on a rooted phone you should basically consider that you don't really have any security at all...

Application class is there for you. use it and save your application level data, like this:
public class WhatEverApp extends Application
{
String mApplicationLevelVar = "Hello";
}
WhatEverApp will be the name of your app used in manifest.xml
Look here for detailed discussion on Application class.

Related

Where to store complex data in the navigation-based application

I have an app that has a lot of data that I need between the pages, such as:
design settings, user parameters, scanner access, printer queue, multiple things that got calculated and formed on one page and will be used on the others.
The general idea of the app is: you quickly select options or input data on each page and then it forms an order, sends it and prints it.
I have several repositories for different things but I can't get how to give access to them from the destination-fragments.
I'm pretty new to Android so I'm trying to find the best way to build this system but failing to do so.
What I found so far:
Room - I don't think so. I honestly tried it for several weeks but loading and saving data is unbearably slow especially when it's just a bunch of menu-pages flipping one after another. Also, I don't need to save data locally between the sessions, so it kind of misses the point of the local database.
Send some simple strings/numbers between the fragments - serialization/deserialization of everything I need for each menu doesn't sound great.
ViewModel factory - this way you need to create and store the ViewFactory somewhere and then access it from each fragment and then build a new ViewModel with it. Kind of might work but looks weird. How should it work? We have a link to the Factory in the "main" ViewModel and then get a link to this "main" app's VM, read the factory and then init local fragment's VM?
One big application's ViewModel - doesn't sound right: too big, too bulky.
Singleton(s) - that's just sad.
Dependency injection - I didn't try Dagger yet (going to, right now). Is it the thing I'm looking for?
I tried to google a lot on this topic but all of the answers look like: "here's how to pass a simple string between the screens", how do people organize the more complex applications? Maybe there's a more sophisticated way to split the application state into some kind of services or other terms that I'm missing.
Could you please help me to understand the proper application architecture in terms of state and data?
I think that your solution is something between a session implementation (in memory or using Room) and a ViewModel for the parts where a screen depends on another. If it is a flow I recommend you to use a way to share the ViewModel between the fragments like this or this (which I use and recommend) and then setting it as a state for the rest of the flow, leading to shared data that survives some config changes. If you need the settings surviving throughout the app execution you should implement a session using a simple class singleton or a Room implementation.

Is this a good reason to use a Singleton?

I'm making an Android app that will have the timetables of a local bus.
There are more than one timetable, the one that will be use depends on the day.
If it's a holiday I must use a special timetable, so I want to know when is a holiday and when is not.
The thing is that I'm creating a class that will handle this, it will try to retrieve information from memory or from a web api. Then some other classes will be able to communicate with this class, but it doesn't seem necessary to me to have more than one instance of this class, I could create just one instance and share it with the rest of the classes.
Could this class be a Singleton or it would be better if I create a normal class ?
In your case (retrieving info from memory), definitely avoid using a singleton class because it will highly likely be tied to your Activity context.
Your class will have a static reference to a class, therefore
it will be kept in memory when not needed.
singleton may be reinstantiated, or may use obsolete instance, with new instations of activities. You will lose control of the current variables.
diffent instances of the same activity class are highly likely to conflict with this class.
Examples of the same activity class several instantiation:
Change device orientation.
Running app from the webbrowser's, Google Play, file browser intent.
Besides, at some point, when you add functionality based on user reviews, your app will grow, you are likely want to refactor your class, break it into subclasses, put some of its methods into separate threads. It will no longer be easy to do.
It might seem fun while the app is small, and untested, but later, in Android specifically, you will run into a nightmite with unpredictable and hard to detect errors.
Because of Android's special way to recreate activity class, through onCreate, onResume etc. you will run into a nightmare, when the app will start living its own life.
You will no longer be able to rely on the assumption that the current singleton instantiation actually belongs to your current activity.
You may swap between orientations or run your app from different entry points (launcher, recent apps, google play), and it may reuse the variables actually prepared for a different activity instantiation.
If you need only one instance of the class, just create one instance of the class in the onCreate method - and that will make the app much more manageable.
One of the main advantages a Singleton class brings you is the fact that you are sure to have one and only one instance of an object doing some thing, and that it is instantiated only once (preferably at a specific point of your application, for instance at startup or only after certain other operations have been performed)
An example could be for instance a cache implementation: you want to make sure that all classes that need a certain cache read and write from the same object, that maybe is created and filled with information at startup time.
Your does not seem to be the case, unless you fetch the information you need when your application starts and then you keep them memorized for some reason: in this case you want to make sure your information is fetched one and only one time, to avoid wasting memory and elaboration time. Also, a Singleton is fine if you need to do some kind of operation when your class is instantiated, like opening a connection that then stays open.
On the other hand, if you just need a class with some method to call some external apis or database and you don't need to memorize any information in it, there is no reason to initialize a singleton.
If this is your case, why don't you try some static class/methods? They can be called like normal methods directly on the class with no need to instantiate objects or keeping a state, saving memory and avoiding side effects.

Java : Using static variable to store Application Specifc Data inside a web based Application

I am working on a existing web based application which uses static map to store data specific to the Application .
This is my code below which is responsible to store Data inside a ConcurrentHashMap as shown below .
public class MyClass
// Class variable
private static Map<String, UserThread> usermap = new ConcurrentHashMap<String, UserThread>();
// Inside a Method
public void userData()
{
UserThread userThread= usermap.get(getLoginId());
if (userThread == null) {
userThread = new UserThread();
userThread.start();
usermap.put(getLoginId(), userThread);
}
}
The application is working fine , here my question is that , is this a valid code because can we store Data inside a static variable ?? (Here the Static ConcurrentHashMap contains data specific to the Application )
Static variables and caches of any kind should be avoided, especially in multi-threaded environments such as web-applications. There are several problems with your code:
Do you remove UserThreads from the map? How do you know when they should be removed? What if client's browser crashes? If you don't remove them you are asking for out-of-memory errors after the application is running for some time.
Using ConcurrentHashMap in the way you use it is not thread-safe, because it's possible that another thread adds a UserThread between if (userThread == null) and usermap.put(getLoginId(), userThread); . Concurent version of HashMap doesn't magically solve all problems with thread-safety as it may seem.
Spawning your own threads in a servlet container is not a good idea. There are better ways to do background tasks, but first you need to say what the thread is trying to do.
Generally using any kind of such static caches is bad idea, in any kind of application. In your case it would be much better to keep application-specific data in user's session.
With static map, you would run into the risk of memory leak unless you are sure of the life cycle of each entry added to the map, i.e. who would be adding them, how long will the entries stay there and when will they be removed so that they can be claimed during GC. Otherwise, your application will use up the memory and will start throwing OOME.
In this case, user which will log in on one machine will have the same session as on the second machine. I bet it's not a good way to do.
I had asked some time ago about Semi static field in Java application and Alessandro Santini gave me very nice solution with ThreadLocal. Check this out.
AFAIK it is according to the specification not ok to start your own thread inside a container. You are supposed to use a WorkManager for this. But the only server I know of that actually is enforcing that rule is Websphere Application server.
a static variable in principle is ok, of course if you run in an clustered environment each server will have its own instance of the static variable. This might or might not be a problem.
So technically you might be fine.
On the other hand I am really curious what you are trying to achieve with all these threads. If you start one thread per user this is an excellent attack vector for DOS attacks. I also have no idea why you would want to do something like this.

Android Programming and Java syntax

This is a question regarding the syntax used in Eclipse SDK while programming some JAVA code for an Android App.
I am an embedded microcontroller engineer that's mainly used to programming in Assembler (a long time ago) and C. I am a newbie when it comes C++ and JAVA and to help me write my code I have been using a mix of the developer.android.com for background info and stackoverflow.com for real world examples and have found them very useful.
So, I have no problem writing code to do what I want to do because I've always done it, but I am finding it very difficult getting my head around the syntax used in writing Android Apps.
For example to access the GPS one of my lines of code read thus:
LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
but can be shortened to this:
LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
I prefer the second version, but why were some examples written like the first example? Both seem to work fine. I've seen other examples that look even more complicated using "Class".
Secondly, is this not a complicated way to do a really simple thing:
Toast.makeText(getBaseContext(),"Hello World",Toast.LENGTH_SHORT).show();
Why not:
Toast("Hello world");
It now takes me four times as long as it use to write code.
The line break after the cast there is just to keep the lines from getting too long.
On this:
Toast.makeText(getBaseContext(),"Hello World",Toast.LENGTH_SHORT).show();
... it would be simple to write it as you say, aexcept that doesn't do the same things. Basically, that line is
Finding the outermost enclosing place to put graphics
Setting the text you want to show, and setting some formatting or some such
and then showing it.
You want to split those up because you don't always write to the outermost world, and you may want to, for example, make several different chunks of text and show90 or hide() them later. (Think an error message and a success message, for example. You like to build them once and then show/hide the ones you don't need.)
Now, if you can define what context you want and never want to mess with the visibillty, you can make a function that does just that.
It is kind of beginner OOP-ish style to put this everywhere. It is implied in your second example, and the second example is the more common style.
Now this one has to do with a bit of engineering. Yes, your second short example could have been implemented (except that Toast is a class, not a function, but a similar thing would work), but it would preclude a lot of important things you may want to do. A Toast may not be all that lightweight of an object; you may want to cache it. That's why you first get an instance with makeText and only then call show on it. The Toast instance will also have a complete lifecycle that you need to control, but won't be able to with your simple example. The instance can probably undergo further configuration, etc. etc. In short, there's a reason for it which is not obvious from a Hello, world piece of code.
Welcome to the world of Android and Java programming. Since you come from an assembly language background, my advice is: Get used to more typing. :)
Regarding the first code fragment: First, the qualifier this. on the call to getSystemService() is redundant; you can just drop it. Secondly, you can eliminate the qualifier on LOCATION_SERVICE by statically importing the name. Add something like this to the imports for the compilation unit:
import static android.content.Context.LOCATION_SERVICE;
or, if you don't mind the namespace pollution:
import static android.content.Context.*;
Regarding the second fragment: for architectural reasons, Toast eventually needs to associate the popup window to some application context. The first argument to the factory method makeToast is what makes this possible. (By the way, you just need getContext(), not getBaseContext(). You could also stash the context in a field.) As far as the third argument to makeText—arguably, a version of the factory method could have been provided that has a default display time, but Android doesn't provide that, so you're stuck with the third argument as well. You can again avoid the qualifier by statically importing LENGTH_SHORT. Finally, the factory method just returns a Toast object. You aren't required to show() it just yet; it could be stashed and shown at a future time. It's good design to separate creating the Toast object from the action of putting it on the screen.
I will try to explain the things in the easiest way and to the best of my ability.
1. ".this" refers to the current object in Java. ".this" specifically points to the current object accessing its own instance variable members of that class.
2. Using "this" is just being more specific.
3. Now in the case of Toast, It requires the "context" parameter to point to the Activity
where it will display the Toast.(ie on which activity)
4. You can use "this" if you are not inside an Anonymous class, or if you are in an Anonymouse class then use "Your_Activity_Name.this" in place of context.
5. getBaseContext, getApplicationContext are like global access to the parts of the Application.
6. I always prefer Your_Activity_Name.this in context place. Context means the Activity, on which the Toast is going to be displayed. And yes there is No Toast(String s) method in activity.

Is a "master preferences" class a good idea?

I have a class that manages user preferences for a large software project. Any class in the project that may need to set or retrieve a user preference from a persistent store is to call the static methods on this class. This centralized management allows the preferences to be completely wiped programmatically - which would be impossible if each pref was handled close to its use code, sprinkled throughout the project.
I ran into another implication of the centralization design in the course of this. The software has a public API. That API can be provided by itself in a jar. Classes in that API might refer to the pref management class. So, the pref manager has to go in the API jar.
Each preference might have a default value. Upon software startup, that default might be computed. The algorithm depends on the preference, and thus tends to reside near the use code. So if the pref manager needs to come up with a default, it calls the class in question.
But now that pref manager has become an "octopus class", sucking in all sorts of classes into the API jar that shouldn't be there. If it doesn't, then programs using the API jar quickly run into ClassDef exceptions. If it does, then the API jar is now bloated, as each of those other classes may refer to still others.
In general, do other Java programmers manage their preferences with a centralized class?
Does it make sense to distribute that static pref management class as part of a public API?
Should that pref manager be the keeper of the code for determining defaults?
IMHO, I think that the answer to your first question is "yes" and "no".
Preferences are commonly handled as a centralized class, in the sense that the class is a "sink" for many classes in the project. Trying to do it closer to the calling code means that if the same preference is later useful elsewhere, you are in trouble. In my experience, trying to put the preferences "too close" also results in a very inconsistent handling.
That being said, it is often preferable to use multiple preference classes or "preference set", each supporting a module or submodule. If you look at the main components of your architecture, you will often find that the set of preferences can be logically partitioned. This reduces the mess in each preference class. More importantly, it will allow you to split your program into multiple jars in the future. Now, the "default value" calculators can be placed in the module but still in a global enough area.
I would also suggest not setting preferences directly as static methods, but rather using some getInstance() like operation to obtain a shared instance of the preferences manage, and then operating on it. Depending on your semantics, you may want to lock that object for a while (e.g., while the user is editing preferences in a UI) and this is easier if you have an actual object.
For your other questions, I would say that your public API should have a way of letting users change preferences, but only if you can document well enough what the results of these changes could be.
If you use a single API function to get the "reference manager", you can give users the possibility of providing their own "default values calculator". The preference manager will ask this calculator first before resorting to the one you have provided by default.
Can't you just handle preferences in a really generic way? You'd then just use the preference manager to handle the persistence. So from a class you'd just say to the preference manager PreferenceManager.setPreference(key, value) and it doesn't care what it's saving in terms of the semantics of the data.
Or am I simplifying this too much?
I'm no Java Dev, but as far as the whole "octopus class" thing goes, can you not just supply an interface to the jar and connect the calls between the interface and the prefs manager at runtime, using the application configuration file to determine the prefs manager to instantiate?
Something like the .NET provider pattern?
That way you can decouple your jar from the prefs manager.
You might want to look at Cocoa's NSUserDefaults class for inspiration. It handles the problem you describe by having several layers of preferences, called domains. When you look up the value for a key, such as "PrintUsingAllCaps", it first checks for a value in the user's local domain. If it isn't found there, it can check the system-wide domain, or a network-level domain, and so on.
The absolute last place it checks is called the "Registration Domain", which is basically where hard coded defaults are supposed to go. So, at any point in my code, I can write a preference into the registration domain, and NSUserDefaults will only serve that value if the user hasn't overridden it.
So, in your case, you could provide a method for classes to set a default value for a key before it accesses the (possibly) user defined value. The preferences class doesn't have to know anything about the classes it is serving.
As somebody else suggested, if you need something more sophisticated, you could set a DefaultValueProvider callback object instead of a straight value.
I deleted my first answer since I misunderstood what the author was asking.
To actually address the actual question--it feels like your desire to place preferences (and the calculation of the default values) with the code that uses them makes sense.
Could you meet both requirements by using a preferences container class for each area that follows a pattern for that area, but having it register with a "Global" preference object collection?
Your global collection could do things like iterate over each set of preferences and reset it to defaults but your preferences themselves would still be locally defined and maintained so that it doesn't spider out into other parts of the code.
The only problem I can see is that if you allow the preference object to register itself when instantiated, you run the risk of trying to "reset to defaults" with some of the preferences not instantiated yet.
I suppose this could be fixed by having the main "preference" class instantiate all the others, then any piece of code could retrieve it's local preference object from the central one though a static getter.
This seems to be a lot like how some loggers work. There is a central mechanism for maintaining log levels, output streams and such, but each class has it's own instance of a "log" method and logs to it.
I hope this was more on target. Oh, I also agree with the accepted answer, don't ever make all your methods public static, always use a getter--you'll be glad you did some day.
The JSR-10 (java.util.prefs.*) API uses a factory method with a Class<?> parameter to create Preferences instances. That way the API can store preferences from different classes belonging to the same package in a single file.

Categories

Resources