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);
Related
I want to know how can I send the context of an activity from ClassA.java to MainAddingItems.java.
I can pass the MainActivity.class as the argument but I am not able to pass the context.
Here is some of the code of ClassA calling the constructor of MainAddingItems
new MainAddingItems(MainActivity.class,"MainActivity Clicked",R.id.activity_main_linearLayout,"Profile Acitvity")
It will work ..make sure that you declerad it as public and static like below
Public static Context context ;
In your main activity
You can use any where that context in whole project
You can do this. If your constructor is:
MainAddingItems(Context context) {...}
Then from Activity1 you can just do:
Context context = Activity1.this; // Or getApplicationContext() or View.getContext() or whatever context you want
MainAddingItems(context);
Make your MainAddingItem class's constructor as this,
class MainAddingItem {
Context context;
MainAddingItem (Context context, rest of the parameters){
this.context = context;
}
}
Use the above constructor and pass the activity's context in the constructor's parameter.
new MainAddingItem (this, rest of the parameters);
Actually you are passing the context here . In android context is the current state of application . As an example if you are in a activity, then the context is the activity class itself , same for service and any other component of android
Let me give another example ,
Just try to show a toast message in onCreate method of any activity , considering your activity name is SimpleActivity you may write something like this
Toast.makeText(this "Understating context",Toast.LENGTH_LONG).show();
Or you may write the following
Toast.makeText(SimpleActivity.this "Understating context",Toast.LENGTH_LONG).show();
The first parameter of makeText method is context , and it works if you simply pass the class .
This is how you will pass activity as an argument
public SimpleClass{
AppCompatActivity mActivity;
public SimpleClass(AppCompatActivity mActivity){
this.mActivity = mActivity;
}
}
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SimpleClass newSimpleClass = new SimpleClass(MainActivity.this);
}
}
Just make Context as static like in MainActivity.
Public static Context contextToUse;
You can use like below :
MainActivity.contextToUse
Please let me know ,if it is helpful to you
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'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?
I am currently working on an android project and I have an activity, lets call it MyActivity and this activity calls a standard Java class called MyClass.
I need MyClass to finish the MyActivity activity but I can't find out how to do this. I thought I might be able to pass the context to the standard java class and call context.finish() but this doesn't appear to be available.
How can I do this, thanks for any help you can offer.
You can pass the Context, but you will need to cast it to an Activity (or simply pass the Activity itself), although this in general seems like a bad practice.
The most secure solution uses listener and a Handler. It is complex, but ensures a non direct call to finish activity.
Your listener:
interface OnWantToCloseListener{
public void onWantToClose();
}
Class that should close activity.
class MyClass {
private OnWantToCloseListener listener;
public void setWantToCloseListener(OnWantToCloseListener listener){
this.listener = listener;
}
private void fireOnWantToClose(){
if(this.listener != null)
listener.onWantToClose();
}
}
When you want to close your activity you must call fireOnWantToClose() method.
public MyActivity extends Activity{
public void onCreate(){
final int CLOSE = 1; //number to identify what happens
MyClass my_class = new MyClass();
final Handler handler = new Handler(){
public void handleMessage(Message msg){
if(msg.what == CLOSE)
MyActivity.this.finish();
}
});
my_class.setOnWantToCloseListener(new OnWantToCloseListener(){
public void onWantToClose(){
handler.sendEmptyMessage(CLOSE);
}
});
}
}
This is secure because Activity is not finished directly by MyClass object, it is finished through a listener that orders a handler to finish activity. Even if you run MyClass object on a second thread this code will works nice.
EDIT: CLOSE var added I forget to declare and initialize this.
Pass the MyActivity to MyClass as an Activity. From there you can call myActivity.finish();
For example:
private Activity myActivity;
public MyClass(Activity myActivity){
this.myActivity = myActivity;
}
public void stopMyActivity(){
myActivity.finish();
}
And in MyActivity:
MyClass myClass = new MyClass(this);
This is risky, because you're holding a reference to an Activity, which can cause memory leaks.
If your java class is a nested inner class, you can use:
public class MyActivity extends Activity {
public static class JavaClass {
public void finishActivity() {
MyActivity.finish();
}
}
}
Otherwise you'll have to pass the java class a Context (i.e. pass it a reference to this, since Activity extends Context) and store it as a private instance variable.
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.