Load new page on button click in android? - java

I am making a game in android. I want to make a main menu screen that has two buttons, one to start the game and one to display the how to screen.
I have classes for both, but when I launch my name and test the buttons, the application crashes. Could someone please tell me what is wrong with my code?
public void launch()
{
Intent i = new Intent();
i.setClassName("com.testing.blockinvasion", "com.testing.blockinvasion.game");
startActivity(i);
}
public void howto()
{
Intent i = new Intent();
i.setClassName("com.testing.blockinvasion", "com.testing.blockinvasion.howto");
startActivity(i);
}
}
My buttons are defined in my main.xml:
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/Start"
android:onClick="launch" />
EDIT: I ended up just deleting the project and starting another one and everything seems to work fine now.

You need to correct your method signatures. So do it in this way:
public void launch(View v)
and
public void howto(View v)

Try it this way:
private OnClickListener button1Listener = new OnClickListener() {
public void onClick(View v)
{
Intent howto = new Intent(getApplicationContext(), .class);
startActivity(howto);
}
};
Assigning a different OnClickListener object to every button --> button1.setOnClickListener(button1Listener)
Anyway, are all the Activities defined in the AndroidManifest.xml?

Related

Android skip Activity and put it last

I am trying to make a skip button and it have to do what i draw.
i honestly don't know how can i make this happen.
The code actually have to skip the current activity and put it as last.
if the activity's question was answered, there is no skip.here i draw
I have tried a few things but it's beyond my powers.
Intent intent=new Intent(this, c1_2.class);
startActivity(intent);
finish();
you can use arrayList or Queue for keep your activityes, then use it to start Activity.
try this.
final ArrayList<Class> activities = new ArrayList<>();
// add your activity---------------
activities.add(c1_1.class);
activities.add(c1_2.class);
activities.add(c1_3.class);
//----------------------------
butonSkip=findViewById(R.id.skip);
butonSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Class firstActivity = activities.get(0);
startActivity(new Intent(c1_1.this,activities.get(0)));
activities.remove(0);
activities.add(firstActivity);
}
});
//-----------can change activities data
// activities.set(1, c1_3.class);

Switching activities loses functionality

I have an app that consists of 3 Activities
MainActivity
CalculatorActivity
InformationActivity
My MainActivity has a confirm button that onClick starts the CalculatorActivity and everything is done correct and working as intended.
CalculatorActivity has 2 buttons, one calculateButton that checks something and shows a message and a learnMorebutton that starts the InformationActivity.
When I am on the
CalculatorActivity for the first time everything is fine and working.Pressing the learnMoreButton navigates me to the InformationActivity.That activity looks like this :
InformationActivity:
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switchActivity();
}
});
}
public void switchActivity(){
final Intent intentObj = new Intent(this,CalculatorActivity.class);
startActivity(intentObj);
}
A goBack button that gets me back to CalculatorActivity.Going back seems to break the functionality.Although the layout is there and everything looks as it should be, pressing the buttons (calculateButton,learnMoreButton) does nothing.
CalculatorActivity :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
final Button calculateButton = (Button) findViewById(R.id.calculateId);
final Button learnMoreButton = (Button) findViewById(R.id.learnMoreButtonId);
there are some more TextView and EditText that dont show up here but you get the point.Some more methods that do the calculations ,getters and setters.
This method
public void switchActivity(){
final Intent intentObj = new Intent(this,Information_activity.class);
startActivity(intentObj);
}
But I am not using onResume() , onPause() or any methods from the lifecycle apart from onCreate().
From some search that I have done I found out that I am doing something wrong with how I manage the activity lifecycle but I still can't find the solution.The dev documents didn't help me that much and a post with kinda the same problem as mine is old.
My question is, how the navigation from InformationActivity to CalculatorActivity should be done, so the functionality doesn't break when CalculatorActivity comes back to interact with the user.Which method should be called onResume()? , onRestart()? and how should it look like?
Thanks anyone who is willing to help.
P.S: As I mentioned , I have read the documents for the lifecycle of an Activity but I haven't found the solution.
instead of starting new activity everytime, finish the informationactivity.
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
You are creating too much activities moving going back and forth this way. You can use either destroy the activity with finish(); or you can also go back to previous activity using onBackPressed();
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
Try this out
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InformationActivity.this.finish();
}
});
}
Instead of saying where to go back, you can just finish the activity and it will automatically switch you to the previous one.
I think your activities are hierarchical thus you should be able to do the following from your main calculator activity:
Intent i = new Intent(this, InformationActivity.class);
startActivityForResult(i);
Your back button add this code:
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setResult(Result.OK);
finish();
}
});
You are all suggesting the same thing.Adding
Information_Activity.this.finish()
fixed the broken functionality , though you are all correct I can pick only one answer.
Thanks

