Is it necessary to write URL of webservice in each page - android

Is it necessary to write URL of web-service in each page in android application or any other way where i can save URL once for the whole application.
I have a android application where i am calling web-service . I am new to android so i don't have idea of saving the URL globally. How i can save the URL once in the whole application.
private final String URL = "http://192.1.1.1/Service1.asmx";
Instead of writing in every .java file what else i can do.

Create a class in java and declare a String field like the following in that class,
public class MyConstants {
public static final String Url = "http://192.1.1.1/Service1.asmx";
}
then you can access it globally from any class like the following
String url = MyConstants.Url;
As Url is a static final field of MyConstants class, so you can access it just with the name of the class(without creating the object of the class with new Operator). i.e MyConstants in this case.
For Learning more about static and to see how this thing works, Please refer to this link
final means that the value cannot be changed after initialization, that's what makes it a constant. static means that instead of having space allocated for the field in each object, only one instance is created for the class.
So, static final means only one instance of the variable no matter how many objects are created and the value of that variable can never change.

If you don't want to create a class you can just put it on res/values/strings
<string name="URLWebService">http://192.1.1.1/Service1.asmx</string>
Then in each class you need it do this :
getResources().getString(R.string.URLWebService);
And you can do it directly or just put a
public static final String URL = getResources().getString(R.string.URLWebService);
You can use what you want all are going to work fine.

You can also use the string file in res/values.
You can you like following:
<string name="ws_url">http://192.1.1.1/Service1.asmx</string>
and use it so: String wsUrl = getString(R.string.ws_url)

create a global constant class and save constants there :
public class Constants {
public static final String Url = "http://192.1.1.1/Service1.asmx";
}
And access it anywhere in application by just calling
Constants.Url

Create common class YourGlobalClass:
public class YourGlobalClass{
public static final String URL = "192.1.1.1/Service1.asmx";
}
And wherever you want just call the class name. your variable name
ex. YourGlobalClass.URL;

Related

How to use FilesDir.Path property outside Activity(Xamarin.Android)?

I create the following class:
public class GlobalVariables
{
public static string databasePath = FilesDir.Path;
private GlobalVariables()
{
}
}
But FilesDir.Path is underlined with red and it doesn't allow me to import its namespaces to use it. When I use it in some Activity I'm able to but when I'm trying to use it in a class like that I'm not able to. With that class I'm trying to get the apk folder path of the project.
How to use FilesDir.Path property outside Activity(Xamarin.Android)?
You need using a Context to implement this feature:
public class GlobalVariables
{
public static string databasePath = Android.App.Application.Context.FilesDir.Path;
...
}
Furthermore, you could refer to: What is 'Context' on Android?

How can i access android global variable from java class

I need to access android global(Application) variable from java class which is inside the my application.I tried with using Context ,but unable.Is there a way to do this ?
Below is the my Application class.I am adding some values for jsonUrl inside my activity.So i need to access these values from a java class.
public class Application extends Application {
private static String jsonUrl;
public static String getJsonUrl() {
return jsonUrl;
}
public static void setJsonUrl(String jsonUrl) {
SPHApplication.jsonUrl = jsonUrl;
}
}
Then i tried to get this valus using below code in my java class.
Application.getJsonUrl();
But it doesn't give me the valus?
It depends.
You could use a static variable by using the static keyword. Then, by using MyClass.staticVariable, you can access it.
Another way is to subclass the android.app.Application class and store your variables there. Then, retrieve them whenever you need.
How to declare global variables in Android?

How to use getString() on static String before onCreate()?

