Search code examples
javaandroidfragmentsettext

SetText in fragment from outside class


I have a fragment that displays data from APIs, but i dont want to be calling apis everytime the fragment is called.. so am making api call from a different class and and calling a method in the fragment to update UI (textViews) but am getting null exception for the textViews but data is 100% there

and if i try to hardcode textView.setText("Hello") it works..


Solution

  • one of the task of fragment is change ui !!! you must change ui in activity or fragment

    you must use interface . your server class :

    public class server {
       .
       .
       .
       public void callServer(IServerResponse iResponse){
               .
               .
               . 
               
             iResponse.onResponse(//your data such as List or string or json and etc);
             }
    
        public interface IServerResponse{
                 // use parameter type as you want like List or string ,etc..
             void onResponse(String data);
            }
    
     }
    

    your fragment or activity implement your interface :

    public class SomeFragment extends Fragment implements Server.IServerResponse{
        .... 
    
       @Override  
       public View onCreateView(...){
          ...
          Server server=new Server();
          server.callServer(this);
        }
    
      @Override  
      public void IServerResponse(String data){
          textview.SetText(data);
    
       }
       
      
    
      }