Two onCreate() methods in Android? - inner-classes

I am working off another example (found here Loading MP3s into the Sound Pool in Android). but for some reason I am ending up with two onCreate() methods and if I delete one I am getting errors.
I am trying to load the MP3s into the Soundpool once and then call them in other activities.
My code:
class MyApp extends Application {
private static MyApp singleton;
private static SoundPool mSoundPool;
public onCreate() { // ##### Deleting this gives me errors ###, not deleting it gives me 1 error.
super.onCreate();
singleton = this;
mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);// Just an example
}
public static MyApp getInstance() {
return singleton;
}
public SoundPool getSoundPool() {
return mSoundPool;
}
}
public class TestAndroidGlobalsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}

Your code only has one onCreate method per class. They serve different purposes and are called when each of those classes is created by the OS.
Your MyApp.onCreate is called when the application is created and sets up application-wide state inside your MyApp class.
Your TestAndroidGlobalsActivity.onCreate is called when the Activity is created and sets the state for that specific activity an initializes its UI.

you must not confuse Application.onCreate, called when your application is created, and Activity.onCreate, called every time your activity is called (which may happen several times during one application execution)
Also, you should have the #Override annotation above each overriden method.

Related

i cant add toast in libgdx

im trying to create toast by call it with interface
the interface works fine it just that when i try to make a toast with it, it crashes
in Android Launcher
public class AndroidLauncher extends AndroidApplication implements Interface {
public void tost() {
Toast.makeText(getContext(), "wrong num",
Toast.LENGTH_LONG).show();}}
in gameclass
interface Interface{void tost();}
public class MyGdxGame extends ApplicationAdapter {
final private Interface interface;
public MyGdxGame(Interface interface){this.interface=interface;}
public void render() {interface.tost}
Android toasts must be performed on the Android UI thread. The game loop in LibGDX runs on the OpenGL thread, so you must post your method to the UI thread to safely run it, like this:
public class AndroidLauncher extends AndroidApplication implements Interface {
public void tost() {
runOnUiThread(new Runnable() {
#Override
public void run () {
Toast.makeText(getContext(), "wrong num",
Toast.LENGTH_LONG).show();}
}
});
}
}

Jbehave get Story name inside #BeforeStory