I am trying to use getString() to get an String from resources to assign it to an String array before my activity is created:
private static final String[] MenuNames = {
Resources.getSystem().getString(R.string.LCMeterMenu),
Resources.getSystem().getString(R.string.FrecMenu),
Resources.getSystem().getString(R.string.LogicAnalyzerMenu),
"Prueba con achartengine",
Resources.getSystem().getString(R.string.BrazoMenu)
};
When I use Resources.getSystem().getString(R.string.LCMeterMenu), Eclipse doesn't complain but I get an error at runtime:
Caused by: android.content.res.Resources$NotFoundException: String Resource ID #0x7f0a000a
But if I put inside onCreate():
Log.i("StringR", "String: " + getString(R.string.LCMeterMenu));
I get the String but I can't assign it to the final String I defined before. If I use only getString() before onCreate() I get and static error message. How can I use resources before onCreate() for global variables?
You cannot initialize a static final field from resources; the field needs to be initialized at the time the class is initialized and that happens before the application resources have been bound at run time. (By the way, the reason you cannot use Resources.getSystem() is that the Resources object you obtain that way contains only system resources, not any application resources.)
If you need those strings available before the application resources are bound, the only practical thing to do is to put the strings into the code directly. However, the "Android way" would be to organize your code so initialization only needs to happen during (or after) onCreate(). Just initialize the string array in onCreate() and don't worry about making the fields static or final.
If you don't want the string array to be associated with a particular activity, then you can subclass Application and read the array from resources inside the application class's onCreate() method. (You also need to declare your custom application class in the manifest.) However, the docs recommend against such an approach. (Since the array is private, I suspect that it is closely tied to a single activity anyway, so the use of an Application subclass doesn't seem warranted.)
An alternative is to declare a singleton class for your array. The singleton accessor function then needs a Context so it can retrieve the resources if necessary:
public class StringArray {
private static String[] theArray;
public static String[] getArray(Context context) {
if (theArray == null) {
theArray = context.getResources().getStringArray(R.array.my_strings);
}
return theArray;
}
}
(This assumes the string data are defined in a <string-array> resource like #JaiSoni suggested in his answer.) Once again, the member field cannot be declared final.
No, you can't use Resources before onCreate(). You can get the instance of Resources in onCreate() by using getResources() where you can get all the Strings. Also the strings are already declared as static by defining them in the strings.xml.
Pseudo code for accessing the Resources,
Resources res = getResources();
String app_name = res.getString(R.string.app_name);
Another approach could be to initialize the static array with resource identifiers (which are already available as opposed to the resources themselves).
private static final int[] MenuNames = {
R.string.LCMeterMenu,
R.string.FrecMenu,
...
};
This way, you can defer the loading of resources to when they are actually available:
String s = getResources().getString(MenuNames[i]);
The following is a working approach to initialize static final variables in android from XML, such as strings.xml.
Subclass application and provide a "static context"
Register the application class in manifest
Use the static context to initialize your constants
1. MyApplication.java
public abstract class MyApplication extends Application {
private static Context context;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
/**
* Returns a "static" application context. Don't try to create dialogs on
* this, it's not gonna work!
*
* #return
*/
public static Context getContext() {
return context;
}
}
2. AndroidManifest.xml
<application
android:name=".android.application.MyApplication"
<!-- ... -->
</application>
3. Your application code, e.g. Activity
private static final String[] MenuNames = {
getContext().getString(R.string.LCMeterMenu),
getContext().getString(R.string.FrecMenu),
getContext().getString(R.string.LogicAnalyzerMenu),
"Prueba con achartengine",
getContext().getString(R.string.BrazoMenu)
};
protected static Context getContext() {
return MyApplication.getContext();
}
For working examples refer to AbstractApplication and PreferencesServiceSharedPreferences.
Note that this approach also has its downsides:
Apart from being opposed to the "Android way" (as #Ted Hopp suggested in his answer),
it makes testing a bit difficult. That is why the call to MyApplication.getContext() is wrapped in another method. As it is a static method, overriding it in testing code is not simple. But you could use a framework such as Powermock for this purpose.
In addition it is a bit prone to NullPointerExceptions. As soon as the context is null (e.g. in your testing code) the application code crashes. One option to overcome this, is to do the initialization in a constructor, where you could react to getContext()returning null (see example).
Whatever you get by the getString(int resId) will already be a constant for your application. Why do you have to keep it in another final static variable. You can read it like that whenever you want, right?

Why use TAG in most of the Android logging code

I can see this is common practice among Android developers.
public final class TasksSample extends ListActivity {
private static final String TAG = "TasksSample";
private void method() {
Log.i(TAG, "message");
}
}
Will it be easier, if I do it this way? I need not to declare TAG for every new class.
public final class TasksSample extends ListActivity {
private void method() {
Log.i(getClass().getName(), "message");
}
}
Rather than writing getClass().getName() at each place where a log is placed in a particular activity, it is always preferred to have a TAG that would represent the name of the activity class.
Why use TAG?
When you are running your application there might be more than one Activity class in it. To distinguish which activity class has logged the information in logcat we use a TAG which of course represents the name of the class.
And the proper way (I am not saying what you have written is wrong) of writing the TAG is:
private static final String TAG = TasksSample.class.getSimpleName(); // and not "TasksSample"
Every previous answer is right, but I just wanna add a little comment.
private static final String TAG = TasksSample.class.getSimpleName();
or
private static final String TAG = "TasksSample"
The latter is used when you use proguard. As you know, proguard obfuscates class names and it affects logs too.
calling a function every time has it's toll and getClass().getName() is calling 2 functions every time you log something into the system (an already long process).
Therefor, it's better to save the tag is a final static String instead of calling the same function over and over again.
Yes its a common practice, and is supported by Google for logging & debugging. If you use getClass().getName() then you have to call getClass().getName() every time, so its a better approach use TAG.
Actually getClass().getName() returns the class name, where TAG represents easy understandable name/identification of your class.

A string from res/values/strings.xml doesn't show up for use in my code

I'm trying to store a create database script (a rather lengthy one) in the strings.xml file (noobie here, haven't figured out a better place to put it yet) it does show up in the generated R class:
public static final class string {
public static final int app_name=0x7f040001;
public static final int create_database=0x7f040002; //this one here
public static final int hello=0x7f040000;
}
but when I try this in the code:
DATABASE_CREATE = R.string.create_database;
'create_database' is not available. Ti's simply not there, I get an error if I try to use it. Any ideas why this is so? Do those strings have length limitations? Can they only consist of a single line?
If that's the case, what's the right place to put my SQL create script?
Thanks for your answers.
R.string.create_database in the generated R is an integer (see your line with the comment). In order to get the string value, you need to call getString(R.string.create_database). See getString(int)

Categories

Resources