I developed a simple game and I want to give an external URL to my web page. The problem is that, I'm using setContentView in the onCreate method of my main activity. My game content is dynamic and I cannot use intents instead of setContentView. However, as you know, onCreate is called once and the only way that I found on web to call an URL is "using intents". It is not working because setContentView is the only thing running. Here is my codes:
GameActivity.java
private static GameContent gameContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameContent = new GameContent(this);
setContentView(gameContent);
} // on.c.ends
My GameContent class is extends SurfaceView and Runnable. I call all draw(), pause() and resume() methods here. I have a class BasicButton and I added it to GameContent and draw it. It works. Here is the part that I want to use:
BasicButton.java
#Override
public void update() {
if (xx > (rate.getX()) && xx < (rate.getX() + rate.getPlayButton('x')))
if (yy > (rate.getY()) && yy < (rate.getY() + rate.getPlayButton('y'))) {
UserInput.setXY(0, 0);
if (UserInput.getAction() == true) {
// I want to add a code here to open a web page
} // fi
} // fi
} // update ends
My solution was to create a boolean in GameActivity and change it from BasicButton class and using an intent and startActivity, to open a web page. However it is not working.
Do you have any suggestion?
You can't. setContentView only works with pre-compiled XML files in your APK. You can't even write a new one on the fly and call setContentView on it. I don't think you really understand what setContentView does.
Related
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
When I see this basic source code in MyActivity.java,
onCreate() method is overriding just. but When I run the app, I can see that overrided method "onCreate()" runs. how is this possible?
If its possible to run the onCreate method in that code, I thought there should be a code like
onCreate();
We can always override these functions and add more to it but the Question is how are these functions called automatically when no one is calling them? We haven’t written any code to call them.
This is where the concept of CALLBACK FUNCTIONS comes in.
The concept of callbacks is to inform a class synchronous / asynchronous if some work in another class is done. Some call it the Hollywood principle: "Don't call us we call you".
Here's a example:
class A implements ICallback {
MyObject o;
B b = new B(this, someParameter);
#Override
public void callback(MyObject o){
this.o = o;
}
}
class B {
ICallback ic;
B(ICallback ic, someParameter){
this.ic = ic;
}
new Thread(new Runnable(){
public void run(){
// some calculation
ic.callback(myObject)
}
}).start();
}
interface ICallback{
public void callback(MyObject o);
}
Class A calls Class B to get some work done in a Thread. If the Thread finished the work, it will inform Class A over the callback and provide the results. So there is no need for polling or something. You will get the results as soon as they are available.
In Android Callbacks are used f.e. between Activities and Fragments. Because Fragments should be modular you can define a callback in the Fragment to call methods in the Activity. copied from here
for more study follow this link please :
link 1
link 2
The onCreate method is called during the Activity Lifecycle. The docs regarding this method state
You must implement this callback, which fires when the system first creates the activity
So the point of this method is for you to initialize anything specific to your activity that needs to be done when it is first created, and call super to propagate this to it's superclasses, allowing them to perform their initialization sequence as well. You should not be invoking this method yourself.
The main problem is that the app starts only after installation or reboot.
Second time the application does not run correctly.
Details are below.
I have encountered with a few strange problems
1) Libgdx did not detect screen size correctly on Android 4 in
SCREEN_WIDTH = Gdx.graphics.getWidth();
I got 369*320 instead of 960*540
I do as follows to fight with this problem:
I run main Activity class, where I get screen size using Display
Then I run AndroidApplication class where I start Admob and Libgdx class.
2) The second problem is that the app starts
with no initialized values, that is to say with the same memory.
No initialization of values such as boolean abc=false;
Looks like invalid exit?
In Libgdx class (third class) I set some value exit=true and exit,
disposing all textures. Program returns to the second class .
public void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Data.exit) finish();
Second class returns to main activity
which checks exit in the same manner
3) Next interesting thing is that now Gdx.graphics.getWidth()
gets screen size correctly. Mistery...
4) If so, I remade the app.
And now main class starts Libgdx class.
It works and exits good, but only first time after installation or reboot.
Seconds time Libgdx onCreate starts, but render() does not.
Looks like invalid exit after first start again:
The main class code is here
public class MyActivity extends AndroidApplication
implements IActivityRequestHandler {
public void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
context.startService(new Intent(context, BillingService.class));
....
// Create the libgdx View
View gameView = initializeForView(new MyGame(this), false);
// Create and setup the AdMob view
adView = new AdView(this, AdSize.BANNER, "aaaaaaa");
}
#Override
public synchronized void onPause() {
super.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
Any ideas? Thanks!!
You are using statics. They preserve their value when you close the app, and you open it again before Android destroys the process, hence using the same VM. You cannot control when Android will destroy it, so try to initialize these variables in the constructor/create method of their class.
Instead of:
static boolean abc=false;
Use:
static boolean abc;
public MyClass/create(){
abc=false;
}
Or do not use statics unless necessary.
I would like to know, why OnCreate() is called only once at the start of an activity?
Can we call OnCreate() more than once in the same activity?
If yes, than how can we call it? can anyone give an example?
Thanks a lot!!!
Why would you want to called it again? unless the activity is reconstructed, which is called by system. You cannot call OnCreate manually , it is the same reason why you won't call setContentView() twice. as docs:
onCreate(Bundle) is where you initialize your activity. Most
importantly, here you will usually call setContentView(int) with a
layout resource defining your UI, and using findViewById(int) to
retrieve the widgets in that UI that you need to interact with
programmatically.
Once you finish init your widgets Why would you?
UPDATE
I take some words back, you CAN do this manually but I still don't understand why would this be called. Have you tried Fragments ?
Samplecode:
public class MainActivity extends Activity implements OnClickListener {
private Button btPost;
private Bundle state;
private int counter = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
state = savedInstanceState;
btPost = (Button) findViewById(R.id.btPost);
btPost.setOnClickListener(this);
Toast.makeText(getBaseContext(), " " + counter, Toast.LENGTH_LONG)
.show();
}
#Override
public void onClick(View v) {
counter++;
this.onCreate(state);
}
}
onCreate() method performs basic application startup logic that should happen only once for the entire life of the activity .
Once the onCreate() finishes execution, the system calls the onStart() and onResume() methods in quick succession.
The initialization process consumes lot of resources and to avoid this the activity once created is never completely destroyed but remains non visible to user in background so that once it is bring back to front , reinitialization doesn't happen .
Where you want to call onCreate manually.
Then just do this.
finish();
Intent intent = new Intent(Main.this, Main.class);
startActivity(intent);
finish() calls the current stuff.
And if you are doing somethong getExtra in this activity then do this,
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("key",your_variable);
super.onSaveInstanceState(outState);
}
And add this to your onCreate()
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
if(savedInstanceState != null)
{
your_variable= savedInstanceState.getString("key");
}
}
Why would you want to call onCreate more than once? You will be re-creating the activity. If this is what you need for whatever reason then finish the activity and use an intent to create a new instance of that activity. Otherwise, you have two instances of the activity at the same time. Hope that helps but if that doesn't make sense then add more information as to what you want so we have context
OnCreate is basically use to create your activity (UI). If you have already created your activity then you need not create it again as you have already created.
It is basically used to initialize your activity and to create user interface of your activity. Activity is a visual part which you can use again and again so.. I think your problem is not to recreate activity but to reinitialize all components of your activity. For that purpose you can create a method initialize_act() and call it from anywhere...
#OnCreate is only for initial creation, and thus should only be called once.
If you have any processing you wish to complete multiple times you should put it elsewhere, perhaps in the #OnResume method.
Recently i realized that onCreate is called on every screen orientation change (landscape/portrait). You should be aware of this while planning your initialization process.
Recreation can be suppressed in AndroidManifest.xml:
<activity
android:configChanges="keyboardHidden|orientation"
android:name=".testActivity"
android:label="#string/app_name"></activity>
So, I am again, asking a very basic question. I apologize for my ineptness but I guess I read the given tutorials on these topics poorly. My question is as follows:
I would like to use a "listener" pattern to handle button presses on my GUI. I believe an onClickListener is what I need to use to handle these button presses. However, I'm not sure if I should be creating and handling events that occur after the GUI is created within an onCreate method. The following code is within my onCreate method for one of my Activities:
View.OnClickListener upDownListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(v == (upOneButton))
{
Log.d("OptionSelect", "Up One Button Pressed.");
ops.getOptionList().get(0).incrementProbability(4);
} . . .
This method being called updates some GUI text with a different number. It is being called, but the GUI isn't responding. I imagine this has to do with my attempt to use it within the onCreate method.
In short, what is a good and simple way to deal with user events within a GUI and where should this occur?
Thank you so much.
EDIT: Log.d() does in fact get called. Also, ops is an object of type OptionSelect which happens to be the type of the class in which the onCreate() call is made. Will that become an issue? Also, here is the method for incrementProbability():
public void incrementProbability(int numberOfOptions)
{
probability += (numberOfOptions - 1);
if(probability > 100)
{
Log.i("OptionSelect", "Exceeded Maximum by " + (probability - 100));
probability = 100;
}
}
Also, here is relevant code I should've included that is updating my GUI at the end of the onClick() method:
private void refreshDisplay(TextView a, TextView b, TextView c, TextView d)
{
a.setText(getOptionList().get(0).getProbability() + "");
b.setText(getOptionList().get(1).getProbability() + "");
c.setText(getOptionList().get(2).getProbability() + "");
d.setText(getOptionList().get(3).getProbability() + "");
a.invalidate();
b.invalidate();
c.invalidate();
d.invalidate();
}
Thanks for the help so far!
I personally prefer to have my Activities implement listener interfaces and add an onClick method to the Activity itself such as...
public class MyActivity extends Activity
implements View.OnClickListener {
...
#Override
public void onClick(View v) {
...
}
}
I then just use...
myGuiObject.setOnClickListener(this);
...whenever I want to set that method as the listener for any GUI object.
When I'm back from the background, onResume() method is called. Okay. So if I want to do some special code when I'm back I can put it there.
What about if I've many activities ? Do I've to duplicate that code everywhere ? Should I used the Application class and call a method in each onResume() methods ?
Plus, I would need to access the UI (changes, dialogs, ...). Maybe the application class isn't that a good idea ... ?
Concretely, I want to refresh my cache every XX time and I want to do that check when the application (or activity) is back from the background but I don't know exactly how to do and where to do that.
How do you do that guys ? Thanks for help.
If it is similar code you could use a static helper functions class and pass this to the functions as the context so that you can do Activity specific functions.
If you just want to know when an APP is returning from background state (when you return to home or another app and back to your app again) maybe this can help you.
if you find a case when this do not apply, please let me know.
public class FatherClass extends Activity {
private static int activities = 0;
public void onCreate(Bundle savedInstanceState, String clase) {
super.onCreate(savedInstanceState);
}
protected void onRestart(){
super.onRestart();
if(activities == 0){
Log.i("APP","BACK FROM BACKGROUND");
}
}
protected void onStop(){
super.onStop();
activities = activities - 1;
}
protected void onStart(){
super.onStart();
activities = activities + 1;
}
}
All of your classes MUST extend from this one, or increment and decrement the value of this class.