Using buttons on android - newbie

I am a newbie to android development, trying to get buttons working. every time i use this code below, the error message "unfortunately the app has stopped". but when i remove the code the app runs but obviously the buttons do nothing. here is the code ive tried
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.ExerciseButton);
button1.setOnClickListener (new View.OnClickListener(){
public void onClick(View v) {
setContentView(R.layout.exercises);
}
});
}
}
anybody able to help me out there? thanks
Don't try to load another View in the current activity. Navigate to a new ExercisesActivity.
Use:
public void onClick(View v) {
Intent intent = new Intent(ExercisesActivity.this, WcActivity.class);
startActivity(intent);
}
You can't call setContentView anymore after the view has loaded (which it obviously has to receive button clicks). Use a different approach, like showing and hiding views or using a ViewFlipper (see Calling setContentView() multiple times), using fragments (see Fragments) or starting a new activity.
Well, from your code, I see a couple of things:
I am usually familiar to using the onClickListener of the Button class if I want to use it for a button. Makes sense, doesn't it?
buttonOne.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//Do stuff here
}
Second thing:
Start a new Activity (if that is what you want) by using an Intent:
Intent myIntent = new Intent(this, exercises.class);
startActivity(myIntent);
You CAN absolutaly call setContentView on any event, even after the view has loaded
I tried your code in a demo project and it is working fine. So, i think the error will be some where in your layout.(Let me know more if you need more help on this)

Switching back to previous activity in tabhost

I am using TabActivity(for example, TActivity) to create tab and in every tab I am loading instance of same activity(for example, MainActivity).
Through this activity I want to switch another activitity(for example, ChildActivity which will be same for every tab i.e. in every tab we will get instance of this activity) using Button click.
This button is hardcoded in original TabActivity(TActivity).
Now I am able to do up to this. But Now I want to switch between 'MainActivity' and 'ChildActivity' using same Button.
MainActivity:
class MainActivity ...{
onCreate(){
Btn.setOnClickListener(new OnClickListener(--) {
public void onClick(--){
Intent intent = new Intent(getBaseContext(),ChildActivity.class);
replaceContentView("MainActivity", intent);
}});
}//MainActivity
public void replaceContentView(String id, Intent newIntent) {
View view = getLocalActivityManager().startActivity(id,newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)) .getDecorView(); this.setContentView(view);
}//replaceContentView
in ChildActivity:
public void hideCurrentActivity(){
Intent intent = new Intent(getBaseContext(),MainActivity.class);
replaceContentView("ChildActivity", intent);
}
public void replaceContentView(String id, Intent newIntent) {
View view = getLocalActivityManager().startActivity(id,newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) .getDecorView(); this.setContentView(view);
}
Ok, now problem is that this code creates fresh activity everytime. So all previous data is getting lost once I switch to previous activity.But i don't want to create fresh activity instead just want to bring old one to front.
Can anybody help?
Thanks in advance.

How to program efficiently? When pressed button create corresponding activity

