Why does getPackageManager return null - android

So I am trying to start another app my inside my AccessibilityService but I keep getting the following java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference even though I use the same method in my MainActivity.class and it works fine. And I know the package name is correct, cause like I said I call it in MainActivity.class
This is the class where I call the function.
public class myAdapter extends Application
{
private void turnOn(String text)
{
Intent b = getPackageManager().getLaunchIntentForPackage(text);
startActivity(b);
}
}
I have tried the various ways to call this same function.
Intent b = getApplicationContext().getgetPackageManager().getLaunchIntentForPackage(appName);
getApplicationContext().startActivity(b);
Intent b = getApplicationContext().getgetPackageManager().getLaunchIntentForPackage(appName);
getApplicationContext().startActivity(b);
My Logcat:
Process: com.tech.myApp, PID: 17195
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
at com.tech.myApp.turnOn(myAdapter.java:198)

You say that you're trying to start an Activity from an AccessibilityService, yet your code very clearly shows that your class is extending Application. This is confusing and also likely one of the core issues you're having regarding these NullPointerExceptions. I am going to state my answer assuming that you are indeed attempting this from an AccessibilityService class, as mentioned in the description of your issue, even though this very much conflicts with the code you have posted. If this is indeed the case, you should update this question to clarify. If this answer does not help you, your question needs considerable TLC.
Once we realize that we're within an AccessibilityService, we see that there is a MUCH simpler way to accomplish starting an activity. Starting another Activity within an AccessibilityService is as simple as the following code snippet:
public class A11yService extends AccessibilityService {
void startMainActivityFromService() {
final Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
Easy as that!

Okay so what I had to do was on my MainActivity.class was create a static context. Which then I could pull from any other class even the ones that run in the background.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivity.context = getApplicationContext();
// CALL MY FUCTION - THIS COULD BE ANYWHERE NOW
startApp(app name you want to start);
}
}
Then in my other classes or activities or services I use this:
public static void startApp(String appName)
{
// MAKE SURE TO GET THE CONTEXT
Context context = MainActivity.getAppContext();
Intent b = context.getPackageManager().getLaunchIntentForPackage(appName);
context.startActivity(b);
}

Related

How to correctly call a method between activities?

In the ActivityA.java, I have tryAgain() method that calls the goToGame() method from ActivityB.java.
ActivityA.java
public void tryAgain(View view) {
ActivityB activityB = new ActivityB();
activityB.goToGame(view);
}
I get the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
because in ActivityB.goToGame() there is the following string:
Intent intent = new Intent(getApplicationContext(), GameActivity.class);
I think that the error is due to a wrong argument of activityB.goToGame() or to getApplicationContext() of the intent.
In similar questions, the solution suggested is to use static but I face a lot of other issues with this solution.
EDIT
Consider that:
I cannot make goToGame() as static
I cannot change the argument goToGame() that as to remain View
I cannot make goToGame() return anything
to call a method from your ActivityB with the right way, you can do something like this
add this your ActivityB
public static Intent goToGame(Context context) {
//here do the things you want to
return new Intent(context, GameActivity.class);
}
Wherever you want to open GameActivity over ActivityB, use this
startActivity(ActivityB.goToGame(this));
so this style is not right
ActivityB activityB = new ActivityB();
activityB.goToGame(view);
do it like this
public void tryAgain(View view) {
startActivity(ActivityB.goToGame(this));
}
hope it helps!

Using intent in a public function

I've a method which is making a huge calculation and then calls an intent as follows
public void sampleMethod(final Context cont)
{
.
.
(huge calculation [50-80 lines])
.
.
Intent intent = new Intent(cont, TimesheetMain.class);
finish();
startActivity(intent);
}
This is present in Activity 'SampleActivity'. When I'm trying to access it through on object of Activity 'SampleActivity' from Activity 'B' as follows:
Context context = this;
SampleActivity sa = new SampleActivity();
sa.sampleMethod(context);
I'm getting a NullPointerException at the startActivity line of code while accessing it from Activity 'B'. I can't figure out where am i going wrong in here. Please help me out
EDIT 2
This seem to work when i added context to it like cont.startActivity(intent), but i need to know why shouldn't i use another class or another activity's function in a secondary class? Is the android framework is the reason? I've been doing this (without the intent part) for the past two months or so, i never faced any sudden force close issues in either emulator or in device(Nextbook professional 7 SE); Please explain it with a legit example
You're not supposed to create explicit instances of activities by yourself as you're doing like this:
SampleActivity sa = new SampleActivity();
Please provide a better description for your problem and what you want to achieve with the outcome of this issue.
try the follwng updated code:
public void sampleMethod(final Activity cont)
{
Intent intent = new Intent(cont, TimesheetMain.class);
cont.finish();
cont.startActivity(intent);
}
also move this method to a util class and call it from activity and pass the activity reference as follows
class ActivityB extends Activity
{
.
.
.
Util.sampleMethod(this);
}

Launch Android activity from non-activity class

I'm using a third-party application that just launches a class that extends another normal class.
So, from that class I would like to launch an activity:
public class SkyTest extends VtiUserExit {
#Override
public VtiUserExitResult execute() throws VtiExitException {
// TODO Auto-generated method stub
logInfo("TEST");
return null;
}
}
How do I launch an activity named MainActivity from here?
I tried this:
Context context = null;
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
but it's not working. I know I can't use the null context, but how do I create a context so it works?
A null context doesn't work because Android needs that Application Context in order to find your Activity. I don't know which framework you are using, but you should look for a way to grab a reference to the Context, have you gone through the API for the class you're extending?

