• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Help with setting Globals

snowman24

Newbie
In the process of learning Java and Android. I understand that I am trying to do but can't seem to make it work. I created a global class as seen here

Code:
public class Globals  {
    private static Globals instance;
    private String status;
public Globals()  {
    }
public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
public static Globals getInstance() {
        if (instance == null) instance = new Globals();
        return instance;
    }
}

In another class I have a method where I set the value of the status.
At the entry of the activity I set the global using
Code:
Globals g= Globals.getInstance()


[code]public void getStatus() {
     JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                serverURL, new Response.Listener<JSONObject>() {
if (response == null) {
} else {
                    try {

                        String status = (response.getString("status"));
if (Integer.parseInt(status) != 0) {
g.setStatus(status);
goMain();
                         
                        } else {
                            // TODO: 10/24/2017 IF ZERO GO TO ACTIVATION ERROR ACTIVITY
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(jsonObjectRequest);
    }


From what I can tell the g.setStatus(status) works from the point that I don't receive any errors. After setting the variable, I goMain(), which for me is just a second activity with a text box where I attempt to call the global back and display in the text box. I am calling the global as such


Code:
public class HomeActivity extends Activity {
    Globals g= Globals.getInstance();
    private TextView mytext;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);


        mytext=(TextView) findViewById(R.id.textView);
        String test= g.getStatus();
        mytext.setText(test);

    }
}


Before somebody says use intent and putextras, yes I could and know how but I want to get global variables to work if for nothing more than my knowledge of knowing how to correctly. I have tested the text box using put and get extra so I know it works, but trying to set and get the global variables it does not. Can somebody point out the mistake I am making?
Thanks
 
First, are your absolutely sure that the g.setStatus() method is being called?
You have this code

Code:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                serverURL, new Response.Listener<JSONObject>() {
if (response == null) {
} else {
  ...

So if response is null then nothing will happen, and you won't even know because you don't log or display any error.
 
And besides, what you have done with your code, is to implement a singleton class.
If you simply want to have a global variable, you could do it like this

Code:
public class Globals {
  public static String status;
}
 
And besides, what you have done with your code, is to implement a singleton class.
If you simply want to have a global variable, you could do it like this

Code:
public class Globals {
  public static String status;
}

Thank you for looking over. I believe I was over thinking it and not full understanding. After you pointed this out and I read some more, it makes sense.
 
Of course the global variable thing is a complete hack, and goes against all that is good O-O design. You should do it using Intent data.
 
Of course the global variable thing is a complete hack, and goes against all that is good O-O design. You should do it using Intent data.
I understand global variables are look down upon by some and not so much by others. I successfully passed the info thru an intent and have no problem doing so, I was just trying to accomplish it with a global for a possible future need.
 
:) I'm a purist, so that kind of thing really grates on me.
Being new to Java and Android, can you give me a brief explanation as to what is bad about using globals. I have seen it posted in several other forums but nobody has really said why it's a bad thing.
 
Being new to Java and Android, can you give me a brief explanation as to what is bad about using globals. I have seen it posted in several other forums but nobody has really said why it's a bad thing.

Because there are certain design principles involved in good O-O design. And one of the foundation ideas is encapsulation. Having global publicly accessible class member variables like this breaks encapsulation. By that I mean that all member variables should ideally be private, and only accessible via methods on that class.
Really, the class member variables are inner implementation details of the class, and should not be exposed to any code outside the class. If anything, your initial implementation using a singleton class, and getter/setter methods was a better design pattern. Having member variables accessible via methods also gives you the freedom to vary the implementation details at a later date e.g. suppose I wished to change the algorithm to calculate a member variable's value, or somehow modify it. If I allow external code to access the member variable directly, I lose that capability. It makes the code architecture more inflexible, and unable to change. And the holy grail of software development is to write your code in such a way, that it can be adapted in the face of future changed requirements. Change happens a lot.

An acceptable use of global public class variables is to use a constant value. So you may have something like this

Code:
class GlobalConstants {
  public static final String MY_NAME = "LV426";
}

Which is ok, because the 'final' modifier means this variable is immutable i.e. cannot change.
 
Because there are certain design principles involved in good O-O design. And one of the foundation ideas is encapsulation. Having global publicly accessible class member variables like this breaks encapsulation. By that I mean that all member variables should ideally be private, and only accessible via methods on that class.
Really, the class member variables are inner implementation details of the class, and should not be exposed to any code outside the class. If anything, your initial implementation using a singleton class, and getter/setter methods was a better design pattern. Having member variables accessible via methods also gives you the freedom to vary the implementation details at a later date e.g. suppose I wished to change the algorithm to calculate a member variable's value, or somehow modify it. If I allow external code to access the member variable directly, I lose that capability. It makes the code architecture more inflexible, and unable to change. And the holy grail of software development is to write your code in such a way, that it can be adapted in the face of future changed requirements. Change happens a lot.

An acceptable use of global public class variables is to use a constant value. So you may have something like this

Code:
class GlobalConstants {
  public static final String MY_NAME = "LV426";
}

Which is ok, because the 'final' modifier means this variable is immutable i.e. cannot change.

If I understand correctly which I think I do, it's best to limit Global varibales to values that will not be changed over the course of the life cycle, something like assigning the value of pie=3.15159 since it would not change but could be called for use thru the application. Use class variables for the scope of the class itself and pass that variable to others via intent. Is this somewhat correct?
 
Yes correct. Although Intents are something very specific to Android apps, to allow data to be passed between Activities.
In other situations, class variable values can be passed in to other classes via method parameters.
 
Yes correct. Although Intents are something very specific to Android apps, to allow data to be passed between Activities.
In other situations, class variable values can be passed in to other classes via method parameters.
Thank you for the brief explanation, makes sense.
 
Back
Top Bottom