Setting Constant Service Url in Android - android

I have a service url (http://servicetest.com/api/) getting datas through the restful service.
I want to ask a question that what is the best way holding this constant?. Is it appropriate holding it in strings.xml or applicationcontroller class, or etc. Because according to my needs, I can use service url in every activity. That's why, it should be accessible from anywhere.
Thanks

I think it would be best to create a class constants(urls or whatever you want to name it) and declare all constant variables as static there so you can access them everywhere in your app without creating an object and when you need to change is you have to change only at one place,hope that helped

Just create a class like this:
public class AppConstants {
public static final String URL = "http://servicetest.com/api/";
/* private Constructor to avoid instanciating this class */
private AppConstants() {}
}
Use it that way, e.g.:
MyAsyncTask task = new MyAsyncTask();
task.execute(AppConstants.URL);

create an Interface (i.e ProjectConstants) for declaring all your project constants like generic class manner..So you can easily access these variables everywhere in your application..
//For example
package com.example.myapp;
public interface ProjectConstants
{
String SERVICE_URL = "http://servicetest.com/api/";
}
// you can use this URL in your application where ever you want by simply calling like this
textView.setText(ProjectConstants.SERVICE_URL);

Related

Using Application class to save current configuration

I have read some articles about how to use/extend the Android Application class but I am still kind of unsure if I can use it for my needs.
In my Application, on startup, i read a JSON configuration file. This configuration file contains some basic infos about an external device. Because I need this infos in several other fragments/activities I simply store an object representation of this json file as a member variable of my Application class.
public App extends Application {
private ConfigurationContainer configuration;
...
getters / setters
}
When I need it i call getApplication().getConfigurationContainer().
Is this OK for my needs?
Yes, It is ok.
Follow this steps.
1.Override onCreate() method and load all the json configuration in this method.
public App extends Application {
private ConfigurationContainer configuration;
public void onCreate(){
super.onCreate();
// load json configuration.
}
// getter setter
}
Declare this class in manifest file.
<application android:name="com.packageName.App">.
Use this configuration in all your activity.
App ap = (App)getApplication();
ConfigurationContainer conf = ap.getConfigurationContainer()
Yes it is reasonable to store globally scoped variables (or objects) in your Application class. You should be careful that you are not storing too much data here, as it will consume memory that is never recovered as long as your app is running.
Your concept is fine, but there are some nuances about using the Application class in this way, it is suggested that you create a Singleton class (instantiated by your Application) to store values like this.
Here is a great SO related to this: Android Application as Singleton

Way to have variables, that can be accessed and modified from every Activity class

I want to hold all my variables somewhere where every Activity can access them and modify them. I tried storing my variables in xml file but it only works one way, I can access them but not modify them. The other option that I have thought about is creating seperate helper class that holds all my variables and offers getValue(); and setValue(); methods, but problem with this is that I think it will be resetted every time I make object of this class. So Is there any other way to have storage for variables?
Your senod option is nearer.
In your Helper class just add a static variable
See:
Class MyHelper {
..
..
public static int globIntVar;
Where you want to use :
MyHelper.globIntVar = 2; // Setter
public int var = MyHelper.globIntVar; // Getter
You can use android.app.Application for Sharing data between diffrence components of Appliction. see this post:
Android: How to declare global variables?
Your requirement is to create some Global Variables, you can create some Global Variable by Using Application Class.
Check Example:
How to declare global variables in Android?
Make one class in your application which store all variables which are used through out application ex.
public Class Const{
Public static int siteurl="http://www.xyz.com/";
}
Now where ever you want to use that variable write
Const.siteurl

Is a "Globals" class holding static variables in Android safe?

Can anyone enlighten me about the safety of a class holding global values in Android?
Here's a short example of what I mean:
public class Globals {
public static int someVariable = 0;
public static User currentUser = null;
public static Handler onLogin = null;
}
Then somewhere in an Activity I do the following:
Globals.someVariable = 42;
Globals.currentUser = new User("John", "Doe");
I have to rely on Globals.currentUser at multiple places in my app as soon as the user is logged in, but I'm unsure if I should do it, and also if I could use a Handler like this.
I read everywhere that an Android app could be killed anytime, does this mean it is killed completely or maybe just a part of it, thus killing my Globals class only?
Or is there any other way to store globally available data in a safe way, without writing every member change to the database (in fact, my User class is a little more complex than in this example. ;-)
Thanks for your effort!
Edit: Ok, here's what I finally did:
public class MyApp extends Application {
private static MyApp _instance;
public MyApp() {
super();
_instance = this;
}
public static MyApp getContext() {
return _instance;
}
....
private User _user = null;
public User getUser() {
if (_user == null) _user = new User();
return _user;
}
}
Then modify the AndroidManifest.xml and add android:name=".MyApp" to your application node to tell the app to use your subclass.
So far everything works fine and I can easily access the current Context (f.ex. in SQLiteOpenHelper) by calling MyApp.getContext().
It would be better to use the Android Application class. It's meant to store global application state
http://developer.android.com/reference/android/app/Application.html
Just create a subclass and make sure to update your manifest file to use your version. Then you can store whatever you need to in it. Activities have a method getApplication() which you can cast to your class to access your implementation
The pattern is discouraged--you will run into problems when unit testing.
Can you explain how you unit-test a class that must supply different custom "Users" here? You are either forcing a mock/fake class into "User" which will probably have a cross-effect on other tests or you are putting an if(test) into your code which gets ugly quick.
Over time populating this class artificially for testing gets more complex and starts to have relationships and dependencies.
More simply it makes it difficult to unit test a class in isolation.
It's one of those patterns that a given programmer either doesn't see a problem with or never uses because he's been burnt--you'll see little middle ground.

Android Store something in Application Context

There is a lot of examples and guides how to get ApplicationContext, but a cannot find some examples which provide me an ability to store some values in ApplicationContext.
I want to get, for example, string mode everywhere in my application, like this:
String mode = getApplicationContext().getMode();
How can I do that?
You have to extend Application (there is no ApplicationContext class) and add the fields you need stored to your custom class. Then you would cast the reference you get from getApplication() to your actual class:
class MyApplication extends Application {
String mode;
}
// in your activity
MyApplication app = (MyApplication)getApplication();
String mode = app.mode;
why don't you store it in shared preferences?

Where should I globally keep/cache data needed for all application lifecycle?

I'm fairly new in Android/Java programming, so some of the basic stuff is still quite confusing. So, lets say my application gets all data (articles) it requires from external XML files, it parses them to data models (Article class) and those articles will be used (displaying in lists or single article) all over the application for all it's lifecycle.
Where should I keep them? Can I create singleton class with an array containing all the articles I've parsed? Or should I save them to database and then query it on demand? (that sounds like too much work, I don't need to cache them for now) What's the best practice here?
Keep them in Application. This is a base class of any android application and it's alive during the whole lifetime of the application, whereas Activities are killed when not shown or orientation is changed.
You have to declare android:name in your AndroidManifest.xml:
<application android:name=".YourApplication"/>
Edited:
This is also relevant: How do I pass data between Activities/Services within a single application?
that depends what is your programming style lol.
you can as you said create a singleton that will read your xml and store everything.
you can create a static hash in your class. this way when you create a new object you will have access to the static information from that class.
you can pass the information from class to class as parameters.
if you want us to tell you which one would be the best it will be difficult without knowing the architecture of your program.
for example you could have a view controller that handle any changes and then it is simple to store the data at that level to pass it on when you switch views.
you could have static views in wich you could directly set all the values as you open them.
you could have losely linked views that call each other without any controller to handle the switching and in that case you would may prefer having a way to collect the info you need from a singleton or a static method...
As long as you make sure that you don't have any threads acting on the shared data you can just create a static class with static members. each activity will be able to access it. If using async download for your data then in the onPostExecute of your handler you can touch the GlobeVars because that runs on the UI thread.
public class GlobalVars {
public static String userId = "?";
//public static String serverUrl = "10.0.2.2"; //localhost when developing
public static String serverUrl = "192.168.1.4"; //on device to laptop
//public static String serverUrl = "102.192.293.10"; //production
public static Book currentBook = null;
public static Chapter currentChapter = null;
public static int lastclickedChapter = -1;
public static Voice currentVoice = null;
public static String catalogJson = "";
public static ArrayList<Book> catalogItems = null;
}
onCreate of MainActivity I can set the catalog to my downloaded list of xml coverted to objects
GlobeVars.catalogItems = downloaded xml to object list
in my SubActivity which is a list of chapters in onclicklistener I can set:
GlobeVars.currentChapter = items[clickeditem];
when you return to the main activity the values will still be set.

Categories

Resources