Hello, there is a code in the class:

... final String test = response.headers().get("example"); Log.d(TAG, "example=%s", test); ... 

How can I show (transfer) to activations in TextView , the contents of this test line (The logs show the necessary information from the test lines. Somehow need to transfer it to activations, and there show in the view)

  • one
    Do you need to activate a variable of some other class? Make a public static String test in 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. - selya
  • one
    Do not listen to harmful advice, do not make static variables. - Suvitruf
  • In the class that sends the http request prokidyvayte link to the Activity . If this is AsyncTask , then in onPostExecute then call the method with the passed Activity . - Suvitruf
  • one
    @ Anton is the solution you are offered, not bad, but terrible. I really hope that you will not do this in a real application, but you will learn something about callbacks. The question lacks context. What is this class in which there is code, from which it is inherited? An instance of this class causes activations, in which it is necessary to show the text? Is this some kind of request in runtime? Edit the question so that there is a minimal reproducible example, then your problem can be solved in a much better way - pavlofff
  • one
    The fact is that he does not personally like me, and this is unacceptable in the android-development, since you are working with the system's life cycle component, and not the user class. Is your class inherited from any API classes or is it custom? - pavlofff

2 answers 2

If you need your Activity to have access to a variable from another class, you can create a static field in your Activity:

 public static String test; 

And then from any part of the program, set the value to this field:

 MyActivity.test = test; 

Although this solution is working, however, if you have to resort to this method, then your application is probably not well designed. Open ( public ) mutable (non- final ) fields should generally be avoided.

A more correct solution in theory would look like this:

  1. In the MyActivity class, the static getInstance() method is defined:

     ... public static MyActivity getInstance() { return ... } .... 

    which returns an instance of MyActivity to which to transfer something.

  2. The MyActivity class also declares the setText(String) method:

     public void setText(String text) { ... } 

    inside of which you do everything you need with this text

  3. Then transfer the text from any part of the program:

     MyActivity.getInstance().setText(text); 

This option already looks quite good.

  • one
    The only solution that looks good in the Android framework is the transfer of runtime-updated data via callback (callback interface). What you wrote here is both - heresy. - pavlofff
  • @pavloff offer your answer) the wording of the question was: "how can you?". I gave the answer. If the question was “how to maximize correctly?”, “How to design correctly?”, “How is it usually done in the code of the android application?”
  • but so it is impossible. at least in android. That it works still does not allow such actions with the components of the life cycle. - pavlofff
  • can you answer then what does the use of static affect? application does not fall? does not lag, does not crash, does not hang. Is the task done? But you keep saying that this is heresy. So write the correct version step by step clearly and correctly. Or the "ego" does not allow?)) - Anton
  • one
    Do not worry, from the point of view of execution there are no problems (at least as long as you do not write / read some variable simultaneously from different streams). The problem is how the android framework is designed. More precisely, the majority of tasks that need to be solved with its help are solved with callbacks. This is equivalent to putting pvc windows instead of stained glass in the temple. It will work, but not accepted. However, there are situations where you can and should do so. - selya

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