Home > Mobile >  SetText in fragment from outside class
SetText in fragment from outside class

Time:10-17

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..

CodePudding user response:

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);

   }
   
  

  }

CodePudding user response:

You should create a FrameLayout in your activity And use this code:

FragmentA newFragment = new FragmentA ();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.container, newFragment).commit();

and than set your text

String editValueName= editName.getText().toString();
String lastStatus = valueStatus.getText().toString();
newFragment .setText(editValueName, lastStatus);

CodePudding user response:

Try for quick fix if it is working for the output of your desire
Make Textview static in class(youractivity) where textview is originated like
public static TextView textview;

And in fragment
if(youractivity.textView!=null){ youractivity.textView.setText("your desire text"); }

  • Related