How to pass string to separate java.class - java

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.

Related

Getting Null when calling variable from another class

I have done a lot of google regarding this and tried many things and have never gotten through. So I have this variable in Class A and I want to print that variable in Class B but the value of the variable in Class A goes through a method before it is called.
public class TestSubject extends javax.swing.JFrame {
static String a;
private void testButtonActionPerformed(java.awt.event.ActionEvent evt) {
a = "hello"; }
}
Here I declare the variable and clicks a button to set the variable value to 'hello'. I tested if the variable did indeed get the value by having another button printing the variable 'a' in the same class.
public class TestSubject2 extends javax.swing.JFrame {
TestSubject test = new TestSubject();
private void okActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(test.a);
}
}
So here I try print the variable a from class 'TestSubject'.
So what I have tried:
I have tried to use both non-static and static.
I have tried to use a return method
class TestSubject { //purposely left the extend but you get what I mean
public String getString() {
return a; } }
Class TestSubject2 {
TestSubject test = new TestSubject();
private void okActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(test.getString());
}
}
However, if I were to explicitly give 'a' a value like:
static String a = "hello";
It would print out properly in the other class using the first method.
I made sure I click the buttons sequentially so the values are being inputted.
So what I want to know is how can I call a variable from another class.

Gauge - run #BeforeSpec in a superclass in Java

I am writing a testing framework using Gauge.
I want some initilization logic performed in one class, and the steps logic to reuse it, like this:
public class A {
protected String property = "";
#BeforeSpec
public void init(){
property = "hello";
}
}
public class B extends A {
#Step("...")
public void verifyProperty() {
assertEquals(property, "hello");
}
}
I can't seem to be able to achieve this. When performing the steps, the "property" is always null.
Placing the #BeforeSpec in class B and calling super.init() works, but I would like to avoid having this call in every test class that extends A.
Has anyone encountered and solved such an issue?
Try to use a static variable:
public class A {
public static String property = "";
#BeforeSpec
public void init(){
property = "hello";
}
}
public class B {
#Step("...")
public void verifyProperty() {
assertEquals(A.property, "hello");
}
}

how to use variable which is declare in another class

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

How do I pass objects along from my Main class to other classes

I'm learning to code java and I encountered some problems in which I could use help understanding how things work.
I've made a list containing "Images", on my Main class, called "myList".
public class Main{
public static void main(String[] args) {
List<Images> myList = new ArrayList<Images>();
...
And I want to access it on this "System" class. But it doesn't seem to let me.
The plan is to access a position (the 3rd, in this example) on the given list (list.get(2)).
So I created the method "work".
//Example
public class System{
public static boolean work(List<Images> list){
if( list.get(2).equals(Something) )
return false;
else ... return true;
}
On this same System class I'm trying to use the method "work", giving it the List that I created on my Main class (myList).
public class System{
...
if( work(myList) ) //Don't know how to reffer to myList
return something;
Gives me the error "myList cannot be resolved to a variable".
So the problem is how to reffer to the list I made on my Main, named "myList".
Not sure if I explained that too well but any suggestions?
Make a List a property of System class, then pass it in the constructor
public class System {
private List<Images> images;
public System(List<Images> images) {
this.images = images;
}
//your other methods
}
Ah, in your main you should also pass the list:
System system = new System(myList);
Another option its to make myList public static and access it like this:
Main.myList
Declare one helper class and declare your list with setter and getters. Mainatin a singleton object of this class and use that list then in different other classes.
you need to make sure its accessible.
Right now your list is scoped the main() function. which is static to boot.
You need to make it accessible. You can do this by storing it in a static variable and having a static function return it.
Or you pass the main object along to other object, so they can access it.
public class Main {
private List<Images> myList = new ArrayList<Images>();
public static void main(String[] args) {
new Main(args);
}
public Main(String[] args) {
myList.add('foo.png');
myList.add('bar.png');
System mySystem = new System(this);
}
public List<Images> getImages() {
return myList();
}
}
public class System{
Main global;
public System(Main main) {
global = main;
}
public void doSomething() {
Iterator<Images> it = global.getImages().iterator();
while(it.hasNext()) {
Images images = it.next();
}
}
}

Writing a Java class with instance parameters, retrieve parameters and print results

Basically, I need to create a new simple Java class which retrieves values from my forms (that I have designed as my process and is deployed as a web application), once the method in the Java class is invoked then the Java class should just simply print out the values (e.g. system.println.out...) it got from the form in a console or text file.
Create a class with some instance parameters. Print a line stating the initial values of these parameter(s).
I am new to Java and have just started few days ago but have this requirement as part of a project.
Please someone help to write this Java class.
I recommend you to read some java beginners books (or the javadoc) in order to understand the Class constructor concept in java before trying to do write something wrong.
A rough class may be like this :
public class myClass{
int param1;
int param2;
public myClass(int firstparam, int secondparam){
this.param1 = firstparam;
this.param2 = secondparam;
}
}
public static void main(){
myClass c = new myClass(1,2);
System.out.println(c.param1 + c.param2);
}
If you don't understand this, please learn the java basis..
You can simply create a class and its constructer like:
public class Test {
//a string representation that we will initialize soon
private String text;
//Firstly you have to instantiate your Test object and initialize your "text"
public Test(String text) {
this.text = text;
//System.out.println(text);
//You can print out this text directly using this constructor which also
//has System.out.println()
}
//You can just use this simple method to print out your text instead of using the
//constructor with "System.out.println"
public void printText() {
System.out.println(this.text);//"this" points what our Test class has
}
}
While using this class is like:
public class TestApp {
public static void main(String[] args) {
Test testObject = new Test("My Text");
/*if you used the constructor with System.out.println, it directly prints out
"My Text"*/
/*if your constructor doesn't have System.out.println, you can use our
printText() method //like:*/
testObject.printText();
}
}

Categories

Resources