A
A
amimamoya2021-06-02 20:10:14
Java
amimamoya, 2021-06-02 20:10:14

How to start an Activity not from an Activity?

I know, there is a similar question with an answer here on Habré, and a couple more on the Internet, but they don’t work for me, I ran into a slightly different situation ...
I have a ListView in MainActivity , I created my own adapter for it, and from With this adapter, I need to launch another activity, that is, by pressing a button from the ListView. In many ways I tried to get the first argument for the Intent constructor, but I always got a similar error: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference.
Can anyone suggest a way to launch another activity? Or is it possible to somehow handle the button click from the ListView not from the adapter, but from the MainActivity? It's just that if you try to put a listener for the button from the ListView, it will also give an error that this is a reference to a null object.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-06-02
@amimamoya

First, don't use ListView, it's deprecated. Use RecyclerView.
Secondly, launching an activity from an adapter is wrong, SRP is violated. You need to set the listener and open the activity using the callback.
Thirdly, most likely, you do not need a new activity, you need to open a new screen using a fragment (unless, of course, you call a third-party application).
Fourth, "the same leg and does not hurt", that is, how are we supposed to guess about your "many ways"?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question