I developing an android application. I'm confused between two way to use static for customized UI component like dialog, progress bar or alert.
See below.
public class UiUtils {
public static void inputAlertDialogShow(Context context, final View view ,String message,DialogInterface.OnClickListener listener)
{
CustomDialog.Builder customBuilder = new
CustomDialog.Builder(context);
if(listener!=null) {
customBuilder.setMessage(message).setPositiveButton(context.getResources().getString(R.string.dialog_confirm), listener);
}else{
customBuilder.setMessage(message).setPositiveButton(context.getResources().getString(R.string.dialog_confirm),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (view != null) view.requestFocus();
}
});
}
customBuilder.create().show();
}
}
I made method showing dialog as static method. So I can call customized dialog to anywhere like
UiUtils.inputAlertDialogShow(context, view, message, listener).
But I can also use it like this
UiUtils ui = new UiUtils();
ui.inputAlertDialogShow(context, view, message, listener);
Can anyone explain me which one is better and why?
Utilities don't need to be instantiated. Utility class purpose is to provide the commonly used functions that's why all functions in Utility class are made static and they are called Utility.functionName so its better to call UiUtils.inputAlertDialogShow(context, view, message, listener).
Hope this helps.
UiUtils.inputAlertDialogShow(context, view, message, listener).
Call directly like above and one more thing and keep callback with you
when you call this function from any activity or fragment.
Hope it will help you !
you can't do it. when you define a variable as static, you can't make an instance to access it. static is the best way to access objects and method without make an instance. why you try to make an instance? do you know by making an instance, you reserve some memory?
There is just one thing you need to consider, are you writing testable code? If you want your code base to be testable then, static methods is not the way to go, because in order to test static methods of a class you need to use PowerMock, the basic Mockito library can't mock static methods. so in order to make the code base testable you need to not use static methods and use dependency injection to inject the UiUtils class to whichever class depends on the UiUtils
So if you want to know theoretically which one is better? Then not using static methods is better, because it makes for testable code.
you can use both method. because compiler will change it to static call like
Class.methodToCall();
refer this SO answer
and according to java practice, it recommend to call without object.
Related
I'm in the process of completely redesigning my Android app. Before, EVERYTHING was in the same class.
So I tried to redraw everything so that the code is clearer apart Admob than the doc advice to put in the Main thread, I separate the different part of my code in class. So I used two technique: I created a songleton that contains variables that I want to have access to constantly,and I call my classes via weak reference.
Here is what it looks like:
For example, the UIManager class that needs to update the game's IU have a weak reference looks like this:
private static SoftReference<UIManager> ManageUI;
static{ManageUI= new SoftReference<>(null);}
static UIManager get()
{
if(ManageUI.get()==null)
{
ManageUI= new SoftReference<>(new UIManager());
}
return ManageUI.get();
}
GameManager Manager=GameManager.getInstance();
to be able to use the findviewbyid for example I place in method argument the main class that is the mainthread
the singleton that contains all my variables that I want to have permanent access to looks like this:
private GameManager()
{}
/** Holder */
private static class Manager
{
/** Instance unique non préinitialisée */
private final static GameManager instance = new GameManager();
}
/** Point d'accès pour l'instance unique du singleton */
public static GameManager getInstance()
{
return Manager.instance;
}
To separate all in different class, I pass argument to my method so I can call au stuff belong to Activity like that:
(My main class is called GamePlay)
void OpenGlobalScene(GamePlay activity)
{
Manager.OnTitle=false;
if (!checkLayout(activity,R.id.globalscene)) {
LayoutInflater(activity,9, true);
LinearLayout GamePlan = (LinearLayout) activity.findViewById(R.id.globalscene);
GamePlan.setAlpha(Manager.AlphaBord);
}
}
For now, I have not noticed any problems except a few slownesses on old android phone 4.4.2.
Also compared to my old code were EVERYTHING was in the same class, it's much easier to change pieces of code (going to the inapp billing V3 was simpler since everything was in one class that I call like the others with weak referencre)
My questions are:
-What are the problems that such a structure might pose?
I had also chosen that structure to not load or leave in memory things that are not useful
-How are chance that Android will erase from memory an action in progress called with weak reference?
-As you can see I pass the activity has argument to the method, sometimes I pass it from a method to another. Is that fact can cause some trouble?
Thank you for your help.
Check Dagger2 is better than the clasic singleton https://developer.android.com/training/dependency-injection/dagger-android?hl=es-419
thanks for your answer and your tips. I'am gonna check this out.
Anyone else know something about consequences on memory when using weak references ?
I want create a own class with utility functions.
Therefore i want to use typical Activity-functions and build something around them.
I want use the setTitle function for example:
public void frameworkSetTitle() {
String testValue;
setTitle(testValue);
}
Is it possible to use this functions in own classes and pass the result back to the calling Activity?
You have to pass the Activity instance to the util method and call the desired methods there, like setTtitle.
This functionality is not recommended, as passing around context can lead to unintended memory leaks. Flow of information should be uni-directional, anyway.
Your util class should do something more like this:
public static String getGeneratedTitle() {
String titleValue;
// some work
return titleValue;
}
This way, you can just make a simple call in your activity:
myTextView.setText(myUtilClass.getGeneratedTitle());
I am looking for how to share functions and data across multiple activities within a single application. I researched the daylights out of it and find some ideology war between overriding the extend for the application and doing a singleton, neither of which I can find examples sufficient to make me understand. Basically I want to share data and share functions. All activities need the same functions and data so this is not one activity sharing data with another activity. It is all activities needing to have access to the same functions and data.
What I want to know is what is the way to go and how do I do it. I need to see what I need to do in my 34 activities, what the class that is going to be common looks like, and what the Manifest entry needs to be. I also need to be sure the common data area will not be closed by the OS.
This is my first Android - Java program and now find my 15,000 line, 34 activity application needs some structure. I know, should have done things differently but the app works really well with two exceptions. One is that it is structurally a mess. Two is that the fact it is a mess is making it hard to fix one behavior I would like to fix.
This is a GPS based application for racing sailboats. It is timing critical and every activity basically runs a once a second loop inside the location manager onLocationChanged function. That part is fine and I do not want to put the GPS code in one place. The problem is that most activities need to filter the data so a lot of code is copied and pasted to the activities. The filter needs history so it needs to remember a state. There are other functions that are used by several activities so these have been copied as well. Think of a function that averages the last three GPS speed readings. It needs to save some history, do its thing, and give a result. All activities need to do the exact same thing. All this works but the problem is that the averaging starts over every time I switch activities because every activity has its own filter. That gives a glitch in the data that I need to get rid of. I need common place to save the data and hopefully a common place to run the filtering and other functions that are common. If every activity can call the filter function that is using common state data, there will be no glitch across activity changes.
I would appreciate some guidance.
Why you don't just make a Class with only static functions, passing needed Parameters? An example if you want to show an ErrorDialog
public class SharedHelper{
public static Dialog showErrorDialog(Context ctx, String message, String title, DialogInterface.OnClickListener okListener, DialogInterface.OnClickListener cancelListener){
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setMessage(message).setTitle(tilte);
if (okListener != null){
builder.setPositiveButton(R.string.button_positive, okListener);
}
if (cancelListener != null){
builder.setNegativeButton(R.string.button_negative, cancelListener);
}
return builder.show();
}
}
Singletons are (from my point of view) one of the uglyest design pattern and will bite you sooner or later. Putting anything in Application requires you to cast it everytime to the Special Application class you designed. A class with only statics however is very flexible in its usage and doesn't need an instance to work.
For the storage-issue:
lookup "SharedPreferences" & "SQLite" and decide afterwards which storage-type suits your needs more.
For the methods-issue:
This question is a bit more complex and there are different ways to do it. For example you could write a parent-class that implements all your globally needed questions and you let all your activity-classes inherit from it.
public class MyParentActivity extends Activity {
public void myMethod() {
}
}
and:
public class Activity1of34 extends MyParentActivity {
myMethod();
}
I think what this comes down to is not an Android problem but an Object-Oriented Programming problem. If I understand the situation correctly, I'm betting the best solution would be to take your shared filter and create a new Filter class that is instantiated within each Activity (this is likely more manageable than a singleton, but not having seen your use case, it's hard to say for sure). If you need to centrally track the averaging, you can simply create a static variable within the Filter class that maintains the same value during the life of the application. If you really want to maintain that average (even past the application's current lifecycle), you can persist it in a database or other local data options. However, I don't see any reason to put everything in a singleton just to maintain that average. Singletons (and all static data structures) can be potentially troublesome if used incorrectly.
I, for one, do not mind the singleton pattern. Of course as everything else it should not be abused.
This is the construction I use for my shared objects. My app is divided into modules this way but can just as well be used in your case.
public class SharedDataObject {
private Context context;
private static SharedDataObject instance;
public static SharedDataObject getInstance() {
if (instance == null) throw new RuntimeException("Reference to SharedDataObject was null");
return instance;
}
public static SharedDataObject createInstance(Context context) {
if (instance != null) {
return instance;
}
return instance = new SharedDataObject(context.getApplicationContext());
}
// notice the constructor is private
private SharedDataObject(Context context) {
this.context = context;
}
...
public void myMethod() {
// do stuff
}
}
Notice that it uses the application context, that means among other things, means that the context owned by SharedDataObject cannot be used for GUI operations. But, the context will live for the entire lifetime of the application, which is nice.
Furthermore I hate having to pass a context everytime I wish to call methods on my SharedDataObject, thus I have a splashscreen calling SharedDataObject.createInstance() on all my modules.
Once an instance is create, I can call:
SharedDataObject.getInstance().myMethod();
Anywhere in my code, regardless of a context being present or not (from the place calling this code that is).
I have more than 50+ activities in a single project so each and every time I need to write code to move a single activity from one to other.
What is in my mind, may I make a single function which can move more than one activity from a single static method of a class?
Like given in code below.
public static void moveActivity(Parameters)
{
//Code to move activity
}
Or may I follow any other idea for the same.
Any help would be really appreciated.
Thanks in advance.
What is in my mind, may I make a single function which can move more than one activity from a single static method of a class?
I believe not because startActivity needs a Context which can't be used in a static context, I believe.
Or may I follow any other idea for the same.
This depends on what you are doing but maybe ViewPager and/or Fragments could make your life easier. If you have that many Activities then most likely you won't want to try and manage them all from one function anyway because you have to consider extras, flags, etc... You will have two lines to start an Activity (sometimes more) just write the code. What you are trying to do will most likely result in more headaches, IMHO.
If there is a lot of the same data that you are passing around and that is your concern then you can use Bundles to pass them all around.
Try this:
public class Utils {
public static void launchActivity(
Class<? extends Activity> nextActivityClass,
Activity currentActivity, Map<String, Integer> extrasMap) {
Intent launchIntent = new Intent(currentActivity, nextActivityClass);
if (extrasMap != null && extrasMap.size() > 0) {
Set<String> keys = extrasMap.keySet();
for (String key : keys) {
launchIntent.putExtra(key, extrasMap.get(key));
}
}
launchIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
currentActivity.startActivity(launchIntent);
}
}
To use it:
From your activity class, make this call:
Utils.launchActivity(ActivityB.class, this, extrasMap);
I'm starting to work with the android system and Java in general.
I'm coming from a VB background, and in VB I had a Module, that enabled me to write functions that were accessible from everywhere in my program(different pages for example)
Is there something similar to the Module of VB6 in Java and Android?
Thanks!
In Java you can set the visibilty of a function to public. Then you can access it from everywhere in your code, if you have a object of that class.
public void doSomething() {
}
Then you can also use the keyword static to define methods that do not need to be called from an object of that class but exists during the first loading of the class until the end of the programm:
public static void doSomething() {
}