I found this on android developers when i was trying to program a button:android developers blog: UI framework changes in Android 1.6
With Android 1.6, none of this is necessary. All you have to do is declare a public method in your Activity to handle the click (the method must have one View argument):
class MyActivity extends Activity { public void myClickHandler(View target){
// Do stuff
}
}
And then reference this method from your XML layout:
<Button android:onClick="myClickHandler" />
can smeone please explain this code to me? I am a beginner in programming, and I don't know what to put in the //do stuff space? I need to reference another activity so i can open another screen. And do i still need to have an activity and put a block of program in the class? this is the code i am using in the class at the moment. Please tell me if i need to update it to use this method:
package com.duncan.hello.world;
import com.duncan.hello.world.R;
import android.app.Activity;
import android.os.Bundle;
public class OtherActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
}
}
You put what you want to happen when the button is clicked in the // do stuff part.
You only need to update your code if you're using a button click handler in this fashion.
You might want to start with something a bit simpler, and perhaps not target Android 1.6.
Related
I am new to android studio and when i am about to start ,the error is noticed by me in the below snippet.i have recognised it by an indication in android studio.U can see below image to trace out my issue.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
}
when i go through that by clicking it shows 720 errors.What might be reason behind this and how to solve.Please help me.
http://i.stack.imgur.com/EayEp.png
This is standard practice. Your code should compile and run as is (judging by the screenshot at least)
Are you referring to the 720 errors in the actual system's class' onCreate method? That's the Android's system inner workings and you have no reason to go there right now as a beginner.
For instance, the mainActivity.java file is really clustered and to keep it clean i created a second .java(class) where i will execute some code upon a button press. I cannot figure out how to do it at all. And i am not sure what search terms to use either so i apologize if this has been covered.
Heres what i have in my "test" application.
I have a main activity with a single button on it.
package com.test.secondclass;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button startButton;
final Intent second = new Intent(getApplicationContext(), testClass.class);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton = (Button)findViewById(R.id.button1);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(second);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Now here is the "second" class that i made, now remember this is very short i am just using this for an exercise program before implementing it into my actual program.
package com.test.secondclass;
import android.app.Activity;
import android.widget.Toast;
public class testClass extends Activity{
public void onCreate(){
Toast.makeText(getApplicationContext(), "Second class thinger started", Toast.LENGTH_LONG).show();
}
}
And if i try this i get a force close immediately. If i comment out the "intent" part at the very beginning of my main activity then the program runs. But it doesnt do what i want. obviously. Thanks everyone
Add an OnClickListener to send whatever information to testClass, as shown below (untested):
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent secondIntent = new Intent();
secondIntent.setClassName(myPackageName, "testClass");
startActivityForResult(secondIntent, REQUEST_CODE);
});
References here and here.
Here's my viewpoint: you are receiving a forced close due the fact that you is trying to open user interface methods (such the Toast) with no context.
IMPORTANT: I'm assuming that you already defined both classes in the manifest.xml file!
Before explaining, I'll make a brief:
Toast: this class opens a quick message, receiving as main arguments the context, the message and the time-to-show;
The context: it is the "environment" where to show. Something like a visual scope, that defines the resources you have. In most cases, you can setup it with setContentView method.
Issue Explanation, in my opinion: The "crash" occurs because you opens the Toast message with no context. An activity is a UI control very similar to a viewpage. If you call a new activity, its very like to call a new page, and so, a new context. In the seccond activity, I haven't see any context. I think that you was assuming that the context is preserved from the first activity, but it ins't because its a new activity.
How to fix:
In the seccond class, define a layout view with setContentView, or...
Reimplement your seccond class as a Service, and call it through startService, or...
Define an AIDL mechams (similar to previous fix, but more sophisticated and complex, as it enables async method calls).
Hope it has helped in some way.
Thank you ALL for the answers!! I was actually able to do what i wanted by using the "stopSelf()" command after i displayed the Toast message. I implemented a service class and when i press the button the testClass.java class gets called and runs the "toast" message then immediately exits by the "stopSelf()" command. I made sure of this by including an "onDestroy()" method which also displayed a simple toast message confirming that the service was stopping :). I usually do stuff like this using threads but it was making the main activity really messy no matter how much formatting i did. So i wanted to have a seperate class i could use.
And to the commenter EfEs, i come from programming in C# language for windows. Android is a new playground for me and im still learning. i think im doing quite well but wasnt sure how to do what i asked. But i figured it out then. And thanks for clearing up that an Activity in android is like a "WindowsForm" in C# where it is completely new GUI for the user. I didnt know that. But thanks to all for helping me with your posts!
Ubuntu 11.10 ADT 16.01 Java 6 Eclipse Java EE Indigo SR1 - All latest release following android dev requirements.
I am just starting to learn coding for android and got to a tutorial on switching Activities. Using the New project android template, I made another test activity class identical to the first except for name.
package com.test.SwitchActivity;
import android.app.Activity;
import android.os.Bundle;
public class SwitchActivityActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
The problem is that when I use the Menifest editor edit the AndroidManifest.xml file - add button for the Application Node, the listbox is empty. All the tutorials I have found are populated with xml tag choices. Now, I can add the xml data manually - it is no problem. What is driving me nuts is not being able to figure out why it does not work for me as it is supposed to work. I don't find other people having the issue and I have re-installed everything at least once before coming here to post another question.
I just want to finish the tutorial and switch between two activities.
Here is a screenshot of what I describe. Anyone have any ideas as to why it does not work?
http://i.stack.imgur.com/Fwfbz.png
To create another activity
Create a new class "myactivity.java" that extends the Activity
Create android xml file with your UI items in it lets call it exampleactivity.xml (it should be in small letters with .xml extension and should be saved in res/layout folder).
In myactivity.java add the following method (same as above except exampleactivity replaced main)
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.exampleactivity);
}
}
create a button changeactivity in SwitchActivityActivity and initialize it in onCreate method of SwitchActivityActivity via
changeactivity = (Button) findViewById(R.id.newActivityButton);
create the following in onCreate method of SwitchActivityActivity
changeactivity.setOnClickListener(new OnClickListener() {
Intent i;
public void onClick(View v) {
i = new Intent(Intent.ACTION_DEFAULT);
i.setClass(SwitchActivityActivity.this, myactivity.class);
startActivity(i);
}
});
In the main.xml create a button and give the button id by
android:id="#+id/newActivityButton"
Finally add the following in AndroidManifest file after the SwitchActivityActivity activity tag
compile and run it.
Does anyone know the rationale behind the design of Android to destroy and re-create activities on a simple orientation change?
Shouldn't allowing the activity to just redraw itself (if it so chooses) be a better, simpler and more practical design?
BTW, I'm well aware of how to disable my app from orientation change effects, but what I don't really get is the reason for this design in Android
In docs,
http://developer.android.com/guide/topics/resources/runtime-changes.html
it states that,
The restart behavior is designed to help your application adapt to new configurations by automatically reloading your application with alternative resources.
Dont know exactly why, my guess is because it has to reconstruct the activity on the screen.
OnCreate takes in a variable "Bundle savedInstanceState". You can save the data in there for faster reloading.
package com.android.hello;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = new TextView(this);
if (savedInstanceState == null) {
mTextView.setText("Welcome to HelloAndroid!");
} else {
mTextView.setText("Welcome back.");
}
setContentView(mTextView);
}
private TextView mTextView = null;
}
This is pretty simple. Android destroys and recreates an activity on orientation changes so that you (the developer) have the option to keep on using the previous layout or use and implement another one.
In my application there are 14 activities. Out of that 9 activity contains custom title bar and tab pane. so here I need to write this common code at one place instead of redundant code in each activity that contain custom title bar and tab pane code (i.e layout and it's activity specific code)
What are the possible ways to do this?
The common way is:
Create a super class called, for instance, CommonActivity which extends Activity
Put the boilerplate code inside that class
Then make your activities extend CommonActivity instead of Activity:
Here a simple example:
public class CommonActivity extends Activity{
public void onCreate(Bundle b){
super.onCreate(b);
// code that is repeated
}
protected void moreRepeatitiveCode(){
}
}
And your current activities:
public class AnActivity extends CommonActivity{
public void onCreate(Bundle b){
super.onCreate(b);
// specific code
}
}
Hmm.. Common code doesn't always need to be in Activity class but just regular class. Than we could call those methods according to our needs referring to the common code class.
Am I right with this example?
Of course in case we need it like Activity, above proposal would work perfectly if we take care of Activity lifecycle and we don't forget to add it to manifest file.
In general Activities should just create UI, handle events occurrences and delegate business logic and/or other actions to the other components in our App.
Cheers