i am writing a code where i get a string value in a class that extends BaseAdapter. I want this value to be used in another class that extends an Overlay. If my class extends an Activity i can use intent,putstring() and getString, but is to be used for these above specified classes..Can anyone tell me how can i do this. Thanks in advance.
You can either make your variable global or make a singleton FileHelper class that contains values you want to pass between classes.
MyClass:
public String myString = "Hello";
and if you want to use it in
OtherClass:
String myString = MyClass.myString;
If your the FileHelper use this:
public class FileHelper {
private static FileHelper instance;
private String myString;
private FileHelper() {
}
public static FileHelper getInstance() {
if (instance == null) {
instance = new FileHelper();
}
return instance;
}
public void setMyString(String s){
myString = s;
}
public String getMyString(){
return myString();
}
}
You can use the FileHelper with this:
private static FileHelper fileHelper = FileHelper.getInstance();
fileHelper.setString("hello");
String myString = fileHelper.getMyString();
Related
I'm trying to test a method that is in a static context in my class and I want to test it in Junit class but I got a null pointer exception.
My App class :
public class App extends MultiDexApplication {
private static Context mContext;
#Override
public void onCreate() {
super.onCreate();
mContext = this;
}
public static Context getContext() {
return mContext;
}
}
My Method :
public class ColleagueChoice {
static ColleagueApiService apiService = DI.getColleagueApiService();
static List<Colleague> colleagueList = apiService.getColleagues();
static String isEatingAt = App.getContext().getResources().getString(R.string.is_eating_at);
static String isJoining = App.getContext().getResources().getString(R.string.is_joining);
static String notDecided = App.getContext().getString(R.string.has_not_decided_yet);
public static List<Colleague> setScarlettAndHughChoice() {
Colleague scarlett = colleagueList.get(0);
Colleague hugh = colleagueList.get(1);
scarlett.setColleagueIsJoining(isJoining);
hugh.setColleagueIsJoining(isJoining);
List<Colleague> colleagueChoiceList = new ArrayList<>();
colleagueChoiceList.add(scarlett);
colleagueChoiceList.add(hugh);
return colleagueChoiceList;
}
So I'm getting this error at line :
static String isEatingAt = App.getContext().getResources().getString(R.string.is_eating_at);
UP!
Simply remove the App class because this is not very good to put getString in a logic code like services. I just add an enum to my model Colleague and then use: holder.itemView.getContext().getString()
in my adapter with a switch condition.
I'm learning about MVC. My project has tons of variables. So I made a new class for them called MainVariables.
public class MainVariables {
private String mPictureDirectory;
private String mNameOfThePictureFile;
private String mFullPathPicture;
private double mLongitude;
private double mLatitude;
private String mAddress;
private String mCity;
private String mState;
private String mCountry;
private String mPostalCode;
private String mKnownName;
private String mDescription;
private String mSolicitationType;
...
...
The rest is composed by automatic getters and setters for each variable.
I'm having a problem accessing and casting those variables across my application.
I tried accessing it by casting the following in other files:
private MainVariables mMainVariables;
The above code throws the error Attempt to invoke virtual method on a null object reference
Then I tried the following:
private MainVariables mMainVariables = new MainVariables();
Now, this does work. Only in the file it's using though. For Example, I set variables from within the "SolicitationFragment" and when I try to access it on "PostFragment", I get an empty result.
That's because I'm having to initialize MainVariables on each file.
How can I get around this and be able to access my variables globally?
Make the variables static, or final if you're not going to change them. This way you don't have to create a new instance and can call MainVariables.mPictureDirectory immediately
public class MainVariables {
public static String mPictureDirectory;
}
Another option is a singleton pattern, this way you create only one instance of an object and still can use getters and setters
public class MainVariables {
private static MainVariables mInstance = null;
private String mString;
private MainVariables(){
mString = "Hello";
}
public static MainVariables getInstance(){
if(mInstance == null)
{
synchronized (MainVariables.class) {
if (mInstance== null) {
mInstance= new MainVariables();
}
}
return mInstance;
}
public String getString(){
return this.mString;
}
public void setString(String value){
mString = value;
}
}
In your MainActivity you can declare a field
MainVariables mainVariables = MainVariables.getInstance()
and call
mainVariables.[METHOD] from basically anywhere in your MainActivity
Create a class extending your Application class and create a method to get instance of MainVariables:
AppController.java
public class AppController extends Application {
private MainVariables mMainVariables;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public MainVariables getMainVariables() {
if (mMainVariables == null) {
mMainVariables = new MainVariables();
}
return mMainVariables;
}
}
MainVariables.java
public class MainVariables {
private String string;
public String getString(){
return this.string;
}
public void setString(String string){
this.string = string;
}
}
USE:
// SET VALUE
AppController.getInstance().getMainVariables().setString("Hello Android");
// GET VALUE
String str = AppController.getInstance().getMainVariables().getString();
FYI, You have to add AppController class under application name in your AndroidManifest.xml file.
<application
android:name=".AppController">
</application>
Hope this will help~
So I have this "middle man" nonactivity class, where I want to get a string path from an activity class. Then, from my nonactivity class send that string path to a different activity?
Activity A
#Override
public void onCreate(Bundle savedInstanceState)
{
Intent imageToFactory = new Intent(this,NonActivity.class);
imageToFactory.putExtra("yourImage", user_image_path);//I already set user_image path
}
NonActivity
public class NonActivity
{
private Intent grabImagePath = new Intent();
private String grabImagePathString = getIntent.getStringExtra("yourImage");//this obviously gives an error but for the example
public String grabUserImage()
{
return grabImagePathString;
}
}
Activity B
#Override
public void onCreate(Bundle savedInstanceState)
{
NonActivity nonActivity;
String example = nonActivity.grabUserImage();
}
So this method doesn't work for some reason, I think I have to use contexts some how but im not sure exactly how to use them, if anyone can help with examples or modify the example code i did below that'd be awesome!
You can build a static variable that can serve as message bridge, first thing you need to create a class and name it anything you like, in my case I will name the example class as Conn, then add a static HashMap.
public class Conn {
public static HashMap<String,String> storage = new HashMap<>();
}
To utilize this this class in your example:
Activity A
#Override
public void onCreate(Bundle savedInstanceState){
Conn.storage.put("yourImage",user_image_path_in_string);
}
Activity B
#Override
public void onCreate(Bundle savedInstanceState)
{
String example = Conn.storage.get("yourImage");
}
if you want to use third class ( here NonActivity.class ) for some reasons, just do it like this:
create globals class like this :
package helper;
public class Globals {
private static final Globals instance = new Globals();
private GlobalVariables globalVariables = new GlobalVariables();
private Globals() {
}
public static Globals getInstance() {
return instance;
}
public GlobalVariables getValue() {
return globalVariables;
}
}
and global variables class like this :
public class GlobalVariables {
public String grabImagePathString;
}
now in activity A::
Globals.getInstance().getValue(). grabImagePathString = "something......";
and in activity B::
String gtabImagePathString = Globals.getInstance().getValue(). grabImagePathString;
Good Luck
I am trying to create a global variable where it can be accessed from any any where including Activity, Fragment and other custom classes.
public class Global extends Application {
private static Global sInstance;
private String mSharedInfoFileName; //can be any custom object
public static Global getInstance() { return sInstance; }
#Override
public void onCreate() {
super.onCreate();
sInstance = this;
initialize();
}
private void initialize() { mSharedInfoFileName = "globalInfo"; }
public String getFileName() { return mSharedInfoFileName; }
private Global() { }
}
and try to use it like this
public class MyFragment extends android.support.v4.app.Fragment {
String s = Global.getInstance().getFileName();
}
even after declaring it in class scope still gave same error
private static Global mGlobal = Global.getInstance();
which give me Attempt to invoice... .Global.getFileName()' on a null object reference. What am I missing?
Thank you
Change this method to static :
public static String getFileName() {
return mSharedInfoFileName;
}
and call it like below:
Global.getFileName();
The mSharedInfoFileName variable has to be static too :
private static String mSharedInfoFileName;
I'm a new to android please help me with the following.
I'm having an integer value which stores the id of a checked radiobutton. I need to access this value throughout the various classes of my app for a validation purpose.
Please let me know how to declare and access this variable from all the classes.
Thank you.
U can use:
MainActivity.class
Public static int myId;
In other Activities.
int otherId=MainActivity.myId;
following singleton pattern is the only way to do this.in java/android if u create a instance for a class every time it create a new object.what you should do is
1.create a model class and make its as singleton
2.try to access the modelclass from every class
public class CommonModelClass
{
private static CommonModelClass singletonObject;
/** A private Constructor prevents any other class from instantiating. */
private CommonModelClass()
{
// Optional Code
}
public static synchronized CommonModelClass getSingletonObject()
{
if (singletonObject == null)
{
singletonObject = new CommonModelClass();
}
return singletonObject;
}
/**
* used to clear CommonModelClass(SingletonClass) Memory
*/
public void clear()
{
singletonObject = null;
}
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
//getters and setters starts from here.it is used to set and get a value
public String getcheckBox()
{
return checkBox;
}
public void setcheckBox(String checkBox)
{
this.checkBox = checkBox;
}
}
accessing the model class values from other class
commonModelClass = CommonModelClass.getSingletonObject();
commonModelClass.getcheckBox();
http://javapapers.com/design-patterns/singleton-pattern/
You can declare your integer variable as static and access in any class.Like this
class A{
static int a;
}
You can access in another class like this.
class B{
int b = A.a;
}