How to get input from an EditText field in Android? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
When coding for Android, there are two main ways I have seen to get text from an editText field. The first way seems to be very commonly used, and looks a little like this.
display = (EditText) findViewById(R.id.editText1);
displayContents = display.getText().toString();
displayTwo = (EditText) findViewById(R.id.editText2);
displayText = (Button) findViewById(R.id.button1);
displayText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayTwo.setText(displayContents);
}
This seems to use a clickListener in the mainActivity class to detect the click, then finds the value of the textfields.
However, when I was looking through Google's official Android tutorial, they used an alternative method. They first added this line of code to the button:
android:onClick="sendMessage";
and then had this method instead of the onClickListener:
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
After that, i created a new activity which made a new xml file with a different GUI, and a new class with the following:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
This seems to have the button broadcast a message rather than having a passive listener, and then trigger a new activity.
So after all that, I suppose my question would be which method is better to use? From both a technical and design standpoint, which one works with what situations? Like, when would I use each one?

I'm pretty new to android so I could be wrong, but pretty sure they are the same thing. When you add android:onClick="sendMessage";
it go's through the same type of listener, you just don't have to actually personally program that in yourself.
Which to use is arguably a personal preference I guess. Personally if things are easy such as click this to open an intent then I would use
public void sendMessage(View view)
But if I wanted the listener to parse variables through, or utilise variables within a specific method I guess, then it would be easier for me to create my own listener.

You can use any of the two methods mentioned above. There is no any technical difference in both of them.
And to learn about those thing go to this link af android developers
http://developer.android.com/develop/index.html

the second method in which the intent is used to pass the string to another activity is used only when you need to pass the string to a new activity.
if you have both of your edittexts in the same activity xml then go with the button clicklistener.
now to do something on button click we have to methods
with java listener
with xml onclick attribute
these methods will do the same thing , either one can be used.
you can create new activity using intent in java listener also with the same code.

Related

Transfer data from one screen to another [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
How to pass an object from one activity to another on Android
(35 answers)
Closed 4 years ago.
I am currently working on a project for my programming class, it is a d&d character creator I've decided to do for my final project. I am nearly finished with it but have run into one problem. I want to take the user's data from a screen where they create a character and store it into a screen where they can view their created characters, but I am not sure how to do this. This is the code from the create a character screen:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_char_screen);
Button btnSave = (Button)findViewById(R.id.btnSaveChar);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkData())
startActivity(new Intent(NewCharScreen.this, HomeScreen.class));
}
});
Button btnEx = (Button)findViewById(R.id.btnExplanation);
btnEx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(NewCharScreen.this, ExplanationScreen.class));
}
});
}
private boolean checkData(){
final EditText charName = (EditText) findViewById(R.id.txtNameInput);
if (charName.getText().toString().isEmpty()){
charName.setError("Enter character name");
charName.requestFocus();
return false;
}
return true;
}
}
If there is a need for the rest of my code or the project itself here is a link to a repository on GitHub:
https://github.com/cbetlinski98/MAD105-final_project
If you want to pass data from one activity to another one, you should pass it inside the Intent object, so intead of creating it inside StartActivity you can create it outside as a normal object, and use putExtra() to put data inside it.
Intent intent = new Intent(getBaseContext(), DestinationActivity.class);
intent.putExtra("OBJECT_PARAM_NAME", your_object);
startActivity(intent);
To recover data on the other activity you can use
String sessionId= getIntent().getStringExtra("OBJECT_PARAM_NAME");
Pass basic types
If you need to pass basic objects like int, float, strings, you can always pass them with putExtra() but to take them in the destination activity there are relative methods like getStringExtra() or getIntExtra() and many others.
Pass your class
If your user is a class defined by you, you can implement Serializable in that class, put it inside the intent with putExtra() and recover it from the other activity with getIntent().getSerializableExtra("OBJECT_PARAM_NAME") and then just cast it to your class before putting it inside an object
In order to pass information across intents:
Intent i = new Intent(this, Character.class);
myIntent.putExtra("paramKey","paramValue1");
startActivity(i);
Then in your activity to obtain the parameters:
Intent i2 = getIntent();
i2.getStringExtra("paramKey");
startActivity(new Intent(CurrentActivity.this, AnotherActivity.class).putExtra(KEY, DATA));

Double Click on Button Android

First off this question has been asked multiple times, however, none of these questions have been answered to any extent. I have one example that works in the main activity class:
final Button button = (Button) findViewById(R.id.viewcatalog);
button.setFocusable(true);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.find_item);
}
});
But all of my other attempts to replicate this in sequential pages has resulted in failure. I know the reason that they won't work the same way is that my buttons are instantiated in other classes and not in the host class. What is the correct way to fix this error?
The method that doesn't work for reference:
public void OnClickSearch(View view) {
final Button button = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText text = (EditText)findViewById(R.id.editText);
String value = text.getText().toString();
setContentView(R.layout.search_results);
}
});
}
It sounds like you are mis-understanding how the UI works in Android.
It is not normally expected that you will change an Activity's view on the fly as your are doing in your OnClickListener.
Instead, you should do one of two things. Either switch to a new Activity, using an Intent and the Activity's startActivity method, or use Fragments, and replace a Fragment in your Activity with a new Fragment.

