LunchList Android App - java

I am new to Android Programming. I am doing this project from the book. I wrote the class to return the name and the address and then wrote the OnClickListener for it but it doesn't seem to work when i click the save Button. Here is my Two Java file:
package com.example.lunchlist;
public class Returant {
private String name="";
private String address="";
public String getName() {
return(name);
}
public void setName(String name) {
this.name=name;
}
public String getAddress() {
return(address);
}
public void setAddress(String address) {
this.address=address;
}
}
Here is my MainActivity File:
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
Returant r = new Returant();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button save = (Button) findViewById(R.id.save);
save.setOnClickListener(onSave);
}
private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {
EditText name=(EditText)findViewById(R.id.name);
EditText address=(EditText)findViewById(R.id.addr);
r.setName(name.getText().toString());
r.setAddress(address.getText().toString());
}
};
}

I believe once you click the save Button it suppose to return the name and the address that you have on the TextField
I have no idea why you would think that. The book certainly does not indicate that. I know this, because I wrote the book in question. Specifically, this would appear to be from my retired book, Android Programming Tutorials, specifically Tutorial #2.
In the most recent Creative Commons edition of the book (Version 3.4), the end of the tutorial steps for Tutorial #2 has:
Run the application to make sure it seems like it runs without errors,
though at this point we are not really using the data saved in the restaurant
object just yet.
All we are doing, at this point in the tutorials, is taking data out of EditText objects and putting it into a Restaurant (or, in your case, Returant).

You can just log the value and see the log.
Try adding these two lines in the OnClickListener.
Log.i(TAG, r.getName());
Log.i(TAG, r.getAddress());
If something is printed out, that means you successfully set the values to the variable.
public class MainActivity extends Activity {
Returant r = new Returant();
EditText name;
EditText address;
String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button save = (Button) findViewById(R.id.save);
name=(EditText)findViewById(R.id.name);
address=(EditText)findViewById(R.id.addr);
save.setOnClickListener(onSave);
}
private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {
r.setName(name.getText().toString());
r.setAddress(address.getText().toString());
Log.i(TAG, r.getName());
Log.i(TAG, r.getAddress());
}
};
}

Related

where to instantiate an anonymous class?

I am trying to use a code from this link https://developer.android.com/training/connect-devices-wirelessly/nsd.html
"from Discover Services on the Network."
I copy and paste code as the following:
import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button aButton = (Button) findViewById(R.id.MyButton);
aButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// there is an error in the next line, ";" expected.
// but I do not know where to put ; exactly
public void initializeRegistrationListener() {
mRegistrationListener = new NsdManager.RegistrationListener() {
#Override
public void onServiceRegistered(NsdServiceInfo NsdServiceInfo) {
// Save the service name. Android may have changed it in order to
// resolve a conflict, so update the name you initially requested
// with the name Android actually used.
mServiceName = NsdServiceInfo.getServiceName();
}
#Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// Registration failed! Put debugging code here to determine why.
}
#Override
public void onServiceUnregistered(NsdServiceInfo arg0) {
// Service has been unregistered. This only happens when you call
// NsdManager.unregisterService() and pass in this listener.
}
#Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// Unregistration failed. Put debugging code here to determine why.
}
};
} }
});
}
}
But there is an error in the this Line "public void initializeRegistrationListener()", ";" expected. but I do not know where to put ";" exactly or there is something else wrong that I cannot see it, can someone guide me, please?
PS: I am trying to make my phone discovers Mdns service that I created on my laptop using javascript, I have no experience in Java but I need to run the previous code to test the service that I have created already.
First of all you need an xml that contains an Button(this button will have android:id="#+id/mybutton", and that's the id you have to use on findViewById(R.id.mybutton).
In onCreate method of your activity you will write that code that you showed us, and you are good to go.
Another small step, if you wrote your own xml, make sure to have this line in onCreate
setContentView(R.layout.yourxml)

Java Variable Scope Global

im trying to understand variable scope with simple example.
I need help with this code
package com.varialescope.examplevariablescope;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button buttonOne;
private Button buttonTwo;
private String mText = "Hello World";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Initialialize UI elements
buttonOne = (Button) findViewById(R.id.button_one);
buttonOne = (Button) findViewById(R.id.button_two);
//Button One click listener
buttonOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Set new text
mText = "ONE";
Toast.makeText(MainActivity.this, mText, Toast.LENGTH_SHORT).show();
}
});
//Button Two click listener
buttonTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, mText, Toast.LENGTH_SHORT).show();
}
});
}
}
How can i access to mText string from click listener method ?
and how can i set a new string for mText clicking button One and make it accessible globally?
thanks for help
you create anonymous class Object for clicklistener any anonymous class or inner class object has information about the outside class object , then it had the right to access the methods and variables of the outside class object

Is findViewById() not be instanced?