I would like to get the Story name in a method annotated with #BeforeStory.
I need this for debugging purposes, cause i'm running a bunch of stories with runStoriesAsPaths and with multiple threads, and I'm trying to log which thread is running which story.
Is there a way to do this?
first you need to create a new StoryReporter (extend that class). In that class you can add actions to be performed before/after story/scenario/step, and you have the story name.
example:
public class NewStoryReporter implements StoryReporter {
private StoryReporter delegate;
public NewStoryReporter(StoryReporter delegate) {
this.delegate = delegate;
}
#Override
public void beforeStory(Story story, boolean givenStory) {
delegate.beforeStory(story, givenStory);
}
#Override
public void beforeScenario(String scenarioTitle) {
delegate.beforeScenario(scenarioTitle);
}
#Override
public void beforeStep(String step) {
if(step.equals("When after each step")){
return;
}
delegate.beforeStep(step);
}
then you need to extend StoryReporterBuilder, this creates your NewStoryReporter.
example:
public class NewStoryReporterBuilder extends StoryReporterBuilder {
#Override
public StoryReporter build(String storyPath) {
StoryReporter delegate = super.build(storyPath);
return new NewStoryReporter(delegate);
}
}
then in your configuration, create an instance of the NewStoryReporterBuilder, and use it in
Configuration configuration = new YourConfiguration().useStoryReporterBuilder(newStoryReporterBuilder....)
Now in Jbehave it's configured in different way.
So, to achieve that goal you need to:
Create new class which extends org.jbehave.core.reporters.ConsoleOutput. Here you can modify various of methods. In your case - you need to override method:
public void beforeScenario(String title)
Check example attached in the end of this post to see how it can be done.
Create new instance of abstract class org.jbehave.core.reporters.Filter:
public static final Format YOUR_CUSTOM_CONSOLE = new Format("YOUR_CUSTOM_CONSOLE")
{
#Override
public StoryReporter createStoryReporter(FilePrintStreamFactory factory,
StoryReporterBuilder storyReporterBuilder) {
return new TeamCityConsoleOutput(storyReporterBuilder.keywords()).doReportFailureTrace(
storyReporterBuilder.reportFailureTrace()).doCompressFailureTrace(
storyReporterBuilder.compressFailureTrace());
}
};
Then you need to add this format to your story builder which you are using in your configuration, that mean:
new MostUsefulConfiguration()
.useStoryReporterBuilder(
new StoryReporterBuilder()
....//here are another modifications of sorey report builder
.withFormats(YOUR_CUSTOM_CONSOLE , .../* another formats */ HTML, Format.XML, Format.TXT))
....//here are another modifications of configuration
.useStepMonitor(new CrossReference().getStepMonitor());
Here is example of such modification, which can be used to integration with TeamCity:
https://github.com/jbehave/jbehave-core/blob/d15774bf763875662869cdc89ce924b1086af6f8/jbehave-core/src/main/java/org/jbehave/core/reporters/TeamCityConsoleOutput.java

How to list all classes in autocompletion inside annotations in Intellij IDEA?

I have custom class InternalTimerServiceController in my application. I want to use it in another class inside android annotations. And it seems that autocompletion does not work correctly in this case.
I have this interface
public interface InternalTimerServiceControllerContract
{
void doWork();
}
And this class
#EBean
public class InternalTimerServiceController implements InternalTimerServiceControllerContract
{
#Override
public void doWork()
{
// do work
}
}
And this is my Activity
public class MyActivity extends Activity
{
// try uncomment line below and see if autocomplete works properly
//#Bean(Internal)
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
It's a bug, thanks for reporting. I've created a ticket for it: http://youtrack.jetbrains.com/issue/IDEA-98298

Instance variable in Stripes

I'm trying to find a way to create an instance variable within the Stripes application context.
Something that i would do in the init() method of a Servlet while using hand-coded servlets.
The problem is that since an instance of the ActionBean is created each time the application is accessed, the variable in the actionBean is created multiple time.
I have tried to get some reasonable place withing Stripes trying to call the ServletContext via ActionBeanContext.getServletContext(), but from there there is no way to access the init() method and write some code in it.
Do you have any suggestions?
The ActionBeanContext is also Stripes application context. This context can be customized and can contain whatever you want. Some example code:
package my.app;
public class CustomActionBeanContext extends ActionBeanContext {
public CustomActionBeanContext() {
super();
}
public MyObject getMyObject() {
return (MyObject) getServletContext().getAttribute(“myObject”);
}
// Alternative solution without ServletContextListner
private static MyObject2 myObject2;
static {
myObject2 = new MyObject2();
}
public MyObject2 getMyObject2() {
return myObject2;
}
}
To let the Stripes context factory know you want to use a custom ActionBeanContext you need to add an init-param to the Stripes filter in the web.xml:
<init-param>
<param-name>ActionBeanContext.Class</param-name>
<param-value>my.app.CustomActionBeanContext</param-value>
</init-param>
You can initialize your object at server start by adding a SerlvetContextListener:
Public class MyServletContextListener implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute("myObject", new MyObject());
}
Example ActionBean:
public class MyAction implements ActionBean {
private CustomActionBeanContext context;
#Override
public CustomActionBeanContext getContext() {
return context;
}
#Override
public void setContext(ActionBeanContext context) {
this.context = (CustomActionBeanContext) context;
}
#DefaultHandler
public Resolution view() {
MyObject myObject = getContext().getMyObject();
// doing something usefull with it..
}
}
An alternative solution, in my opinion a superiour solution, is to use a dependency injection framework for injecting the (singleton) objects into your actionbeans. See Stripes configuration example here: Injecting Stripes ActionBeans with Guice DI
Not a Stripes-specific way, but using the standard Servlet API you'd implement ServletContextListener and do the job in contextInitialized() method. If you register it as <listener> in web.xml (or when you're already on Java EE 6, annotate using #WebListener), then it'll run during webapp's startup.
#Override
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute("somename", new SomeObject());
}
This way it's available in EL by ${somename} and in all action beans by ServletContext#getAttribute().
#JBoy, You have to specify your implementation of ServletContextListner in the web.xml like below
<listner>
<listner-class>
www.test.com.MyListner
</listner-class>
</listner>
Thanks KDeveloper for his advice. I was also searching for the solution. I found the information from his blog
There is one more method I have found out. For that you have to subclass the "RuntimeConfiguration" class
public class MyConfiguration extends RuntimeConfiguration {
#Override
public void init() {
getServletContext.setAttribute("myObject",new MyObject);
super.init();
}
}
After that in the web.xml specify the above configuration.
<init-param>
<param-name>Configuration.Class</param-name>
<param-value>www.test.com.MyConfiguration</param-value>
</init-param>
You also have to subclass the ActionBeanContext as KDeveloper said; to get the object in ActionBeans
This is my finding. I found out it is working. But I don't know whether it has any side effects. If it has any; please comment..

Global application class with stack of activities

Stemming from this article more efficient way of updating UI from service I was wondering if I could take that a step further and implement the following. I may have a misunderstanding of my Apps lifecycle though.
public class MyApplication extends Application {
private static final String TAG = MyApplication.class.getSimpleName();
private static Stack<MyActivity> mActivityStack = new Stack<MyActivity>();
private static String mTopActivity = "none";
public static void pushActivity(MyActivity activity)
{
mActivityStack.push(activity);
mTopActivity = activity.getClass().getSimpleName();
Log.i(TAG, "push::"+mTopActivity);
}
public static void popActivity()
{
Log.i(TAG, "pop::"+mTopActivity);
mActivityStack.pop();
}
#Override
public void onLowMemory() {
super.onLowMemory();
Log.w(TAG, "low memory!!!");
Log.w(TAG, "Current::"+mTopActivity);
}
}
public class MyActivity extends Activity
{
private static final String TAG = MyActivity.class.getSimpleName();
public void onCreate(Bundle last)
{
super.onCreate(last);
MyApplication.pushActivity(this);
}
public void onDestroy()
{
super.onDestroy();
MyApplication.popActivity();
}
}
Would the stack be valid during the lifecycle of the application?
As CommonsWare said, this did not work out. Also, it is not a great idea to derive from Activity, because you would then have to also derive listactivity, preferenceactivity, etc. Obviously, I did not think this would solve any problem it was just an experiment in android life cycles.
Would the stack be valid during the lifecycle of the application?
Of course it won't be valid. You assume every activity is created and destroyed in the same sequence. They won't be in many cases (e.g., user presses HOME).
Whatever problem you think you are solving this way, this is not the right solution by any stretch of the imagination.