How to run the click event on an image that is in Activity’s Fragment?

Asked

Viewed 731 times

0

I want to run the function that is Fragment - remove task() - on an image that is in Fragment being added in Activity at runtime, and I’m not getting, help me !!!

Code of the Activity

public class MainActivity extends AppCompatActivity {

private ImageView botao_deletar;
public static SQLiteDatabase banco_dados;

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

Code of the Fragment

public class ListaNotificacoes extends Fragment {

View minha_view;


private ListView lista_notify;
private ArrayAdapter<String> itens_adaptador;
private ArrayList<String> itens;
private ArrayList<Integer> ids;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    minha_view = inflater.inflate(R.layout.lista_notificacoes, container, false);
    return minha_view;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

private void remover_tarefa(Integer id){
    try {
        banco_dados.execSQL("DELETE FROM lista_notificacoes WHERE id="+id);
        recupera_tarefa();
    }catch (Exception e){
        e.printStackTrace();
    }
}

What I tried to do...

public class ListaNotificacoes extends Fragment {

View minha_view;


private ListView lista_notify;
private ImageView botao_deletar;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    minha_view = inflater.inflate(R.layout.lista_notificacoes, container, false);
    return minha_view;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    recupera_tarefa();

    botao_deletar = (ImageView) getActivity().findViewById(R.id.botao_deletar);

    botao_deletar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            remover_tarefa(lista_notify.getId());
        }
    });
}

private void remover_tarefa(Integer id){
    try {
        banco_dados.execSQL("DELETE FROM lista_notificacoes WHERE id="+id);
        recupera_tarefa();
    }catch (Exception e){
        e.printStackTrace();
    }
}

The error that shows on the console...

Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
  • What’s the problem? What happens?

  • I’ll edit the question and I’ll put what I tried to do so you can help me... pera

  • To ImageView is in Activity or Fragment layout?

  • in the layout of the Fragment

2 answers

1

I’m going to assume you’re not getting your reference ImageView in your code, ok?

If I’m wrong, let me know. Anyway, what do you do to get the reference of widget is to use the myview as an identifier.

The method findViewById() can be called two ways:

View.findViewById()
Activity.findViewById() || Context.findViewById() ~ Context as Activity.

In fragments, we need to pass a identificador so that the method can find its view, if we don’t pass, it won’t work, since you’re not in an Activity.

Your final code would look like this:

Button deleteTask;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    minha_view = inflater.inflate(R.layout.lista_notificacoes, container, false);

    deleteTask = (Button) minha_view.findViewById(R.id.action_delete_task) // mude para o Id do seu componente
    deleteTask.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            remover_tarefa(taskId);
        }
    });

    return minha_view;
}

If you are using Java 8, you can use Lambda Expressions to write less and avoid Boilerplate code. Your code would look like this:

deleteTask = (Button) minha_view.findViewById(R.id.action_delete_task)
deleteTask.setOnClickListener(v -> remover_tarefa(taskId))

To be able to use Lambda Expressions, you need to enable compatibility with the Java 8. To do this, you need to modify the build.gradle at the level of application, that is to say in the module app.

android {
    ...
    defaultConfig {
    ...
        jackOptions {
           enabled true
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
 }
  • continued the same mistake, helps me !!! I do not know what to do...

0

You are getting this error because in the method onActivityCreated of your fragment, you are seeking a vision in your activity, but it belongs to your fragment.

Fragment Lifecycle

If you analyze the life cycle of a fragment, the method onActivityCreated is executed after the onCreateView, which means that in it you already have the inflated vision and can already use it.

Just change your code, and change it getActivity() for getView(), in the method onActivityCreated of your fragment:

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    recupera_tarefa();

    botao_deletar = (ImageView) getView().findViewById(R.id.botao_deletar);

    botao_deletar.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            remover_tarefa(lista_notify.getId());
        }
    });
}

Note: There must actually be a view with the id R.id.botao_deletar in the layout (R.layout.lista_notificacoes) which is inflated by its fragment, lest a Nullpointerexception.

  • in its final note I kept thinking about it, because it has no imageview with this id in the layout, but only that within this layout has a listview that is being populated with another layout that has the imageView with that id, will be that the problem is this ?

  • Then you should get this event on the Adapter that handles your list. You can update the question with it?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.