null point object using asset manager - android

#Override
public void show()
{
main = new MainClass();
texture = main.manager.get("ball.png");
mainActor = new MainActor(world, texture, new Vector2(1,2));
stage.addActor(mainActor);
}
Attempt to invoke virtual method 'java.lang.Object com.badlogic.gdx.assets.AssetManager.get(java.lang.String)' on a null object reference
how to fix it?
"manager" is the AssetManager created on my MainClass
my MainClass
public class MainClass extends Game
{
protected AssetManager manager;
#Override
public void create()
{
manager = new AssetManager();
manager.load("ball.png", Texture.class);
manager.finishLoading();
setScreen(new MainScreen(this));
}
}

You are creating manager object inside create() method, but you are not calling that method. create() method is not constructor - it won't be called automatically. I don't know what Game class constructor does but most likely not it's not calling create(), but that method is called at some other occasion.

I am assuming your first block of code is from within your MainScreen class. It doesn't make sense for your MainScreen to create a new MainClass Game instance. And since it is, you are referencing a MainClass instance that has never had create() called on it, so its manager is null.
Since I can see that your MainScreen class already takes an instance of MainClass, you just need to make sure it's storing it and you don't instantiate a new one. In this sort of case, I declare passed-in variables as final so I know they are not going to change (and it's impossible to change them accidentally).
public class MainScreen implements Screen {
final MainClass main;
public MainScreen(MainClass main){
this.main = main;
}
//...
#Override
public void show()
{
texture = main.manager.get("ball.png");
mainActor = new MainActor(world, texture, new Vector2(1,2));
stage.addActor(mainActor);
}
//...
}

Related

Getting instance of MainActivity

Hi I am kind of new to android, still learning. And my problem is that, for example I have a method which was created in the MainActivity and I need to call it from another class.
Is it a good practice to get the instance of the MainActivity so that I may be able to call the method in the MainActivity from another class?
This is an example:
public class MainActivity extends AppCompatActivity {
private static MainActivity inst;
public static MainActivity instances()
{
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showToast (String text){
Toast.makeText(inst, text, Toast.LENGTH_SHORT).show();
}
Then this is the other class:
public class broadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
MainActivity instance = new MainActivity();
instance.showToast(AnyText);
}
}
I saw this type of coding while looking at tutorials and wondered if it's a good practice or maybe there might be a better way? Since I get the warning of Do not place Android Context Classes in static classes
Thanks in advance for any insight or help! :D
I guess You want to make A singleton of Activity Class
but as Mention in All Pattern Design
using Singleton
If and Only If its only way to Make A Global Variable
Singleton is based on Lazing Initialing and Load On Memory
so I guess If you cant to Interact With Activiy You can Use
BroadCast Or Intents
You can call method from another class like this:
MainActivity instance = new MainActivity();
String data = instance.data();
and create data method in that class:
public String data() {
return mangaId;
}
Is it a good practice to get the instance of the MainActivity so that
I may be able to call the method in the MainActivity from another
class?
You totally can do this but you don't need to make it static and use a constructor. Just create a new instance like follows and you'll access the public methods
MainActivity mainActivity = new MainActivity();
mainActivity.showToast(text);
About the warning
It suggests avoiding having context fields defined as static. The warning itself explains why: It's a memory leak. If you make it static it will be accessible anywhere in your app and some methods can hold the reference to this context for a really long time and it won't be garbage collected. It will lead to a outofmemory exception and the app could crash. But here you're trying to invoke showToast() from broadcastreceiver so you can just get rid of static references. And it you need them in the future you safe ways to inject context
You cannot create instances of an Activity using the new operator.
You have to use an Intent to let an Activity to be created.
So you cannot get a reference to an instance of your activity.
The only methods you can use of your activity class are static ones.

How can I use Java Plugin in Unity

I try make a plugin in android studio to use in Unity.
So I make this method in android studio.
public class MainActivity extends UnityPlayerActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public static String SendMessage(){
return "Message";
}
}
and in Unity,
public class PluginWrapper : MonoBehaviour {
// Use this for initialization
void Start () {
TextMesh textMesh = GetComponent<TextMesh> ();
var plugin = new AndroidJavaClass ("com.thewell_dev.beaconf.MainActivity");
textMesh.text = plugin.CallStatic<string> ("ReturnMessage");
}
}
to use SendMessage() method in unity, using AndroidJavaClass and CallStatic.
It is success.
I can check message in device by unity.
But, one error occurs.
If I change method like this,
public class MainActivity extends UnityPlayerActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public String SendMessage(){
return "Message";
}
}
change SendMessage method type.(static String to String)
and in Unity,
public class PluginWrapper : MonoBehaviour {
// Use this for initialization
void Start () {
TextMesh textMesh = GetComponent<TextMesh> ();
var plugin = new AndroidJavaClass ("com.thewell_dev.beaconf.MainActivity");
textMesh.text = plugin.Call<string> ("ReturnMessage");
}
}
change plugin.CallStaic to plugin.Call
In case, I just delete Static, but it returns no result.
https://docs.unity3d.com/kr/current/ScriptReference/AndroidJavaClass.html
I just change the type. But no returns.
I think I mistake to Call method by AndroidJavaClass,
but I can't find it.
If you know about it, Please help me.
You can use "types" to invoke static methods, as static things are bound to their defining types. You can't, however, use instance methods (non-static methods, that is) without an instance of the type. That's why your second attempt fails. To invoke instance methods, you must get an instance of the type, either by making one yourself by invoking the java constructor like this:
var object = new AndroidJavaObject ("com.some.class", constructor_param1, constructor_param2, constructor_param3, ...);
result = object.Call<string> ("SomeMethod");
Or, to get as instance of something like an activity which is constructed outside the scope of your C# script, you use static methods to retrieve the instance you're looking for:
var type = new AndroidJavaClass ("com.some.class");
var object = type.CallStatic<AndroidJavaObject>( "SomeStaticGetterMethod" );
result = object.Call<string> ("SomeMethod");

