How to execute the click event on an image that is in the activity fragment?

0

I want to execute the function that is fragment - remove task () - on an image that is in the fragment being added in the activity at runtime, and I am not getting it, help me !!!

Activity code

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

Fragment code

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 in the console ...

Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    
asked by anonymous 21.05.2017 / 17:01

2 answers

1

I'll assume you can not reference your ImageView in your code, okay?

If I'm wrong, let me know. Anyway, what you do to get the widget reference is to use my_view as the identifier.

The findViewById () method can be called in two ways:

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

In fragments , we need to pass identificador so that the method can find its view , if we do not pass, it will not work, since you are not in an activity.

Your final code looks 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're 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))

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

android {
    ...
    defaultConfig {
    ...
        jackOptions {
           enabled true
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
 }
    
21.05.2017 / 18:32
0

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

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

Just change your code, and change getActivity() to getView() , in the onActivityCreated method of your snippet:

@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 should actually be a view with the R.id.botao_deletar id in the layout ( R.layout.lista_notificacoes ) that is inflated by its snippet so that a NullPointerException .

    
21.05.2017 / 18:38