Android (student cw) in need of direction - android

public class Menu extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
//myIntent.setClassName("hello.World", "hello.World.mybuttonclick");
// myIntent.putExtra("com.android.samples.SpecialValue", "Hello, Joe!"); // key/value pair, where key needs current package prefix.
//startActivity(myIntent);
//Button myButton = (Button) findViewById(R.id.my_button);
super.onCreate(icicle);
setContentView(R.layout.main);
}
public void updateLayout(){
Intent myIntent = new Intent(Menu.this, mybuttonclick.class);
startActivity(myIntent);
// TextView sayHello = (TextView) findViewById(R.id.Hello);
}
}
Hey guys, I am a new android java student and we have to develop a simple hello world app.. I am finding some difficulty getting my onClick() activity to work, using android:Onclick in xml.. what i am trying to do is change the content view do display a simply a different layout and saying hello.. i am using setContentLayout to do this, every time i click said button tho the android app crashes out.. am i doing something wrong?
regards,
Stefan

When you set a click listener in xml you must have the method defined inside the activity you are clicking in. Lets say you set the onClick in xml to be "buttonClicked", you must create a method looking exactly like the one below.
public void buttonClicked(View view)
{
//Your code here
}
The thing to notice is that the method is a public void with only a single parameter of type View. XML defined click listeners must be like this to work. The view object in the example above is the view that was clicked.

You update layout function needs to read
public void updateLayout(View view)

