UnityPlayerActivity getContext() substitution - android

Is there an alternative to the getContext in UnityPlayerActivity?
I want the code as shown below.
Activity.getContext()

answer from here
using (var actClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) {
playerActivityContext = actClass.GetStatic< AndroidJavaObject >("currentActivity");
}
or you can use code below from here
public class Main extends UnityPlayerActivity {
public static Context mContext;
#Override
protected void onCreate(Bundle bundle)
{
super.onCreate(bundle);
mContext = this;
}
}

getContext() is not defined in an Activity. It's used in a View to get a reference to the enclosing context(an Activity).
Please read below Answer .I hope it will helps you.
Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

Related

How to pass the context of some activity as an argument

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

Android JavascriptInterface use context to call method in activity (OOP)

In OOP, I can use the object to call its methods. So I want to do that in android using the same concept. However, it doesn't work. I used context to call the function updateLvl(int), but it said the method cannot be resolved. I want to know how can I use the context to call the method updateLvl?
public class MainActivity extends Activity {
private WebView webview;
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPref = this.getPreferences(0);
editor = sharedPref.edit();
webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new WebViewJavaScriptInterface2(this), "app");
public void updateLvl(int newLvl){
sharedPref = this.getPreferences(0);
editor = sharedPref.edit();
int be4Level = sharedPref.getInt("currLevel", 1);
if (newLvl >= be4Level){
editor.putInt("currLevel", newLvl);
editor.commit();
}
}
}
class WebViewJavaScriptInterface2{
private Context context;
/*
* Need a reference to the context in order to sent a post message
*/
public WebViewJavaScriptInterface2(Context context){
this.context = context;
}
#JavascriptInterface
public void openLvl(int lvl){
context.updateLvl(lvl);
}
}
you need to cast your context as MainActivity because your MainActivity class has updateLvl method not Context class hence compiler will show you error while applying static binding
#JavascriptInterface
public void openLvl(int lvl){
if(context instanceof MainActivity) // add safety check if required
((MainActivity)context).updateLvl(lvl);
}
The Context is not the instance of your WebViewJavaScriptInterface2 but a class of the android system (as well as Activity).
One way is to cast the context to the activity as Pavneet suggested. But this has the flaw that you can not be absolutely sure in your WebViewJavaScriptInterface2 that is is instanced from the right activity. Also you can use it just from one activity if you cast it to that one.
A cleaner way would be to define a callback interface, implement that interface in your activity (or multiple activity) and pass that callback interface into the WebViewJavaScriptInterface2.
This might help someone.
new Handler(Looper.getMainLooper())
.post(new Runnable(){
#override
public void run(){
updateLvl(lvl);
}
});

Calling context.getResources() returns null

So I am trying to get a string resource in my project but when I called context.getResources().getString(...), I get a NullPointerException. In debug mode, I found out that the context isn't null but looking at its members, I found out that mResources was null. Why are the resources not loaded for the activity context?
EDIT
Apparently, this is what triggered the Exception
public class MyActivity extends Activity {
SomeClass someClass = new SomeClass(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
public class SomeClass {
private final Context mContext;
public SomeClass(Context context) {
mContext = context;
mContext.getResources().getString(R.string.app_name);
}
}
I had to move the initialization of someClass to after super.onCreate() as suggested by CommonsWare. Thanks.
If I had to guess, you are trying to call this in an initializer. Do not attempt to use getResources() before the super.onCreate() call in your activity returns.

Access parent activity's method from dialog

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)

How to get the current Activity context for a non-activity class, statically

I have a non-activity class that needs to launch a new activity. Right now I just pass the current context as a parameter, but I would like to access the context statically if possible. I've already tried creating a new application (MyApplication extends Application), both as a new application and the main application, and neither worked. Any suggestions?
Current Code:
public class SharedFunctions {
public static void doSomething(Context context){
Intent i = new Intent(context, NextActivity.class);
context.startActivity(i);
}
}
The cleaner way to do it is to pass in a Context to each method. It's more typing, but it helps to make sure you're not leaking the reference.
Of course, if you really need static reference to it, you can just keep a static member in your SharedFunctions class and set it for each Activity.
onResume() and onPause() may be good places to set/clear it, but depending on your needs, you might want to change it. Just try not to keep references to old Activities.
public class SharedFunctions{
private static Context context;
public static void setContext(Context ctx){
context = ctx;
}
public static void doSomething(){
context.someContextFunction();
}
}
In each Activity:
protected void onResume(){
SharedFunctions.setContext(this);
}
protected void onPause(){
SharedFunctions.setContext(null);
}
create this class:
public class MyApplication
extends Application
{
private static Context context;
#Override
public void onCreate()
{
super.onCreate();
context = getApplicationContext();
}
public static Context getContext()
{
return context;
}
}
after that you must add this class to field name in application (Manifest)
<application
android:name="yourPackageName.MyApplication"
........
</application >
As a result you can call MyApplication.getContext() anywhere in your application and get the context.
hope, I help you.

Categories

Resources