How to exchange information between classes?

0

I want to pass information from one class to another for example:

TextView t;

I have a TextView here, called t and it is in the Main class.

Now in the Main2 class:

t.setText("TextView saiu da Main para a Main2");

I've already tried to put public but still says that the t variable does not exist on Main2.

    
asked by anonymous 08.10.2014 / 22:29

3 answers

4

To access a variable of another class, simply state that the variable is estática , which will allow you to access it without needing an object:

public static TextView t;

To access another class, you must also indicate the class in which the variable exists:

Main.t.setText("TextView saiu da Main para a Main2");

example:

public class Example{
    public static TextView t;
}
public class Example2{
    public static void main(String[] args){
        Example.t.setText("TextView saiu da Main para a Main2");
    }
}
    
08.10.2014 / 22:55
2

I can suggest 3 options

1 Option

Use singleton, or simply define a class as static.

public class Singleton {

    private static Singleton uniqueInstance;

    private Singleton() {
    }

    public static synchronized Singleton getInstance() {
        if (uniqueInstance == null)
            uniqueInstance = new Singleton();
        return uniqueInstance;
    }
}

Read more at: Java Singleton Project Pattern link

2 option

Defining global variables or objects, you can create a Class Application on Android and set global variables or even the singleton.

Example .

3 Option

You can pass variables or objects by Intent to other activities or fragments

Activity 1

Intent i=new Intent("....");
i.putExtra("TEXT", "Olá");
startActivity(i);

Activity 2

TextView text = (TextView) findViewById(R.id.text);

Bundle bundle = getIntent().getExtras();

String var_intent = bundle.getString("TEXT");
text .setText(var_intent );

Read more.

    
09.10.2014 / 20:30
0

You can use the following code below:

Main1 class:

import android.widget.TextView;

public class Main1 {

    private TextView t;

    public TextView getT() {
        return t;
    }

}

Main2 class:

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Main2 extends Activity {

    private TextView t;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Main1 objeto = new Main1();
        t = objeto.getT();
        t = (TextView) findViewById(R.id.textView1); //aqui você põem o nome do id do textView
        t.setText("TextView saiu da Main para a Main2");

    }

}
    
08.10.2014 / 23:11