Mock activity class member before onCreate

I am trying to test an activity using robolectric 3.3.2.
Want to mock and activity's member initialization as the direct call results in NPE.
ActivityController<MyActivity> activityController =
Robolectric.buildActivity(MyActivity.class);
mTestActivity = activityController.get();
Mockito.when(mTestActivity.getCountry()).thenReturn("xxxx");
activityController.setup();
Tried out above code, but the setup.() (oncreate) ignores the mock of
getCountry method and invokes the definition from activity.
Is there a way to achieve this?
It will not work like this even if you use spies (#Spy, Mockito.spy()).
You should use stub:
public class MyActivityTest{
public static class StubMyActivity extends MyActivity {
Country getCountry() {
return someSpecialCountry;
}
}
#Before
public void setUp(){
ActivityController<StubMyActivity> activityController =
Robolectric.buildActivity(StubMyActivity.class);
mTestActivity = activityController.setup().get();
}
}

How to let Asynctask static inner class instantiate outer objects

I need to instantiate some objects in a separate thread cause i don' t want the UI to get slow. Using AsyncTask i faced the problem of a memory issue: the GC won't deallocate the memory.
So i found the solution declaring AsyncTask as a static inner class. I'm new to android developing so i need your help cause i'm having a NullPointerException. Here is my code:
-static variables because of the inner static class-
public class Wash extends ActionBarActivity {
private static Effetti effect1,effect2,effect3…effect50
private static Effetti[] effects;
.
.
.
-the static inner class-
private static class TaskL extends AsyncTask <Effetti[], Void,Effetti[]> {
#Override
protected Effetti[] doInBackground(Effetti[]... params) {
effects = new Effetti[]{
effects1 = new Effetti(MyApplication.getAppContext(),R.raw.ef1),
effect2=new Effetti(MyApplication.getAppContext(),R.raw.ef2),
effect3 = new Effetti(MyApplication.getAppContext(),R.raw.ef3),
effect4 = new Effetti(MyApplication.getAppContext(),R.raw.ef4),
.
.
.
};
return effects;
}
#Override
protected void onPostExecute(Effetti[] result) {
super.onPostExecute(result);
}
}
The "Effetti" class is a class which contains SoundPool methods for play and stop audio files. Also contains constructors with arguments like context and a resid.
I used MyApplication.getAppContext() trick seen in this post:
Static way to get 'Context' on Android? android
Any suggestion? thaks
I think that this line MyApplication.getAppContext() is giving you the NullPointerException.
You could try doing this:
private static class TaskL extends AsyncTask <Effetti[],Void,Effetti[]> {
Activity activity;
updateDashboardContent(Activity a){
activity=a;
}
#Override
protected Effetti[] doInBackground(Effetti[]... params) {
effects = new Effetti[]{
effects1 = new Effetti(activity.getApplicationContext(),R.raw.ef1),
effect2=new Effetti(activity.getApplicationContext(),R.raw.ef2),
effect3 = new Effetti(activity.getApplicationContext(),R.raw.ef3),
effect4 = new Effetti(activity.getApplicationContext(),R.raw.ef4),
.
.
.
};
return effects;
}
#Override
protected void onPostExecute(Effetti[] result) {
super.onPostExecute(result);
}
}
and according to which part of your code you call it like this:
new TaskL(getActivity()).execute(...); or new TaskL(this).execute(...);
If the above snippet doesn't work then try passing to the constructor of TaskL an Effetti array (doing what I did with 'activity') with variables effects1,effects2... already instantiated avoiding instantiating them in the AsyncTask...

Is it possible to invoke a method from abstract class?

I have the Abstract class as following:
AbstractFilePickerFragment.java
public abstract class AbstractFilePickerFragment<T> extends ListFragment
implements LoaderManager.LoaderCallbacks<List<T>>
....
....
public void GoBackToPreviousDirectory() {
currentPath = getParent(currentPath);
refresh();
}
}
OtherActivity.java
private AbstractFilePickerFragment<T> mAbstractFilePickerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
//THIS LINE SAYS "Cannot instantiate the type AbstractFilePickerFragment"
mAbstractFilePickerFragment = new AbstractFilePickerFragment();
}
public void GoBackToPreviousDir_onClick(MenuItem item) {
mAbstractFilePickerFragment.GoBackToPreviousDirectory();
}
}
Does anyone if it is possible to invoke the GoBackToPreviousDirectory from AbstractFilePickerFragment class???
I know a static method would work, but I can't make a static method for this situation.
Thank you so very much for the help
No. First, you do not invoke methods from classes. You invoke object methods as object is instance of class. Abstract class cannot be instantiated.
In order to call a non-static method, you have to instantiate the class.
Abstract classes cannot be instantiated, by definition. So Answer is NO
If you still need to access the method, You will have to create a class that extends the abstract class and implement all of the methods in the class. Then you can instantiate the extended class within your program and call the method.

Categories

Resources