I'm new to programming so I have a really easy question. Since I do not really know the terms I couldn't find any topic on my problem, so excuse me if this question has been asked before.
My problem is as follows: I'm running an app, created with Eclipse, on an Android machine. On the first screen I have just a list of buttons:
layout_main:
<Button
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/alpha"
android:onClick="alpha" />
<Button
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/beta"
android:onClick="beta" />
If I press a button then the corresponding activity will start. I programmed the main activity as follow in order to do that:
main activity:
public void alpha(View view) {
Intent intent = new Intent(this, AlphaActivity.class);
startActivity(intent); }
public void beta(View view) {
Intent intent = new Intent(this, BetaActivity.class);
startActivity(intent); }
Since I have many buttons, I will have as many times the operation public void as seen above. Isn't there any way to program it more efficient? For example: Start new activity, if alpha was selected then start activity alpha, if beta was selected start activity beta, else do nothing.
You could apply the same listener to each button, not really sure if it's more efficient or even better style, but this will probably work. Something like:
public void buttonListen(View view)
{
Class clas;
int id = view.getId();
switch(id)
{
case R.id.alpha:
clas = AlphaActivity.class;
break;
case R.id.alpha:
clas = BetaActivity.class;
break;
...
case R.id.zeta:
clas = ZetaActivity.class;
break;
}
startActivity(new Intent(this, clas));
}
and assign the corresponding id in the XML as the next answer states.
you can give every button an id like this :
<Button
android:id="#+id/alpha"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/alpha"
/>
<Button
android:id="#+id/beta"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/beta"
/>
then in the main activity you can findviewbyid() to find the two buttons and give buttons onclicklistener,then you implements the onclicklistener like this :
public void onClick(View v) {
Intent i = new Intent();
switch(v.getid()){
case: R.id.alpha:
i.setClass(context,AlphaActivity.class);
break;
case: R.id.beta:
i.setClass(context,BetaActivity.class);
break;
}
startActivity(i);
}
hope that helps.
There are many different ways to achieve this and make it simpler. Not a single method will be "the best". What you are doing is probably down the list of "what I would not do".
Don't assign things in XML, it's harder to work with, cannot be really changed at running time and make it less portable when you have to maintain a lot of different layouts. Instead…
This is just ONE way to do it:
Instead of defining the onClick method in the XML, do it programatically.
Add an android id to your Views:
<Button
android:id="#+id/alpha_button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="#string/alpha" />
(the same for all the other buttons)
Note: don't use fill_parent, use match_parent (the former is deprecated and both do the same).
The in your Activity onCreate() method, right before you setContentView(R.layout.your_above_layout_with_the_buttons);
You can obtain a reference to each button:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.your_above_layout_with_the_buttons);
final TextView alphaButton = (TextView) findViewById(R.id.alpha_button);
//etc for the rest
// now add click listeners:
alphaButton.setOnClickListener(this);// more on this later
betaButton.setOnClickListener(this);
// etc.
}
Now your activity should be:
public class YourActivity extends Activity implements View.OnClickListener {
and somewhere in your activity you have to implement:
#Override
public void onClick(final View view) {
// which button was clicked? Different ways to tell… a simple one:
Intent intent;
switch (v.getId()) {
case R.id.alpha_button:
intent = new Intent(this, AlphaActivity.class);
break;
case R.id.beta_button:
intent = new Intent(this, BetaActivity.class);
break;
//etc.
}
if (intent != null) {
startActivity(intent);
}
}
There are many ways you could accomplish your goal.
Note: the best solution would be to add android:id to your layout file, but if for some reason you can't do that, you could use the button text.
A very simple (although not great) way to do it without changing your layout file much would be to look at the text on the button, if all buttons have unique text, and perform the action based on that.
public void onButtonClick(View view)
{
//Cast the click View into a Button
Button selectedButton = (Button) view;
Intent intent = new Intent();
String buttonText = selectedButton.getText().toString();
if(buttonText.equals("beta"))
{
intent = new Intent(this, BetaActivity.class);
}
else if(buttonText.equals("alpha"))
{
intent = new Intent(this AlphaActivity.class);
}
startActivity(intent);
}
Make sure to set the onClick for each button in the layout file to call this method
android:onClick="onButtonClick"
For your specific situation, you could could change the way you handle the calls from your buttons, for example, you could give the buttons IDs and check the IDs of the buttons in a single method.
<Button
android:id="#+id/alpha_button"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/alpha"
android:onClick="onButtonClick" />
<Button
android:id="#+id/beta_button"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/beta"
android:onClick="onButtonClick" />
public void onButtonClick(View view) {
Intent intent;
switch (view.getId()) {
case R.id.alpha_button:
intent = new Intent(this, AlphaActivity.class);
break;
case R.id.beta_button:
intent = new Intent(this, BetaActivity.class);
break;
default:
return;
}
startActivity(intent);
}
However, I would suggest that your current code is clear and concise so just leave it as it is. There are many ways to solve a problem, especially when it comes to designing software.
In general though, programming languages try to balance making code (and more importantly it's function or purpose) easy to read/understand while trying to keep the syntax as concise as possible. In time you will learn about the advantages and disadvantages of each language and it's syntax, some will be better at solving certain types of problem while being too verbose for solving others. For now just learn how Java works and try to understand why they have implemented each keyword and syntax element.

Categories