In response to your question, there are a number of things that are issues causing the complication that you described. Let it first be said, that you don't have to do anything any particular way, provided that you make concessions for certain things. Android is a very flexible platform and Java, as an OOP language allows you to do things that many non OOP languages do not.
Whenever you create a "clickable" item, like a Button, if you want to have your program respond, you must have something "listen" to it. This is known as a Listener. In your case, you are looking for an OnClickListener. The OnClickListener does not have to be a part of the Activity necessarily. It just has to be a class that implements View.OnClickListener. Then, you have tell the setOnClickListener() method of the Button who its listener is. The following example shows what is necessary without your declaration in XML (but it is important).
class Menu extends Activity implements View.OnClickListener
{
public void onCreate(Bundle icicle)
{ setContentView(R.layout.main);
Button btn = (Button)findViewById(R.id.BUTTON_ID_AS_DEFINED_BY_YOUR_XML);
btn.setOnClickListener(this);
}
public void onClick(View view)
{ int id = view.getId();
if (id == R.id.BUTTON_ID_AS_DEFINED_BY_YOUR_XML)
updateLayout()//Do your Click event here
}
public void updateLayout()
{ //updateLayout code...
}
}
Something that needs to be noted is the OnClick() above. Every OnClickListener must use the same signature as theOnClick() That means itmust have the same return and same arguments even if it has a different name. For what you are trying to do (in XML), you have set your android:OnClick to updateLayout. This means that `updateLayout() must be declared as follows:
public void updateLayout(View view)
Now, getting the update method to actually work: While you provide your code, we don't actually know what errors you are getting. It is always much easier to solve a problem if we have a copy of the Logcat output that includes the error you are receiving. Once, we have that we can target your error specifically and I can edit my answer to include what you may additionally need.
FuzzicalLogic

Related

How to create an activity with its corresponding XML file just tapping a button

I'm programming an app which one of its functionalities is that the users can tap on a plus button (typical (+)...) that has to create a new activity and a new XML file with a specific structure.
I'm beginner on Android and also in Stack Overflow, so due to that I'm unable to post images and make this question easier to understand.
I need you to summarize how to program this. I'm not telling you to codify my code, I just need to know if it's possible to do and ,more or less, the steps to get it.
Hope you can help me. Thanks!
Okay, so this is how you'd do it, if you're sure you want to create a new instance of the activity from that very same activity. First, make a reference to your "plus button". Assuming the android:id="#+id/plusButton, it'd be like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
//Initialize your layout and variables
findViewById(R.id.plusButton).setOnClickListener(new View.onClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
}
This would launch a new instance of the same Activity (MainActivity) and give it focus.
You can make the activity yourself and have a button open the activity.
You'd start by making a new android activity. With eclipse it's simply File >> New >> Other >> Android Activity and then just fill out the form and hit finish. Make sure your current project is open.
Draw the button in your xml file, make sure it has a unique Id to reference and your text is declared in your strings.xml file that should look like this.
<string name="strX">(x)</string>
then in your activity's xml file under your button make sure you have
android:text="#string/strX"
You can also reference this in the GUI in the properties window under text.
With the button code in your .java you could use OnClickListener and Intent and the code for the button would look something like this.
TextView buttonYourButton = (TextView) findViewById(R.id.ButtonYourButtonId);
Button pushYourButton = (Button) buttonPlay;
pushYourButton.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
Intent nameOfIntent = new Intent(NameOfCurrentClass.this, NameOfNewClass.class);
startActivity(nameOfIntent);
}
});
R.id.ButtonYourButton is the Id you gave the button, and the .class is the name of the public class in that .java file. Like:
public class MainActivity { ...
Anyways, good luck I was where you were about a month ago. Don't forget to check out tutorials on Android development on youtube, there are about a million of them. Also you can search stackoverflow for questions that already have been asked.

Pass reference of one Activity to another Activity

I know that I can pass some values between Activities using intent.
However, if I want to pass whole Activity to another Activity I think it is not good approach.
Is there another way to do that?
I have Settings Activity in which I am changing some Colors. So after I come back to my Main Activity I would like to apply those colors. To do this, I need access to MainActivity fields after I change Color value, so inside PreferenceActivity. In other words, I want to have access to Main activity fields from PreferenceActivity class. Any ideas?
You should be using a SharedPreference and then accessing that in your main activity. I recommend you reading up at http://developer.android.com/guide/topics/ui/settings.html because it seems like you are implementing your settings activity incorrectly. The part you might be specifically interested in is the "Read Preferences" section. However, I strongly suggest you read through the whole thing and then implement your settings the proper way.
Updated answer with the 3 different ways (that I can think of):
1) Start your preference activity using startActivityForResult(), then in your onActivityResult() access the SharedPreference and make your necessary changes. See here
2) Register a SharedPreferenceChangeListener with your MainActivity, which will be called when any changes happen to your SharedPreference. See here for a detailed discussion. Also see my initial response.
3) In your MainActivity's onResume(), access the SharedPreference and then make your changes there. I do not like this method because you will be cluttering onResume() with more logic and you will also probably have to have a variable that keeps track of the state of the variable you are interested in.
I would personally go with option 2 because the callback was created for this exact purpose.
I think you could pass the value by using method putExtra(name, value).
And after you start new activity you can get the value you pass before by using method getStringExtra(name).
Shared preferences can be used. If you want your changes to be reflected right away add listener. Refer to SharedPreferences.onSharedPreferenceChangeListener. Its an easy way to do.
If you want to lots of changes required in many activity from you change in any one.
And access last modify data from all Activity and modify also.
for example.
Constants.java
public class Constants
{
public static String name;
}
In your MainActivity you have an editText.
MainActivity.java
public class MainActivity extends Activity {
private EditText yourName;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourName = (EditText) findViewById(R.id.yourName);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Constants.name = yourname.getText().toString();
Intent intent = new Intent(getApplicationContext(),Activity2.class);
startActivity(intent);
}
});
}
In your Activity2 you have an TextView and that getting value which you enter in MainActivity.java without pass in Intent.
Activity2.java
public class Activity2 extends Activity {
private TextView yourName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourName = (TextView) findViewById(R.id.tv_yourName);
// directly use ferom serializable class
yourname.setText(Constants.name);
}
like that you use many values from all activity and modify from all activity.

Android: Call listener manually from java code

Is there any way to call a listener manually from code?
More background information: I use a Spinner and a DatePicker. With the Spinner you can choose a reason for staying at home (maybe your ill, maybe you have vacation) and with the DatePicker you can choose the date how long you will not be available. With these two pieces of information I build up a string for a TextView and show the same data in a compact way. The building process for the string is set by some listeners which recognize changes on one of the two controls and build and set up the new string.
If I start the program and read some data from a server the string will not be build (clearly because nothing changed and no listener will called).
The workaround is to build the string in my own onLoaddata() method. But I think it would be smoother way to call one listener to build the string for me. I also can "call" a listener if I just do some fake .updateDate but I don't think it’s a good idea to create useless calls...
Maybe someone of you have a good hint for me?
Use the following pattern:
public class YourActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
// Some initialization here
findViewById(R.id.some_button).setOnClickListener(this);
...
// Here you want to update your view
updateTextView();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.some_button:
// Here you also want to update your view
updateTextView();
break;
...
}
}
private void updateTextView() {
// Here you update your view
...
}
}

Android App Button 'onClick'

I am creating a charity app for Android. The app consists of 4 pages, each with a button which, when clicked, should navigate the user to the next page.
-Currently using Eclipse SDK-
The first (welcome) page button works and the code for this is:
public class CharityAppActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button main = (Button) findViewById(R.id.mybutton);
main.setOnClickListener (new OnClickListener(){
#Override
public void onClick(View v) {
setContentView(R.layout.donate);
// TODO Auto-generated method stub
}
});
}
I am wondering where I should put the code for the other buttons?
(this java file is currently called CharityAppActivity.java)....
Any help would be gratefully received. I would be more than willing to offer you any more code if you need it to help me a little better
Ps. the pages are named main.xml, donate.xml, value.xml and thanks.xml
Activity is only one screen of application.
You should create more activities for every screen and do not try to only change content. It is not possible call setContentView() multiple times by default.
I suggest you try to more samples application from SDK directly, read some tutorials or book.
Like you are finding Button main = (Button) findViewById(R.id.mybutton);
find other buttons from your main activity and set their onClickHandler to invoke your different activities.
I am assuming all the four concerned buttons are in same layout.
You just need to create 4 Activities.
The OnClick method will call the next Activity using "startActivity"
#Override
public void onClick(View v) {
Intent it = new Intent(NextClass.class);
startActivity(it);
}

Android: Listener Pattern within onCreate()

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.

Categories

Resources