I have a question about programming in android.
When I write a activity like this:
package com.mathquiz;
import android.widget.ImageButton;
public class ChooseMode extends ActionBarActivity {
private ImageButton easyButton=(ImageButton)findViewById(R.id.easy_button);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_mode);
easyButton.setVisibility(View.INVISIBLE);
}
The eclipse throws NullPointerException at line 4
However, if I assign "easyButton" in method onCreate, everything will be OK.
package com.mathquiz;
import android.widget.ImageButton;
public class ChooseMode extends ActionBarActivity {
private ImageButton easyButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_mode);
easyButton=(ImageButton)findViewById(R.id.easy_button);
easyButton.setVisibility(View.INVISIBLE);
}
Please help me to understand this problem.
It can't be "instanced" as you call it because in your first example, you haven't set a content view yet. Android's lifecycle methods have a specific order, that occur after the constructor is called.
The method works as expected, it just returns null because it has nothing to find at that current time.
Also, using an instance variable that requires using the current Activity as a Context will not work (In the below example, this refers to the ChooseMode instance).
Eg
public class ChooseMode extends ActionBarActivity {
private SharedPreferences = PreferenceManager.getDefaultSharedPreferences (this);
Will throw a NullPointerException down the line when used.
The layout is not defined on class variable definition. That's why it's a NullPointerException, because you haven't called setContentView(R.layout.activity_choose_mode); yet.
If you want to do that way, to avoid that amount of boilerplating, try RoboGuice. An example of a view could be this:
#ContentView(R.layout.main)
class RoboWay extends RoboActivity {
#InjectView(R.id.name) TextView name;
#InjectView(R.id.thumbnail) ImageView thumbnail;
#InjectResource(R.drawable.icon) Drawable icon;
#InjectResource(R.string.app_name) String myName;
#Inject LocationManager loc;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
name.setText( "Hello, " + myName );
}
}
More examples and tutorials are here.

Problems with OnClickListener

Hey am new to android , i just want to handle a click event , but i got problems ...thi sis my code:
package karim.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
public class TestActivity extends Activity implements android.view.View.OnClickListener {
private Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) this.findViewById(R.id.button1);
b1.setOnClickListener(this);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
#Override
public void onClick(View v) {
}
and i got this error :
Description Resource Path Location Type
The method onClick(View) of type TestActivity must override a superclass method TestActivity.java /Test/src/karim/test line 33 Java Problem
can you please tell me whats wrong ????
Please Be specific !!
My guess is that you're compiling with a Java 5 compiler (or Java 5 compiler settings in the IDE). In Java 5, #Override was only usable on a method overriding a method of a class, not an interface. It was extended to interface method overriding in Java 6.
Change the compiler version, or remove the #Override annotation on the onClick method.
You don't need to have your Activity class implement OnClickListener. Get rid of that. You just need to define the listener and assign it to your button. Take a look at the official android docs:
http://developer.android.com/guide/topics/ui/ui-events.html
public class TestActivity extends Activity{
private Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) this.findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
or in your case
public class TestActivity extends Activity implements android.view.View.OnClickListener {
private Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) this.findViewById(R.id.button1);
b1.setOnClickListener(this);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
#Override
public void onClick(View v) {
if(v==b1)
{
//button logic
}
}
As an extension to "JB Nizet" answer:
The neatest way to handle onClick-events is (in my opinion) to add the onClick-attribute to the XML-Layout definition.
<Button android:text="Click Me!"
android:onClick="doSomething"
/>
In your java-code:
public void doSomething(View v){
// Do stuff here
}
This way, you can define a single method for every single onClick-event. This is available since API-Level 4 which corresponds to Android 1.6
Looks like you are using compiler below java 6 for your project in eclipse. Right click on your project, go to properties-->Java compiler. Make sure you have 1.6 selected in compiler compliance field.

setOnClickListener in simple Android does not work

I try to learn JAVA and I try to write an app for Android. My Code is simple and often I've seen code like this. But when I push the second time a button, the message does not return. The first time it works. What is my error?
package com.test.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class HelloWorldApp extends Activity {
private Button closeButton;
private Button buttonAnswer1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonAnswer1 = (Button)findViewById(R.id.button1);
closeButton = (Button)findViewById(R.id.buttonEnde);
buttonAnswer1.setFocusable(false);
closeButton.setFocusable(false);
buttonAnswer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.main);
showToastMessage("1");
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.main);
showToastMessage("2");
}
});
}
private void showToastMessage(String msg){
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
}
}
Don't call the setContentView method inside the click listener:
buttonAnswer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showToastMessage("1");
}
});
In your onClick functions, you are replacing the entire content view, which will replace the existing button objects with new instances. These new instances no longer have any OnClickListeners.
There is no reason to replace the content view in this case, so the solution is to eliminate those calls from the onClick functions. But if for some reason you needed to replace the content view, then you would need to go through the entire process of finding the new buttons and calling setOnClickListener for each.

Categories