How to transfer a variable with method1 () to method2 ()?

The variable is not visible because it is declared inside the method, and there is no hard link to it. In other words, after executing the method, the variable is really erased from memory, what can you think of?

Maybe there is an option to write data to a temporary file?

public class Test1 { ... @JavascriptInterface public String method1() { String title = 1; return title; } } public class Test2 { public void method2() { title //ошибка компиляции - пСрСмСнная title Π½Π΅ Π²ΠΈΠ΄Π½Π° ΠΈΠ· этого Π±Π»ΠΎΠΊΠ° ΠΊΠΎΠ΄Π° } } 

    2 answers 2

    Thank you all for your attention, here is the answer.

      public class Test1 { ... @JavascriptInterface public String method1() { String title = 1; SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.putString("key_name", title); // сохранСниС ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½ΠΎΠΉ return title; } } public class Test2 { public void method2() { SharedPreferences pref = mContext.getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); String title = pref.getString("key_name", null); } } 
    • Learn what class properties are. - And
    • And this code only earns on android? - gil9red
    • @ gil9red, where do you see the androyd label? - And
    • @And, Google SharedPreferences shows links to articles on android, and there is no corresponding label in the question - gil9red
    • @ gil9red was a label, but it was removed - Sergey Zelensky

    Braces define the scope of the variables. This is all about the stack question. Line

     { String title = "1" } // ΠΈΠΌΠ΅Π½Π½ΠΎ с ΠΊΠ°Π²Ρ‹Ρ‡ΠΊΠ°ΠΌΠΈ, Π² вашСм ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π΅ Π² String ΠΏΠΎΡ‡Π΅ΠΌΡƒ-Ρ‚ΠΎ пСрСдаСтся int 

    will create a reference to the title object on the stack. The object will be available in all nested levels {}, but as soon as the curly bracket inside which the object was created is closed, it ceases to be accessible from the outside. You can solve the problem, for example, by creating an object as a class field, that is

     public class Test1 { String title = "1"; ... public String method1() { ... // ΠžΠ±ΡŠΠ΅ΠΊΡ‚ title Π±ΡƒΠ΄Π΅Ρ‚ здСсь доступСн } public class Test2 { public String method2() { ... // И здСсь Ρ‚ΠΎΠΆΠ΅ } } } // А Π²ΠΎΡ‚ здСсь ΡƒΠΆΠ΅ Π½Π΅Ρ‚. 
    • just the difficulty was that the value I get after the @JavascriptInterface, and it appeared in the method, but with the post above I solved my problem and went around the scope - Sergey Zelensky