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?
Related
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);
}
My project have a activity named MainActivity and a BrowserActivity extend dialog service.
MainActivity will intent BrowserActivity on application started.
I would like to BrowserActivity can access MainActivity's public method.
something like that:
Method on MainActivity:
public void chooseShare(Intent intent)
{
try
{
startActivityForResult( intent , PICK_SHARE);
} catch (android.content.ActivityNotFoundException ex)
{
Log.e("Share" , ex.getMessage());
}
}
And i want to do on BrowserActivity :
(Pseudocode)
((MainActivity)BrowserActivity.this.getOwnerActivity()).chooseShare(intent);
I try to do that:
MainActivity ma = new MainActivity();
ma.chooseShare(i);
However, it not work, it throw NULLPointerException.
Because i need startActivityForResult() instead of startActivity() for callback result.
And i digg on SOF, i found startActivityForResult() should be start on Activity, but not Dialog.
thanks you.
You should be able to use getParent() if it's within the same project.
Activity parent = getParent();
if (parent instanceof MainActivity)
((MainActivity)parent).chooseShare(i);
Another option would be to bind it with an ibinder and use a service or implement interfaces.
Services | Android Developers
you can access all classes method like this:
Context context;
public ProceedDialog(#NonNull Context context) {
super(context);
this.context = context;
//do something
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//do something
}
#Override
public void onClick(View view) {
ParentActivity activity = (ParentActivity)context;
activity.method();
}
I had the same question. And I found a partial solution.
The key is that Activity is a subclass of Context.
You pass the Context paraneter to the constructor of your dialog, right?
And most people pass it by using this of MainActivity.
So, I used the following codes to get MainActivity reference.
private MainActivity getMainActivity()
{
Context c= getContext();
if( c instanceof MainActivity)
{
return (MainActivity)c;
}
return null;
}
Then you can call the desired method by
this.getMainActivity().chooseShare(intent);
In the dialog.
I tested this and it works!
Hope it helped you or forecomers.
(I saw the last modification date just now)
I've made a separate class to launch and intent as the class I would like to launch the intent from is a thread and does not inherit from activity and would not launch startActivity. Every time I launch the app I get a null pointer exception for the context.
public class ToLaunch extends Activity {
public void launchScoreloop() {
con.getApplicationContext();
startActivity(new Intent(this, LeaderboardsScreenActivity.class));
}
}
You Are writing an Activity , and you didn't override the method onCreate().
public class ToLaunch extends Activity {
#override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Call your method here after a button click cor example or something else
}
public void launchScoreloop() {
con.getApplicationContext();
startActivity(new Intent(this, LeaderboardsScreenActivity.class));
}
}
refer this two tutorials about using intents to start another Activity :
tuto 1
tuto 2
And if you want to launch the Activity from another Class , you should pass the context to the second Class like this :
SecondClass instance = new SecondClass(this);
and the contructor of your SecondClass will be something like this :
public void SecondClass(Context _context){
this.context = _context;
}
and then you can start the Avtivity by using the context that you passed to your SecondClass like this :
this.context.startActivity(....);
If thread is a inner class inside your activity you can use
startActivity(new Intent(YourActivity.this, LeaderboardsScreenActivity.class));
If it is a separate class you can make a constructor that take context has constructor as argument and you can pass your activity context into that constructor
Context con;
public YourThread(Context context){
con = context;
}
and from inside your activity, while making thread object
YourThread thread = new YourThread(this);
I want call an activity class from a normal java class(without extends anything) for every some time interval to refresh the Ui, Is it possible to call an activity from normal java class. We can call the activity from another activity using intent and startactivity. But am not sure about calling the activity from class.
For example
class example extends Activity
{
}
class example2 extends Activity
{
// we can call like
Intent intent = new Intent(this.example2,example.class);
startActivity(intent);
}
class test
{
// How can i call example or example2 from here.
}
Thanks,
Lakshmanan
You could provide a parameter consisting of the context of your Activity that has been creating the Object. Then you can use the Context's methods just like within an Activity.
i.g.
public class Foo {
private Context context;
public Foo(Context context) {
this.context = context;
}
public void startActivity() {
context.startActivity(/*your intent here*/);
}
}
Intent intent12 = new Intent(context.getApplicationContext(), ImageClick.class);
context.startActivity(intent12);
It works. I've tried.
I use this to view you tube videos from a non activity class -
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // important step
context.startActivity(intent);
Hope this helps you.
Salil.
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).