'App with fragment.settext of textview stop working with nullpointer on textview

In my app i set fragment.textview text from mainactivyti class and today it just fall with that error

Solved by changing <androidx.fragment.app.FragmentContainerView /> in start.xml to < fragment />

I rly dont know thats the point is.

It work's great with fragmentW ( fragmentB). edittext_path ( textView ) . setText("anyText") bu now it cathes null pointer exception and fragment.getView is also null

My classe's code below:

FileChooserFragment:


    private static final int MY_REQUEST_CODE_PERMISSION = 1000;
    private static final int MY_RESULT_CODE_FILECHOOSER = 2000;

    private Button buttonBrowse;
    public TextView editTextPath;

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
       View rootView = inflater.inflate(R.layout.fragment_file_chooser, container, false);
        this.editTextPath = rootView.findViewById(R.id.editText_path);
        this.buttonBrowse = rootView.findViewById(R.id.button_browse);
        this.buttonBrowse.setOnClickListener(view -> askPermissionAndBrowseFile());
        return rootView;
    }



    private void askPermissionAndBrowseFile()  {
        // With Android Level >= 23, you have to ask the user
        // for permission to access External Storage.
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { // Level 23

            // Check if we have Call permission
            int permisson = ActivityCompat.checkSelfPermission(this.getContext(),
                    Manifest.permission.READ_EXTERNAL_STORAGE);

            if (permisson != PackageManager.PERMISSION_GRANTED) {
                // If don't have permission so prompt the user.
                this.requestPermissions(
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_REQUEST_CODE_PERMISSION
                );
                return;
            }
        }
        this.doBrowseFile();
    }

    private void doBrowseFile()  {
        Intent chooseFileIntent = new Intent(Intent.ACTION_GET_CONTENT);
        chooseFileIntent.setType("*/*");
        // Only return URIs that can be opened with ContentResolver
        chooseFileIntent.addCategory(Intent.CATEGORY_OPENABLE);

        chooseFileIntent = Intent.createChooser(chooseFileIntent, "Choose a file");
        startActivityForResult(chooseFileIntent, MY_RESULT_CODE_FILECHOOSER);
    }

    // When you have the request results
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //
        switch (requestCode) {
            case MY_REQUEST_CODE_PERMISSION: {

                // Note: If request is cancelled, the result arrays are empty.
                // Permissions granted (CALL_PHONE).
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    Toast.makeText(this.getContext(), "Permission granted!", Toast.LENGTH_SHORT).show();

                    this.doBrowseFile();
                }
                // Cancelled or denied.
                else {
                    Toast.makeText(this.getContext(), "Permission denied!", Toast.LENGTH_SHORT).show();
                }
                break;
            }
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case MY_RESULT_CODE_FILECHOOSER:
                if (resultCode == Activity.RESULT_OK ) {
                    if(data != null)  {
                        Uri fileUri = data.getData();

                        String filePath = null;
                        try {
                            filePath = FileUtils.getPath(this.getContext(),fileUri);
                        } catch (Exception e) {
                            Toast.makeText(this.getContext(), "Error: " + e, Toast.LENGTH_SHORT).show();
                        }
                        this.editTextPath.setText(filePath);
                    }
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public String getPath()  {
        return this.editTextPath.getText().toString();
    }
}

Fragment xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:dividerPadding="5sp"
    tools:context=".FileChooserFragment">

    <TextView
        android:id="@+id/editText_path"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10"
        android:inputType="textUri" />

    <Button
        android:id="@+id/button_browse"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="Browse" />
</LinearLayout>

MainActivity:


    FileChooserFragment fragmentW;
    FileChooserFragment fragmentB;
    EditText editText;
    private Button nextAct;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.start);

        this.fragmentW = (FileChooserFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_fileChooser);
        this.fragmentB = (FileChooserFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_fileChoose2r);
        fragmentW.editTextPath.setText("123"); // nullpointer here
        editText = findViewById(R.id.editText);
        this.nextAct = this.findViewById(R.id.nextAct);
        nextAct.setOnClickListener(view -> {
            String editTextText = String.valueOf(editText.getText());
            Intent intent = new Intent(getApplicationContext(),AllStuffActivity.class);
            intent.putExtra("wheelsFilePath",fragmentW.getPath());
            intent.putExtra("bringsFilePath",fragmentB.getPath());
            intent.putExtra("searchQ",editTextText);
            startActivity(intent);
        });
    }

main activity .xml (start.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="5sp"
    android:paddingTop="5sp"
    android:paddingRight="5sp"
    android:paddingBottom="5sp"
    tools:context=".MainActivity" >

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragment_fileChooser"
        android:name="com.example.donttouchthis.FileChooserFragment"
        android:layout_width="0dp"
        android:layout_height="45dp"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragment_fileChoose2r"
        android:name="com.example.donttouchthis.FileChooserFragment"
        android:layout_width="0dp"
        android:layout_height="45dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="76dp"
        android:layout_marginEnd="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.444"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:minHeight="48dp"
        app:layout_constraintBottom_toTopOf="@+id/nextAct"
        app:layout_constraintTop_toBottomOf="@+id/fragment_fileChoose2r"
        tools:layout_editor_absoluteX="4dp" />

    <Button
        android:id="@+id/nextAct"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="104dp"
        android:text="Go next"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/fragment_fileChooser" />
</androidx.constraintlayout.widget.ConstraintLayout>```


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source