Since activit is a component of the system life cycle, “simple” methods of interaction between classes are not suitable for it, since activit should not be connected with classes that can live longer than the life cycle of the activity itself.
For transferring dynamic data that is updated during execution, a callback (callback interface) is traditionally used in activation. An example of such a callback:
Class that generates data during program execution:
public class DataSource { StringCallback stringCallback; // Определяем интерфейс обратного вызова public interface StringCallback { public void onResult (String result); } // Метод для регистрации интерфейса на принимающей данные стороне public void setStringCallback (StringCallback callback){ stringCallback = callback; } // некоторый метод получения данных public void getData(){ // искуственная задержка в 10 сек., изображающяя время на получение данных try { Thread.sleep (10000); } catch (InterruptedException e) { e.printStackTrace(); } // Получены данные в виде строки "Бинго" String data = "Bingo!"; // Передаем полученные данные приемнику (в активити) stringCallback.onResult(data); } }
Activit, in which you need to get data from another class:
public class MainActivity extends Activity { TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // виджет, куда выводить полученный текст text = findViewById(R.id.text); // регестрируем колбэк в активити DataSource ds = new DataSource(); ds.setStringCallback(new DataSource.StringCallback() { // получаем данные при их поступлении @Override public void onResult(String result) { // выводим полученные данные на экран text.setText(result); } }); // некоторый метод запроса данных, которые нужно отобразить на экране ds.getData(); } }
In this way, you can transfer any data: primitive types, classes, collections, etc., as well as any number of different data. What you need to pass is determined only by the signature of the callback interface method ( onResult() in our example)
This is the simplest, but quite working example for simple interaction. For more serious work of this kind, it is recently accepted to use reactive interaction through RxJava , previously used data buses as EventBus
public static String testin the class of your activity, and from your class in which your code is located, set its value:YourActivity.test = test. This will work, but from the point of view of the OOP, this solution is generally a crutch, because the application must be designed so that the objects communicate with each other by function calls. - selyastaticvariables. - Suvitruf ♦Activity. If this isAsyncTask, then inonPostExecutethen call the method with the passedActivity. - Suvitruf ♦