SQLiteOpenHandler why do we need the Context variable? - java

I've started programing my first app in android, and noticed that in the constructor of SQLiteOpenHandler that is:
public SQLiteOpenHelper (Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
I have a "Context" variable which role is unclear to me, because my intuition is to think that only one DB could exist with the same name NO mattar in what context I create it. I've looked in the manual and it said:
Parameters:
context to use to open or create the database
which did help me figure out the Context role ether.
Therefore, I'd like to ask
What is the role of the Context in the DB creation?
Will different Data Base instances will be created for different Contexts but same DB name, factory and version?

What is the role of the Context in the DB creation?
It is needed to obtain your app's package name when constructing the full package-private path for the database file.
Specifically, Context.getDatabasePath() called by openOrCreateDatabase(), called by SQLiteOpenHelper.
Will different Data Base instances will be created for different Contexts but same DB name, factory and version?
No, provided that the contexts are withing the same app i.e. share the same package name defined in the manifest.
If the apps are different, the app-private data paths will be different and the database files will be different.

Related

Guice IOC: Manual (and Optional) Creation of a Singleton

Trying to get started with Guice, and struggling to see how my use-case fits in.
I have a command-line application, which takes several optional parameters.
Let's say I've got the tool shows a customer's orders, for example
order-tool display --customerId 123
This shows all the orders owned by customer with ID 123. Now, the user can also specify a user's name:
order-tool display --customerName "Bob Smith"
BUT the interface to query for orders relies on customer IDs. Thus, we need to map from a customer name to a customer ID. To do this, we need a connection to the customer API. Thus, the user has to specify:
order-tool display --customerName "Bob Smith" --customerApi "http://localhost:8080/customer"
When starting the application, I want to parse all the arguments. In the case where --customerApi is specified, I want to place a CustomerApi singleton in my IoC context - which is parameterized by the CLI arg with the API URL.
Then, when the code runs to display a customer by name - it asks the context if it has a CustomerApi singleton. If it doesn't it throws an exception, telling the CLI user that they need to specify --customerApi if they want to use --customerName. However, if one has been created - then it simply retrieves it from the IoC context.
It sounds like "optionally creating a singleton" isn't exactly what you're trying to do here. I mean, it is, but that's as simple as:
if (args.hasCustomerApi()) {
bind(CustomerApi.class).toInstance(new CustomerApi(args.getCustomerApi()));
}
To allow for optional bindings, you will probably need to annotate their use with #Nullable.
I think your real question is how to structure an application so that you can partially configure it, use the configuration to read and validate some command-line flags, then use the flags to finish configuring your application. I think the best way to do that is with a child injector.
public static void main(String[] args) {
Injector injector = Guice.createInjector(new AModule(), new BModule(), ...);
Arguments arguments = injector.getInstance(ArgParser.class).parse(args);
validateArguments(arguments); // throw if required arguments are missing
Injector childInjector =
injector.createChildInjector(new ArgsModule(arguments));
childInjector.getInstance(Application.class).run();
}
Child injectors are just like normal injectors that defer to a parent if they don't contain the given bindings themselves. You can also read documents on how Guice resolves bindings.

Why is context passed to the constructor of Intent?

I am trying to understand why we pass a Context instance to the Intent constructor? Why isn't it enough to do new Intent(SomeActivity.class)? Does Android enforce some restrictions or what?
I was trying to look at the code but all I find is that it gets the package name.
Intent documentation
To identify an Activity in an Android application unambiguously, you need to have both, the name of the application (aka Android application package), and the full name of the activity (java package name + class name of activity class). These are exactly those two parameters you give in constructor. Context is used to get Android application package name, and the class to get full class name.
An Activity with the same full name can be used in two applications. If you do not provide Context, then Android won't know which application an activity belongs to.
As you guessed, the Context in the constructor is used to get the package name of the application.
Inferring the package name from the class as in SomeActivity.class.getPackage().getName() does not work in every case, as it could be different from the application's package name.

ClassCastError when share objects between webapp

Note: this is not cross-posting (although it's related to my other question shared objects between webapps of the same tomcat)
I have 2 webapps running at two contexts: c1, c2 (both immediately after the root). I put a startupListener in c1 to share a variable, and another one in c2 to retrieve it. The problem is if I share an object of built-in datatypes (like HashMap, Integer,...) it is ok, but custom datatype can't be cast. For example, if I have a custom class named User, and pass an object of that type around, ClassCastError happened.
My startuplistener in c1 is:
public void contextInitialized(ServletContextEvent sce) {
User user = new user("name");
Integer exampleInt = 1;
ServletContext context = sce.getServletContext().getContext("/c1");
if (context!=null)
{
context.setAttribute("user", user);
context.setAttribute("id", exampleInt);
}
}
In c2 app, it is like this:
public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext().getContext("/c1");
Integer integer = (Integer) context.getAttribute("id");//this line is OK
Object object = context.getAttribute("user");
User userObject = (User) object; //this line triggered error
User user = (User) context.getAttribute("user");// also trigger error
}
Why so? (a class complain about casting to itself?). Any workaround: I want to share my objects between contexts of the same jvm.
Tks.
The class of the object in the first webapp is loaded by the first webapp classloader. A class with the same name is loaded in the second webapp, by the second webapp classloader. So, even if both apps have access to a class with the same name, they're two different classes, because they're not loaded by the same classloader.
I wouldn't try to share objects between apps this way. It won't work in a clustered environment anyway, and a more secure container could return null when asked for another servlet context. Consider sharing a database between the two applications, and storing the shared data in the shared database.
If you still want to go this route, then make sure the shared classes are in the container's classpath, and not in each webapp classpath.

REQ: Retrieving properties in my java app. collected by "PropertyPlaceholderConfigurer" -- properties are stored in a database as key/value

PUsing Spring 3.2.0.release and JDK 1.6. I've a standalone Java program (NOT running inside tomcat etal) and I'm loading properties from a database.
I've used this excellent article as a base and it works perfectly. Using the PropertiesPrinter bean (defined there) as a base and adding getters I can do stuff like getFileLocation(), getPetDogsName() but then I need to have/create setter/getters for every property.
What I would like to have is a Spring Bean or normal Java class called DatabaseProperties with a method like getProperty("filelocation"); which I can use in my application (main)and so I can retrieve/get the value of the property filelocation which is somewhere inside the information collected by PropertyPlaceholderConfigurer.
I've done a lot of digging but can't seem to find the information I need or at least I'm not able to combine the gathered info into a working program as I'm not fluent with Spring....
Any hint/pointers/urls/code is higly appreciated. It's probably relative easy but it is still out of reach for me atm.
One solution for reading values set by the PropertyPlaceholderConfigurer, is to use the #Value annotation rather than a method for setting class member variables:
class MyClass {
#Value("${file.location}")
private String fileLocation;
...
}

JSF application not supporting multiple users logged in

I am a JSF beginner and have developed a mini application that is working fine. the problem is, when more than one user logs in, the application won't work. Only one user can log in and work. what part of application probably have to be checked??? the only static variable in my application are the beans managed name as follows:-
public static final String MANAGED_NAME = "catBean";
public static final String MANAGED_NAME = "appBean";
etc etc.
Do I need to change the static keyword? or where possibly can error be in my application. this is way too primitive question but owing to my very little knowledge accepted........:)
You need to take sessionScoped bean to maintain session data
It seems you are using static fields which are shared and they are not at object level they are associated with class

Categories

Resources