Search code examples
androidandroid-studio-2.0

How to change TextView text persistently in Android?


I've tried using Thread, but it was unsuccessful, the textView didn't changed after I change the TextView text using EditText as input. Help me, please!

        Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            //shared is SharedPreferences object that I define as an instance variable
            String inp = shared.getString("input", def);

            textView.setText(inp);
            Log.d("input",inp);
    });

    thread.start();

Solution

  • try this:

        Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            //shared is SharedPreferences object that I define as an instance variable
            String inp = shared.getString("input", def);
             runOnUiThread(new Runnable() {
    
                        @Override
                        public void run() {
    
                            textView.setText(inp);
                            Log.d("input",inp);
                        }
                    });
    });
    
    thread.start();
    

    for updating UI you should use the main ui thread. take a look at :

    Android runOnUiThread explanation