I have a variable which is initialize in one class and i want to use it in another java class
and i want to use collect as table name in another class which is for Database Helper class how can i do it..
Thanks in advance for making a time to read it :)
i have a example code below
public class example()
{
String collect;
//and here i have one spinner
//and in itemSelected in spinner
//i getting that item like this
String item = getItemslected.toString;
collect=item;
}
Options:
1.Use static variable:
Declare static String collect;
and access it from other class as <YourClassNmae>.collect;
where YourClassName is the class in which you have declared the static variable.
2.Use Application class
Create application class extending Application
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
Declare the application class name in manifest like:
<application
android:name=".MyApplication"
android:icon="#drawable/icon"
android:label="#string/app_name">
Then in your activities you can get and set the variable like so:
// set
((MyApplication) this.getApplication()).setSomeVariable(collect);
// get
String collect = ((MyApplication) this.getApplication()).getSomeVariable();
You can declare that variable as public static and you can use it from any other class. Other way to use that is by using set and get method.
You can make a variable static and refer to it using Classname.variable. If you don't want to make it static, you'll need a reference to an instance of the class then refer to it using myInstance.variable. The other option is to use methods to return it (again, either static or non-static).
The variable (or method) will also need the appropriate access modifier:
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
public class Main{
public static void main(String[] args) {
System.out.println(Example.test);
Example.test = "123";
System.out.println(Example.test);
}
}
public class Example{
public static String test = "This is a Test";
}
Output:
This is a test
123
Related
Is it able to avoid using "static" when call variable from another class? thank you very much
Here is my code.
class Hello {
public static String say = "Hello World"; //I using static
public void born() {
System.out.println(say);
}
}
public class SayHello extends Hello {
public static void main(String[] args) {
Hello myHello = new Hello();
myHello.born();
System.out.println(say);
}
The Output:
Hello World
Hello World
If I use public String say = "Hello World";
it output Hello World null
AnyIdea to avoid using "static" when call variable from another class?
thank you very much
If you remove the static, it will not compile. Static fields can be marked private, if you want to hide them. So then they are reachable by all instances of the class Hello only. The proper way of modifying or getting would be:
class Main extends Hello {
public static void main(String[] args) throws Exception {
Hello myHello = new Hello();
myHello.born();
// System.out.println(say); //doesn't allow access
// System.out.println(Hello.say); //doesn't allow access
System.out.println(myHello.getSay());
}
}
class Hello {
private static String say = "Hello World"; //private
public void born() {
System.out.println(say);
}
public String getSay() {
return say;
}
}
A static variable is common to all the instances (or objects) of the class because it is a class level variable. In other words you can say that only a single copy of static variable is created and shared among all the instances of the class.
So if you don't want to use static, then you can't use it in the other instances of class.
Yes, if you don't declare it static you can reference it from an instance: myHello.say.
It is the same as for calling a function.
public class SayHello extends Hello {
public static void main(String[] args) {
Hello myHello = new Hello();
myHello.born();
System.out.println(myHello.say);
}
}
For a constant, ie. a String that never changes and is the same for all instances of the class, it makes sense to declare it static and use it as such.
If you don't mark the string as static you will get a compilation error because when you do System.out.println(say) in the main method you are using say in a static context (since the main method must be static).
If you remove System.out.println(say); and just leave myHello.born(); then there's no need for say to be static because you'll only be using it from non-static methods (i.e. the born() method). You can see it in this example where I commented that line and defined say as not being static.
Another option would be to make the println like this, since the variable is public: System.out.println(myHello.say);
Need a variable to hold a value which will be assigned once and will be used by every method of a class
if I specify it as non static variable it is not holding the value
Class Test{
private String test;
public void method1(){
test = "String1";
}
public void method2(){
System.out.println(test.length());
}
}
Getting Null Pointer exception. the value of the test will be used in every method.
Could anyone help me, how to fix the issue.
The NullPointerException will be thrown whenever the test variable is null and you try to invoke methods on that variable. In your case, when you invoke method2() before method1(). That has nothing to do with global, local or whatever, as Long Vu already mentioned.
So first you should make sure, you don't access an uninitialized variable. Then, if you need a class with a single instance, which should be accessible application wide, you can implement this using the singleton pattern. For more about it, have a look at this Wikipedia page: https://en.wikipedia.org/wiki/Singleton_pattern
Maybe your problem is that you are creating multiple objects of class Test.
For example this should work:
Test test1=new Test();
test1.method1(); //call this first then other methods
test1.method2();
You should use this object "test1" as a parameter wherever you need it.
If you want to access the variable globally then create a Singletone class:
class Test{
private static Test single_instance = null;
private String test;
// private constructor restricted to this class itself
private Test(){
}
// static method to create instance of Singleton class
public static Test getInstance(){
if (single_instance == null)
single_instance = new Test();
return single_instance;
}
public void setTest(String value){
test = value;
}
public String getTest(){
return test;
}
public static void main(String args[]){
Test test = Test.getInstance();
test.setTest("String1");
test.getTest();
}
}
I'm trying to pass a string from my main activity to a separate class
that does not have a activity running.
I've looked into passing variables with intent and bundles but what i've read they use two activities
I've found a video of something close to what i'm trying to do but in reverse and can't get it to work. (https://www.youtube.com/watch?v=CSifkubnE-E)
Now the string changes so I can't use static
and my second.java has no context to pass to.
below is a basic representation of what i'd would like to do.
main.java
import second
public class Main extends Activity {
String mystring = "variable"
//mystring changes depending on the user
mystring = "userchangedvariable"
}
second.java
public class dosomething(){
String localvar;
localvar = mystring
}
To be clear as possible I want to pass a variable from the main.java to the second.java that has no context. I don't want to add the second.java class to my main.java, I want to keep them separate(some of the things I read say merge them). How can I do this?
I did not get the following statement.
Now the string changes so I can't use static
You can update the static values. You cannot update final values. Also, you need to somehow create a connection. You can create another class and share the static variables
class ThirdClass {
public static String sharedString;
}
class Main {
ThirdClass.sharedString = "somevalue";
}
class Second {
localVar = ThirdClass.sharedString;
}
You can do it in those ways:
class Activity {
onCreate() {
String stringToPass = "TEST";
Example example = new Example(stringToPass);
}
}
class Example {
private String stringToPass;
public Example(String stringToPass) {
this.stringToPass = stringToPass;
}
}
or
class Activity {
onCreate() {
String stringToPass = "TEST";
Example example = new Example();
example.setStringToPass(stringToPass);
}
}
class Example {
private String stringToPass;
public void setStringToPass(String stringToPass) {
this.stringToPass = stringToPass;
}
public Example() {
}
}
or
class Activity {
onCreate() {
String stringToPass = "TEST";
Example.stringToPass = stringToPass;
}
}
static class Example {
public static String stringToPass;
}
or (not the advised way)
class Activity {
onCreate() {
String stringToPass = "TEST";
Example example = new Example();
example.stringToPass = stringToPass;
}
}
class Example {
public String stringToPass;
public Example() {
}
}
If you create a new object and the string is required for creating -> great make it as a requirement in the constructor. (first version)
If you create a new object and the string is not required for creating -> great make a property (second version)
Third version is needed more rarely (you can set the string without having to create an object) and the fourth version should be avoided completely in Java.
In the main .java file, add the following:
second example = new second("variable");
This can then be referenced anywhere inside your main method. For example:
example.setString("variable);
Then, inside your second .java file, you'll need to add the following:
public class second
{
private String variable;
public void setString(String pass)
{
variable = pass
}
}
This way anything you pass to the example variable inside your main .java file
will be passed over to the setString method.
static class PushConfig{
#Value("${jpush.mq.appKey}")
private String appKeyMQ;
}
like this, I want to get config in inner Class,it's not work
Create a new class with this code:
public static anyName = yourClass
Then you can use anyName.anyMethod(...) to use a method
I'm trying to initialize a static class, with an argument, and then run some more static code in that class.
I'm aware of the static block, but it seems it can't take any arguments.
Is there a way to pass arguments to a static constructor?
If not, what is the recommended technique to initialize a Static class using an argument?
Edit:
A static class to my understanding is a class which cannot be instantiated (in c# they're called static classes, if Java has a different term for them, sorry for not being aware of it) - it's accessed through it's class name rather than an object name.
What I'm trying to achieve (very simplified) is a class which receives a dictionary as String, parses it, and has methods manipulate it like GetRandomEntry.
Here's an elaborated snippet of my code:
public class QuestionsRepository {
private static Map<String,String[]> easyDefinitions = new HashMap<String,String[]>();
//...
staticĀ
{
// need to receive and parse dictionary here
}
//...
Taking the relevant parts of a code snippet is never easy, hope i have chosen wisely (:
Another detail that may be relevant - I'm a c# programmer, usually. Just Started learning Java lately.
Thanks.
I think you would need to initialize the static fields of the class according to some input. You can do it in the following way by calling the static method of another class:
class ClassToInitialize {
static {
staticField = ParamPassClass.getParameter();
}
private static String staticField;
ClassToInitialize() {
System.out.println("This is the parameter: " + staticField);
}
}
class ParamPassClass {
private static String parameter;
static String getParameter() {
return parameter;
}
static void setParameter(String parameter) {
ParamPassClass.parameter = parameter;
}
}
class Main {
public static void main(String args[]) {
ParamPassClass.setParameter("Test param");
new ClassToInitialize();
}
}
Java doesn't have static constructors. It only has static initializers and static initializers do not take any arguments. It is executed when the class is first loaded, and there is no way to call it yourself.
You either need to use actual objects, or add some way of configuring the class (eg through a static method).
you should mention the member class with a static qualifier, otherwise there is no such a thing as a static class
Here you can find the explanation of using the word 'static' in this context.
Now you should just call its constructor and pass all the arguments you want,
the only restriction that you have on a static member class is that it can't refer the non-static fields of its outer class, it resembles a static methods on class that can't refer the non-static fields of class.
I didn't understand why do you mention a static initialization block here, could you please clarify a little?
Be aware also that in java there is no such a thing as static constructor....
Hope this helps
You can have a static method public static void setUp(Arg1 arg1, Arg2 arg2...) which sets up all your static fields and invoke it when your program starts.
You have to make sure this method will be called only once [or only when you want to reset these fields]
It is not possible to pass arguments directly to the static initializes (JLS:static initializers).
It would be nice if you could share more information about your goals.
You could use an enum to initialize a singleton with a string parameter like this
import java.util.*;
class Data {
static Map<String,String[]> easyDefinitions = new HashMap<String,String[]>();
}
public enum QuestionsRepository
{
repository("primary=red,green,blue;secondary=cyan,yellow,magenta");
QuestionsRepository(String dictionary) {
String[] rules = dictionary.split(";");
for (String rule:rules) {
String[] keyValuePair = rule.split("=",2);
Data.easyDefinitions.put(keyValuePair[0],keyValuePair[1].split(","));
}
}
}