access a view that is in a fragment from activity?

1

I want to access from the main activity a Button that is in a fragment by means of this code:

Button button = blankFragment.getView().findViewById(R.id.btnFragment);

but I get the following error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
    at com.example.brynner.comunicationfragmentactivity.MainActivity.onCreate(MainActivity.java:27)
    at android.app.Activity.performCreate(Activity.java:6662)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)

Someone could please help me, I'll give you the complete code.

MainActivity.java

public class MainActivity extends AppCompatActivity implements 
BlankFragment.OnFragmentInteractionListener{

private BlankFragment blankFragment;
private EditText editTextActivity;
private Button buttonActivity, buttonConnectFragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    blankFragment = new BlankFragment();

    editTextActivity = findViewById(R.id.edtxtActivity);
    buttonActivity = findViewById(R.id.btnActivity);

    getSupportFragmentManager().beginTransaction().add(R.id.frameContainer, blankFragment).commit();

    Button button = blankFragment.getView().findViewById(R.id.btnFragment);
    button.setText("Conectado");

}

@Override
public void onFragmentInteraction(Uri uri) {

}
}
    
asked by Leonidas 28.12.2018 в 04:23
source

1 answer

1

After several attempts and I could solve the problem I will leave the answer in case someone else needs it.

The problem is that the code:

 Button button = blankFragment.getView().findViewById(R.id.btnFragment);

only works if it is within OnClickListener() otherwise it will always give an error.

    
answered by 28.12.2018 / 05:07
source