Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Jasmeet Singh
Jasmeet Singh
20,145 Points

My textView text is lost on rotating the screen twice.

when i rotate the screen from portrait to landscape it works fine my textview text is saved, but when i again rotate it back to portrait the text is lost and savedInstance and RestoreInstance becomes null. how do i fix that can someone help me.

    String yourstring="";
     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
           if (savedInstanceState != null) {
            String myString = savedInstanceState.getString("MyString"); //get it
            textView.setText(myString);
         } else {
            getString();
       }


        }
        private void getString(){
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(URL_MOVIE)
                    .build();

            client.newCall(request).enqueue(new Callback() {

                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {



                    res_120 = response.body().string();
                   runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        updateUI(res_120);
                                    }
                                });
                }
            });

        }

        void updateUI(String string) {
           textView.setText(string);
           yourstring=string;

        }
        @Override
        public void onSaveInstanceState(Bundle savedInstanceState) {



          savedInstanceState.putString("MyString", yourstring);  // save your instance

          // etc.  

          super.onSaveInstanceState(savedInstanceState);  
        }  

        //onRestoreInstanceState  

        @Override  
        public void onRestoreInstanceState(Bundle savedInstanceState) {  

          super.onRestoreInstanceState(savedInstanceState);  



          String myString = savedInstanceState.getString("MyString"); //get it
          textView.setText(myString);  
        }