Finish Activity() from a separate myJavaClass.java

I have tried almost all the solutions from SO but no success :(.
I have a simple myJavaClass.java with a couple of functions.
One of the functions in myJavaClass : startActivity() starts MyCustomActivity
public startActivity(Context context)
{
Intent intent = new Intent(context, MyCustomActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(intent);
}
This launches MyCustomActivity() as expected.
Now I have another function in myJavaClass.java to close/finish MyCustomActivity but it is not able to do so!
I have tried
Making MyCustomActivity SingleTop in manifest and creating the activity via an intent as above
Passing an activity instance to "this" in onCreate() of MyCustomActivity and calling MyCustomActivity.activity.finish() from myJava.class but that doesnt work as well
Please help me. I have been stuck here for hours now. I know the solution is very simple and conceptual but I am a newbie. Just building Java/Android concepts!
EDIT
MyCustomActivity
public Activity activity;
OnCreate()
{
...
this = activity;
}
MyJavaClass
public closeActivity(Context context)
{
Activity customActivity = MyCustomActivity.activity;
customActivity.finish();
}
I think that what you are trying to do is fundamentally bad. For a start, outside of the Activity code, there are no guarantees that the activity still exists - the memory manager may have cleaned it up, the user may have pressed Back etc. Think of Activities as independent entities - you can start them, and you can optionally get a result back when they finish what they're doing, but that's it.
Think about whether you really have to programmatically close the activity from outside it - I'd say this is an unusual design, but there are circumstances where it may be appropriate.
If so, what I think you want is a publish/subscribe system whereby MyCustomActivity can register a listener with MyJavaClass, and then receive a callback whereupon it can 'finish' itself.
public Activity activity implements FinishListener
{
public void onCreate(...)
{
//where does MyJavaClass come from? see in a minute
MyJavaClass myjava = getMyJavaclass();
myJava.addFinishListener( this );
}
public void onFinishCallback()
{
this.finish();
}
}
and
public class MyJavaClass
{
private List<FinishListener> finishListeners = ...;
public void addFinishListener( FinishListener fl )
{
this.finishListeners.add(fl);
}
public closeActivity(Context context)
{
for ( FinishListener fl : finishListeners )
{
fl.onFinishCallback();
}
}
}
and
public interface FinishListener
{
void onFinishCallback();
}
Now the only remaining issue is how to get MyJavaClass from the Activity. That's up to you - you may already know how, you may be able to put it in your Application implementation, it could be a singleton (bad), the listeners could be static (bad) or various other options.
Oh, and don't forget to remove the listener again in the Activity's onDestroy() method!
Just try this....
public closeActivity(Activity _activity)
{
_activity.finish();
}
you can't finish activity from other class until you have the reference of instance of Activity in that class, give the reference in that class and call finish() method to stop the activity.
activity.finish();

New Activity nullpointerexception

I have a beginners problem. Here is my situation:
I want to start a new activity from the main activity. The code to launch the new activity is found in a separate class file. I seem to be passing the wrong arguments and I am ending up in a nullpointerexception when trying to launch the new activity. The new activity launches fine when I place the code in the main activity class file, therefore the second activity and the manifest are fine. Here is a sample of my code:
In my main activity class where I instanciate the second class (THIS IS MY MAIN ACTIVITY. I OMITTED THE REST BECAUSE I DO NOT THINK IT IS RELATED TO THE PROBLEM):
Tester mytest = new Tester();
mytest.test(this);
In my second class file (THIS IS NOT AN ACTIVITY; IT IS A CLASS THAT IS INSTANTIATED IN THE ACTIVITY):
public class Tester extends Activity {
Intent myIntent;
public void test (Context context) {
myIntent = new Intent (Intent.ACTION_VIEW);
myIntent.setClass(context, newActivity.class);
thebutton.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
startActivity(myIntent);
}
}
):}
When I perform the click I receive a nullpointerexception at startactivity. Can anyone enlighten me on this please?I am sure that I am wrongly using the context.
Activities are started with Intents. Please read the Android Application Fundamentals first and try the Hello World app :)
I understood that you will use your separate Tester class at all cost ;) so I'm trying to adapt and help you out there.
First of all, don't let your class inherit from Activity. This won't help you, cause this calls will probably not have any valid context. Activity somehow implements the template pattern, providing you key method like onCreate(...), onPause(...) etc and is instantiated by the Android OS.
If you still want to use the class, you have to pass in the context. Probably you're aiming for some MVC/MVP pattern structure, anyway.
public class Tester {
private Context context;
public Tester(Context context){
this.context = context;
}
public void test () {
final Intent myIntent = new Intent(context, NewActivity.class);
//guess this comes from somewhere, hope through a findViewById method
thebutton.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
context.startActivity(myIntent);
}
}
)};
}
}
This would be a proposed solution from my side. A problem I still see here is on how you retrieve the button in that test() method. In order to have that work properly you have to retrieve it from some View class (with view.findViewByid(R.id.myButton)) or to create it dynamically and associate it with the view during the onCreate(...) of your Activity (probably using an Inflater).

Categories

Resources