Search code examples
androiddynamicnullpointerexceptionimageviewfragment

Changing ImageView inside Fragment Dynamically - Or Generating Fragment Dynamically?


I am new starter at android programming. Although I searched this problem on achieve I couldn't find any satisfying solution:

The problem is: I want to set an image to imageview - which is located in a fragment - dynamically.

And I want to do this using file name of the image.

But I am getting that NullPointerException:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference

Below my code are shown. I would be glad if anyone respond.

Activity class:

public class Oku extends AppCompatActivity {

    private int hedefSayi;
    private int actualNumber;
    private FragmentManager fragmentManager;
    private Fragment tempFragment;
    private BottomNavigationView bottomNavigationView;
    private FrameLayout fragmentContainer;
    private ProgressBar progressBar;
    private Button btn_tıkla;
    private Vird comingVird;
    private Fragment arabicImageFragment;
    private Fragment turkishTextFragment;
    private Fragment anlamFragment;

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

        comingVird= (Vird) getIntent().getSerializableExtra("Vird.class");

        hedefSayi=200;
        actualNumber=hedefSayi;
        fragmentContainer=findViewById(R.id.fragment_container);
        bottomNavigationView=findViewById(R.id.bottom_navi);
        arabicImageFragment=new Fragment_Arabic_Image(comingVird.getImageName());
        
        //put the arabic image fragment on the container first
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,arabicImageFragment).commit();
       
        //on navigation item selected:
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                
                //get the selected items id number
                int itemID=item.getItemId();

                //if id number is related to the arabic image fragment, set the temp fragment as arabic image fragment
                if(itemID==R.id.action_oku_arapca){
                    tempFragment=new Fragment_Arabic_Image(comingVird.getImageName());
                }

                //if id number is related to turkish text fragment, set the related fragment
                else if(itemID==R.id.action_oku_turkce) { tempFragment=new Fragment_Turkce_Okunus();}

                //if id number is related to the meaning set related fragment..
                else if(itemID==R.id.action_oku_anlamı){ tempFragment=new Fragment_Anlam();}

                //replace the fragment on the container with the temp fragment
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,tempFragment).commit();

                return true;

                }
            });

        //initiate progress bar with full progress
        progressBar=findViewById(R.id.progressBar);
        progressBar.setProgress(100);

        btn_tıkla=findViewById(R.id.button_tıkla);
        btn_tıkla.setText(""+actualNumber);

        //on button click
        btn_tıkla.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressBar.setProgress(100*actualNumber/hedefSayi);

                //decrease the number and set on the text of the button
                actualNumber--;
                btn_tıkla.setText(""+actualNumber);

                //her button tıklamada kısa titreşim ver
                Vibrator vb = (Vibrator)   getSystemService(Context.VIBRATOR_SERVICE);
                vb.vibrate(100);
            }
        });
    }
}

Fragment Class:

public class Fragment_Arabic_Image extends Fragment {

private String imageName;
private ImageView arabicText_Image;
private int imageid;


public Fragment_Arabic_Image(String imageName) {

    this.imageName = imageName;

}

@SuppressLint("ResourceType")
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view=inflater.inflate(R.layout.fragment_arabic_image,container,false);
    imageid=getActivity().getResources().getIdentifier(imageName,"drawable",getActivity().getPackageName());
    arabicText_Image=view.findViewById(R.id.img_arabic_text);
    arabicText_Image.setImageResource(this.imageid);//this line causes error

    return view;
}
}

Error message:

2020-08-04 14:11:18.822 12101-12101/com.codeforlite.virdlerim E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.codeforlite.virdlerim, PID: 12101

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference

at com.codeforlite.virdlerim.Fragment_Arabic_Image.onCreateView(Fragment_Arabic_Image.java:46)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1433)
at android.app.Activity.performStart(Activity.java:7980)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3578)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2220)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:8016)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1087)


Solution

  • It seems like ImageView arabicText_Image is not initialized properly. check fragment_arabic_image.xml. make sure ImageView has id attribute with value "img_arabic_text"

    <ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/img_arabic_text" />