Reputation: 15552
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.
Upvotes: 3
Views: 6318
Reputation: 131
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();
}
Upvotes: 1
Reputation: 1128
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)
Upvotes: 0
Reputation: 1388
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.
Upvotes: 2