change textview when change static string variable in android

android change string resource programmatically
android dynamic string resource
android global variables best practice
how to change string value in android
android string resource %
android studio global variable for all activities
android application variables
android two-way data binding livedata

This is my main class. change textview settext when static text change in another class. Note: this process will be applied for several views

public class MainActivity extends AppCompatActivity {

        public static String text = "123";
        Button btn;
        TextView txt;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
             txt = findViewById(R.id.txt);
             txt.setText(text);

        }
    }

Another class

public class AnotherClass{  
 public void changeTextViewText(){

   MainActivity.text = "bulut";
}

Its not recommended to use static in Activity class because it can cause memory leak. But if you must, then make the static in your TextView not your String. Something like :

public class MainActivity extends AppCompatActivity {

        public static String text = "123";
        Button btn;
        public static TextView txt;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
             txt = findViewById(R.id.txt);
             txt.setText(text);

        }
    }

Then in your another class

public class AnotherClass{  
 public void changeTextViewText(){

   MainActivity.txt.setText("bulut");
}

Recommended way

Make a constructor in your another class like :

public class AnotherClass{
  MainActivity mainActivity;
  public AnotherClass(MainActivity mainActivity) {
     this.mainActivity = mainActivity;
  }

  public void changeTextViewText() {
     mainActivity.getTxt().setText("bulut");
  }
}

And in your MainActivity : public class MainActivity extends AppCompatActivity {

    public static String text = "123";
    Button btn;
    TextView txt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         txt = findViewById(R.id.txt);
         txt.setText(text);

    }

    public TextView getTxt() {
        return txt;
    }
}

Dynamically change bundled strings - Hamid Gharehdaghi, Providing string resources as XML files is how we manage static texts of an application in Android. us to change this static bundled text dynamically and from server-side. But this is not that easy(or let's say clean) in Android. There is a few ways you can do it. The best way from my view is to do it from your activity class, if you dont want to do that. You will have to pass the "TextView" object to your method, that way you can change it like you would normally. So: private void updateScreen(TextView textview){ // the textview text change code here }

You should update your textview when you change your String. In your case, observer pattern is a good design pattern to accomplish this. Basic approach:

//create a class that stores object. 
public class Observer{
  private static Observer instance = new Observer();
  private HashMap<String,TextView> map;
  public static Observer getInstance(){
      return instance;
  }
  private Observer(){
    map = new HashMap<>();
  }
  public static void subscribe(String viewKey, TextView view){
    Observer observer = getInstance();
    observer.map.put(viewKey, view);  
  }
  public static void changeText(String viewKey, String text){
      Observer observer = getInstance();
      if(observer.map.containsKey(viewKey)){
          TextView textView = observer.map.get(viewKey);
          textView.setText(text);
      }else{
        // throw exception 
      }
  }

  // in your activity do this
  Observer.subscribe("Main text view", txt);

  // in your other classes simply do 
  Observer.changeText("Main text view", "bulut");

Of course you can use some libraries to accomplish this as well such as https://github.com/ReactiveX/RxAndroid . Or send your textview to your other classes as parameter of course

Global Variable Or Application Context Variable, In this example defining variable in application context and you can use this variable as a Global variable. You can achieve this by creating static variable but it is not the good way it influencing towards public void setName(String aName) { import android.widget.TextView;. public class SecondScreen extends Activity {. Overview; Android Platform; Android Support Library; AndroidX; AndroidX Test; AndroidX Constraint Layout; Architecture Components; Jetpack Compose UI; Android Automotive Library

Prevent Memory Leaks and do not reference Contexts(Activities)

Interface callbacks method

Better Approach would be :

Make a interface:

interface TextUpdater{
void updateText(String text);
}

and implement it on your Activity, or create a instance of it

example:

Implementation method:

MainActivity extends... implements TextUpdater{
...
..


    @overRide 
  void updateText(String text){
   textView.setText(text);
}

Instance method:

TextUpdater textUpdater = new TextUpdater(){

    @overRide 
  void updateText(String text){
   textView.setText(text);
}
}

Finally add your interface instance to the other class via constructor or setter method.

ex1:  otherClass.setUpdater(this)  // (implementation case)
ex2:  otherClass otherclass = new OtherClass(this) 
 // if you make a instance of interface then use it (change 'this')

In your other class make a reference to interface:

 OtherClass {

  TextUpdater textUpdater...

 add constructor or do  setter...

and then call the interface like

textUpdater.updateText("Your String")

Notes: Make sure you run on UI Thread

LiveData method: (Better option)

OtherClass .. {



  MutableLiveData<String> textLiveData = new MutableLiveData()
     ...
     void changeText(String text){
      textLiveData.setValue(text)
     } 

Main Activity ...

otherClass.getTextLiveData().observe(this,Observer<String>() {
  @Override
  public void onChanged(final String text) {
    textView.setText(text)
  } 
  )}

Update your text like:

otherClass.changeText("Your text")

How to declare global variables in Android?, Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all How to change the text color of Menu item in Android? In the above code, we have taken text view to show global variable. public class singleToneClass { String s; private static final singleToneClass ourInstance  As an argument of setText() we could also use a String variable (so the variable storing a text). First define a variable (for instance named newText), then assign some text to it and finally set this text to TextView.

Two-Way Data Binding on Android: Observing Your View with XML , Android. If you've used Data Binding in an Android app before, you'll know how it <data> <variable name="viewModel" type="com.example. Just like you can bind a String to an EditText, you can also bind a TextWatcher to an EditText. And update the EditText in your layout to look like this instead:. In this video I take a look at using TextViews and Strings for Skip navigation HOW TO SHOW HTML INSIDE TEXTVIEW - Android Development 05 How To Add String Resources - Android Studio

Kotlin Android TextView and EditText, Kotlin Android TextView and EditText with introduction, architecture, class, Location Google Map Fixed Location Google Map Search Location Android Web Service We can get and modify the content of text view defined in the XML layout in Kotlin class file as setOnClickListener(){; val inputValue: String = editText.text. A blogger, a bit of tech freak and a software developer. He is a thought leader in the fusion of design and mobile technologies. He is the author of Xamarin Mobile Application Development for Android Book (goo.gl/qUZ0XV3), DZone MVB and founder of stacktips.com.

Store strings of EditText and use in another class, Declare and initialize a private static final String variable for each did not change the way you declared and initialized your EditText variables  This example demonstrates about how and where do I use static variable in android studio. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project

Comments
  • How about setter?
  • Why don't you use an interface if it has to be done for several views? Making every view static is not recommended
  • my views are not static. but variables have to be static. calling from a few different class
  • @FatihBulut i added 2 different approaches, if you need more information on them, let me know. :)
  • i have edited to add recommended way
  • It's not recommended to use static views in Activity but there's nothing wrong about using static finals like a RequestCode
  • as I mentioned the question had worked for the fragment. But I can't remember how I'm doing now.