Correct use of save button code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So I've been learning and trying to build upon an app I made by following an online tutorial. It is a simple, bare bones, note taking application. The mainActivity simply shows note objects in a list view. The second screen/activity is the one I'm currently working on, trying to add code where I can. So far I've added a save button that will simply save the text/string value and take the user back to the main activity. I would like some feedback as to my implementation of the onButtonSave method:
public class NoteEditorActivity extends Activity {
private NoteItem note;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_editor);
getActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = this.getIntent();
note = new NoteItem();
note.setKey(intent.getStringExtra("key"));
note.setText(intent.getStringExtra("text"));
EditText et = (EditText) findViewById(R.id.noteText);
et.setText(note.getText());
et.setSelection(note.getText().length());
// I'm wondering if this is the correct way to call my onButtonSave method
onButtonSave();
}
private void saveAndFinish() {
EditText et = (EditText) findViewById(R.id.noteText);
String noteText = et.getText().toString();
Intent intent = new Intent();
intent.putExtra("key", note.getKey());
intent.putExtra("text", noteText);
setResult(RESULT_OK, intent);
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
saveAndFinish();
}
return false;
}
#Override
public void onBackPressed() {
saveAndFinish();
}
// This is the code I've added for the save button.
public void onButtonSave(){
final Button button = (Button) findViewById(R.id.saveButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
button.setText("Saved!");
saveAndFinish(); }
});
}
}
I assume you are curious as to whether or not you have covered all your cases. Breaking up the setup of listeners and UI components from your onCreate into separate methods can be a good practice for easier readability when there are a lot of things being initialized.
You cover the case when the back button is used.
You cover the case when the user presses the button.
From what can be seen you also cover the case with the menu selection of leaving the screen. A couple people have talked best about how to detect whether the screen goes to the background or not. If you really want to catch all cases, you can do your save within the onPause() of an Activity. This will be fired if you press back, go home or call another activity.
Distinguishing between another activity and the home button is tough. But some people have pointed towards onUserHint() as a way to detect this. Just thought I would provide some feedback to what I can understand of your question.

Android: Determining clicked button in java file

I want to use the same xml file for displaying depending upon which button was clicked in the previous page. There is an xml template and depending upon the user's input the output will be shown.
Let's say there are 5 buttons and the layout of the output will be same for all but there will be difference in output data.
How can I get the id of the clicked button in the java file?
Can I use ImageView instead of buttons for the same purpose?
Thanks in advance!
1: You can create an onClickListener in your java class:
Button myButton = (Button) findViewById(R.id.mybutton);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
Or you can use set the click event in your layout-xml and ask the Id of the clicked view, see: How exactly does the android:onClick XML attribute differ from setOnClickListener?
2: You can use an ImageButton instead of a Button/Imageview
http://developer.android.com/reference/android/widget/ImageButton.html
Extra: sending info to next Activity
Bundle bundle = new Bundle();
bundle.putString("clickedTag", v.getTag());
intent.putExtras(bundle);
Tip: don't use the Id, but set the android:tag="ABC" to all your buttons, that's better to read than an integer Id.
To read the clickedTag use this inside your next Activity:
String tag = getIntent().getExtras().getString("clickedTag");

Change class view using buttons

I'm trying to have a program go from one class to another by the press of a button. I know this needs to be done with intent, but I'm not sure exactly what action to use for intent. Also, i would rather not try to use OnClickListener since it seems to me to be a bit excessive for what I need to do. Though I could be wrong and I'm just over thinking it. Here's what I have for the code:
public void loginScreen(View view) {
// Should take user to the next view when button pressed
Intent intent = new Intent(this, LoginActivity.class);
Button login = (Button) findViewById(R.id.button1);
intent.getData(login);
startActivity(intent);
}
I want it to go to the next screen when only button1 is pressed so i don't know if just lines 3 and 6 are the only ones needed, but it won't work if it's just those two. I believe the problem is getData, i don't know what to put there, but i know getData's wrong. I'm probably also missing something else, but I don't know what.
Also, forgive me if this isn't easy to follow, first time trying to ask a question here.
In your XML file you can declare your on click:
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="loginScreen" />
Then in your Activity:
public void loginScreen(View button) {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
Here is the onClick View API
Name of the method in this View's context to invoke when the view is
clicked. This name must correspond to a public method that takes
exactly one parameter of type View. For instance, if you specify
android:onClick="sayHello", you must declare a public void
sayHello(View v) method of your context (typically, your Activity).
Note that if you add an onClick to a Fragment layout it will still need to be caught in the Activity.
Without explicitly setting an onClickListener:
<button
...
android:onClick="loginClicked" />
public void loginClicked(View v) {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
Also setting an onClickListener explicitly is not overkill.
Your question isn't entirely clear, so let me know if you need more and I'll edit my answer.

Categories

Resources