Load textures from another class in android - java

I'm working on a game for android, using libgdx and IntelliJ. In this game I have two 'screens', these screens use the same texture for their background, this is how I load them:
Texture backgroundTexture;
public static Sprite backgroundSprite;
backgroundTexture = new Texture("textures/background.png");
backgroundSprite = new Sprite(backgroundTexture);
This is done in both screens, so my question is, can I load these texture in another class, then use them in both screens somehow, I feel like that would be the way to do it, am I correct? If I'm on the right track, how should it be implemented?

You can use AssetLoader on your own way to load assets. It's nothing special just a class, which is called when the application starts, because the fact is that you should avoid to load assets, when everything is running. It would be just a simple class with static things.
public class AssetLoader {
public static Texture myBackgroundTexture;
public static void Load() {
myBackgroundTexture = new Texture("mybgs/my_bg_texture.png");
}
Let's call AssetLoader.Load() when the application start, and you can reference everywhere to your things like:
Texture thisScreenBg = AssetLoader.myBackgroundTexture;

Related

How do I store data to one object in Android for the whole app to access

I'm utilizing Firebase in my application and I figure it'd be better practice if I constantly observed the AuthState once the user has signed up or logged in and updated one class that can be accessed globally throughout my application (but that can only be instantiated once). Do I use a Singleton design pattern for this? How do I accomplish something like this in Android?
A common pattern is to create your own subclass of Android's Application class (specified in AndroidManifest.xml as shown below for example) and store variable there....effectively a singleton.
<application
android:name=".MyApplication"
In my app I use a static way for doing something similar.. maybe it helps to find solution for your situation:
I created a class which can not be instantiated because the constructor is set private and the class is used as some "variable-holder" accessible from all app statically. Here is the class:
VarHolder.java
package your.package.name;
public class VarHolder {
private VarHolder() {}
static int myInt;
static String myString;
}
than in app I use it this way:
VarHolder.myInt = 1;
VarHolder.myString = "Hello";
on another place in app :
textView.setText(VarHolder.myString);

Use of super class

I'm trying to follow an Android tutorial for caching bitmaps and looking at the sample code confuses me.
The code defines some utility classes as ImageFetcher, ImageResizer, and ImageWorker. Fetcher extends Resizer and Resizer extends Worker.
When Fetcher is called in the tutorial it invokes this code.
public ImageFetcher(Context context, int imageSize) {
super(context, imageSize);
init(context);
}
The super class Resizer invokes this code
public ImageResizer(Context context, int imageSize) {
super(context);
setImageSize(imageSize);
}
And finally the super class Worker invokes this code
protected ImageWorker(Context context) {
mResources = context.getResources();
}
What I don't understand is what resizing has to do with fetching, what working has to do with resizing, and why these classes are arranged like this. I'm trying to emulate something like this for my own app and was looking at what would be considered a good example but it only confused me further. I naively thought that you could simply have a class that does the fetching, not extended from one that did resizing (since they seem completely separate actions to me).
Yes I am new to Java as well.

How to execute methods in Java in a certain order without using a main method?

This is sort of like LibGDX. It has an Application interface and an ApplicationListener interface. The methods create(), render(), pause(), resume(), and dispose() are somehow magically executed (at least to me it seems that way) without being called anywhere. How is this possible? Did I miss something? I have a basic knowledge of Java, but maybe I missed something.
The source can be viewed here at https://github.com/libgdx/libgdx/tree/master/gdx/src/com/badlogic/gdx
Here is a tutorial for writing an application with libGDX:
https://code.google.com/p/libgdx/wiki/ApplicationConfiguration
As it states for the sample application, you actually need to write
a main method yourself and create a LwjglApplicationthere specifying your ApplicationListener:
public class MyFirstTriangleDesktop {
public static void main (String[] argv) {
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.title = "my-gdx-game";
cfg.useGL20 = false;
cfg.width = 480;
cfg.height = 320;
new LwjglApplication(new MyGdxGame(), cfg);
}
}
You can see how methods you mention are then called by the LwjglApplication class in the source file: https://github.com/libgdx/libgdx/blob/master/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglApplication.java
EDITED: Updated deprecated tutorial link
You need to use a "runner" provided by the LibGDX framework. For instance, there are runners that are designed for running as an ordinary Java application, an Android application, a GWT application or (apparently) an iOS application.
References:
"Running the demo & and test apps" in http://libgdx.badlogicgames.com/documentation.html
"Running your application" in http://code.google.com/p/libgdx/wiki/ProjectSetupNew
... or you could write your own simple launcher: see Lake's answer.

How to use an API level 8 class when possible, and do nothing otherwise

I have a custom view in my Android App that uses a ScaleGestureDetector.SimpleOnScaleGestureListener to detect when the user wants to scale the view via a 2 finger pinch in or out. This works great until I tried testing on an Android 2.1 device, on which it crashes immediately because it cannot find the class.
I'd like to support the pinch zoom on 2.2+ and default to no pinch zoom <2.1. The problem is I can't declare my:
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
{
#Override
public boolean onScale(ScaleGestureDetector detector)
{
MyGameActivity.mScaleFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
MyGameActivity.mScaleFactor = Math.max(0.1f, Math.min(MyGameActivity.mScaleFactor, 1.0f));
invalidate();
return true;
}
}
at all on android <2.1. Is there a clever way to get around this using java reflection? I know how to test if a method exists via reflection, but can I test if a class exists? How can I have my
private ScaleGestureDetector mScaleDetector;
declared at the top of my class if the API can't even see the ScaleGestureDetector class?
It seems like I should be able to declare some sort of inner interface like:
public interface CustomScaleDetector
{
public void onScale(Object o);
}
And then somehow...try to extend ScaleGestureDetector depending on if reflection tells you that the class is accessible...
But I'm not really sure where to go from there. Any guidance or example code would be appreciated, let me know if it isn't clear what I'm asking.
well, you can get ScaleGestureDetector source code and put in your project, make it as your own class, and use this to instead of system ScaleGestureDetector, this can avoid the android 2.2 and below version.
here is the ScaleGestureDetector source code: http://pastebin.com/r5V95SKe
Create two classes A and B. A for 2.2+ and B for 2.1 or earlier versions.
if(Build.VERSION.SDK_INT < 8) //2.2 version is 8
{
Use the class B
}
else
{
Use class A
}
Build.VERSION.RELEASE
use the above line to get the OS version of the device.
And you can have simple if else case. just check if the OS version is above 2.2 the you can have zoom in zoom out. else make it no zoom in or zoom out.

Android - Java - Access private variable in Main-Activity from another instanced class

I've been thinking for hours about this problem now without finding a solution. Still I think I'm just overlooking some very simple things.
My program is (mainly) supposed to record and playback audio, so I got one Main-Activity which contains all the functions with interactivity to the user and I got one class I called 'AudioHandler' to manage all the audio stuff in the background.
The Main-Activity uses an instance of AudioHandler.
Within the AudioHandler-class I got an OnCompletionListener, to notice when playback of the recorded audio-file has finished.
The problem is: When playback has finished - and the OnCompletionListener gets called, I want to change an ImageView (Turn the pause-button into a play-button) in the Main-Activity.
How can I access the ImageView in the Main-Activity from the AudioHandler-Instance?
...without making the ImageView-Variable public.
Method that calls play from the AudioHandler in the Main-Activity:
public State playRecording() {
//change play-button to stop-button
iPlay.setImageResource(R.drawable.stop_button_active);
//start or resume playback of the recorded Audio
ah.play();
//Return that the program is in playing-mode
return State.PLAYING;
}
play-function in AudioHandler
public void play() {
try {
mPlayer.start();
} catch (IllegalArgumentException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
e.printStackTrace();
} catch (IllegalStateException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
e.printStackTrace();
}
//add listener to notice when the end of the audio record has been reached
mPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//should somehow change the ImageView 'iPlay' in the Main-Activity when reaching this point.
}
});
}
Any help is appreciated :)
Marco
If you need to gain access to a variable, that variable should be either package-accessible or public. Or, even better, you should have an encapsulating method. Something like:
// On the main class:
public ImageView getIPlay(){
return iPlay;
}
private static MainActivity instance;
public MainActivity getInstance(){
return instance;
}
/** Either on the constructor or the 'OnCreate' method, you should add: */
instance = this;
Now you can access the ImageView from any Activity or class with:
MainActivity.getInstance().getIPlay();
It's that simple, really. You can go through a lot of other solutions, from using reflection through AOP or any kind of things. But it's just making the issue more complex. Try creating the setter method.
Your question is about object encapsulation.
When you define an instance variable as private, you are saying that only that object and members of that class can access the variable. This is a good thing because it protects you from accidentally changing data you did not want to. This is also why we have getters and setters.
So in your class you have something I imagine looks like this
public class Main {
... some code here
private ImageView myView;
... more code here
what you need to do is add the following methods to your Main class
public ImageView getView() {
return myView;
}
and
public void setView(ImageView a) {
myView = a;
}
so now when you want to access the ImageView from another class, you just call something like Main.getView() and you'll have it.
Now if this doesn't answer your question, it's because you didn't design your app too thoughtfully (so it seems) but luckily I won't be the kind of responder who tells you to uproot everything you have done and start over.
It sounds like you're working with an Android app and your issue is to communicate between activities.
This is why Android has something called Intents. You can send an Intent from one activity to another to carry data. So in this case you would send an Intent from one activity to the main class that would tell the main class to change the picture in the imageview. I won't lie, I suck at using intents but there are many wonderful tutorials online that will show you how to do this.
Another option would be to create a RemoteView of your layout that has the play/pause button and access it from the other activity, RemoteView has a built in function to change the bitmap of a remote imageview (again, see the Android Developer Documentation for RemoteView for more on this)
I'm sorry I couldn't give you some actual code, I'm not confident enough in my abilities on these topics but I'm 100% confident that one of the three methods I just listed will answer your question.
You could create a public wrapper method within your main Activity that toggles the ImageView between Pause and Play.
Or, you could pass the the ImageView to the AudioHandler (via the constructor?) and just manipulate it there.

Categories