Get Value of a Edit Text field - android

I am learning how to create UI elements. I have created a few EditText input fields. On the click of a Button I want to capture the content typed into that input field.
<EditText android:id="#+id/name" android:width="220px" />
That's my field. How can I get the content?

By using getText():
Button mButton;
EditText mEdit;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton = (Button)findViewById(R.id.button);
mEdit = (EditText)findViewById(R.id.edittext);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("EditText", mEdit.getText().toString());
}
});
}

Get value from an EditText control in android. EditText getText property use to get value an EditText:
EditText txtname = findViewById(R.id.name);
String name = txtname.getText().toString();

I guess you will have to use this code when calling the "mEdit" your EditText object :
myActivity.this.mEdit.getText().toString()
Just make sure that the compiler know which EditText to call and use.

I hope this one should work:
Integer.valueOf(mEdit.getText().toString());
I tried Integer.getInteger() method instead of valueOf() - it didn't work.

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button rtn = (Button)findViewById(R.id.button);
EditText edit_text = (EditText)findViewById(R.id.edittext1);
rtn .setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("EditText value=", edit_text.getText().toString());
}
});
}

You might also want to take a look at Butter Knife. It aims at reducing the amount of boilerplate code by using annotation. Here is a simple example:
public class ExampleActivity extends ActionBarActivity {
#InjectView(R.id.name)
EditText nameEditText;
#InjectView(R.id.email)
EditText emailEditText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
Butterknife.inject(this);
}
#OnClick(R.id.submit)
public void onSubmit() {
Editable name = nameEditText.getText();
Editable email = emailEditText.getText();
}
}
Just add the following dependency to your build.gradle:
compile 'com.jakewharton:butterknife:x.y.z'
As an alternative there is also AndroidAnnotations.

Shortest & Simplest
getText(editText);
getText(button);
getText(textView);
Little Workaround
Just make method in your BaseActivity / create BaseActivity if you don't have.
public class BaseActivity extends AppCompatActivity{
public String getText(TextView tv) {
return tv.getText().toString().trim();
}
}
And extend your all activities by this BaseActivity.
public class YourActivity extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState){
getText(editText);
getText(button);
getText(textView);
}
}
Note that EditText, Button extends TextView, so I created only getText(TextView tv).

String value = YourEditText.getText().toString;

A more advanced way would be to use butterknife bindview. This eliminates redundant code.
In your gradle under dependencies; add this 2 lines.
compile('com.jakewharton:butterknife:8.5.1') {
exclude module: 'support-compat'
}
apt 'com.jakewharton:butterknife-compiler:8.5.1'
Then sync up.
Example binding edittext in MainActivity
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity {
#BindView(R.id.name) EditTextView mName;
...
public void onCreate(Bundle savedInstanceState){
ButterKnife.bind(this);
...
}
}
But this is an alternative once you feel more comfortable or starting to work with lots of data.

step 1 : create layout with name activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity"
android:background="#c6cabd"
>
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17dp"
android:textColor="#ff0e13"
/>
<EditText
android:id="#+id/et"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv"
android:hint="Input your country"
/>
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get EditText Text"
android:layout_below="#id/et"
/>
</RelativeLayout>
Step 2 : Create class Main.class
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
final TextView tv = (TextView) findViewById(R.id.tv);
final EditText et = (EditText) findViewById(R.id.et);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String country = et.getText().toString();
tv.setText("Your inputted country is : " + country);
}
});
}
}

If you are using Kotlin and wants to make it generic you can use the Extension function
Extension function:
fun EditText.getTextString(): String {
this.text.toString()
}
and call this method directly from your EditText
yourEditText.getTextString()

Try this code
final EditText editText = findViewById(R.id.name); // your edittext id in xml
Button submit = findViewById(R.id.submit_button); // your button id in xml
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String string = editText.getText().toString();
Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
}
});

Button kapatButon = (Button) findViewById(R.id.islemButonKapat);
Button hesaplaButon = (Button) findViewById(R.id.islemButonHesapla);
Button ayarlarButon = (Button) findViewById(R.id.islemButonAyarlar);
final EditText ders1Vize = (EditText) findViewById(R.id.ders1Vize);
final EditText ders1Final = (EditText) findViewById(R.id.ders1Final);
final EditText ders1Ortalama = (EditText) findViewById(R.id.ders1Ortalama);
//
final EditText ders2Vize = (EditText) findViewById(R.id.ders2Vize);
final EditText ders2Final = (EditText) findViewById(R.id.ders2Final);
final EditText ders2Ortalama = (EditText) findViewById(R.id.ders2Ortalama);
//
final EditText ders3Vize = (EditText) findViewById(R.id.ders3Vize);
final EditText ders3Final = (EditText) findViewById(R.id.ders3Final);
final EditText ders3Ortalama = (EditText) findViewById(R.id.ders3Ortalama);
//
final EditText ders4Vize = (EditText) findViewById(R.id.ders4Vize);
final EditText ders4Final = (EditText) findViewById(R.id.ders4Final);
final EditText ders4Ortalama = (EditText) findViewById(R.id.ders4Ortalama);
//
final EditText ders5Vize = (EditText) findViewById(R.id.ders5Vize);
final EditText ders5Final = (EditText) findViewById(R.id.ders5Final);
final EditText ders5Ortalama = (EditText) findViewById(R.id.ders5Ortalama);
//
final EditText ders6Vize = (EditText) findViewById(R.id.ders6Vize);
final EditText ders6Final = (EditText) findViewById(R.id.ders6Final);
final EditText ders6Ortalama = (EditText) findViewById(R.id.ders6Ortalama);
//
final EditText ders7Vize = (EditText) findViewById(R.id.ders7Vize);
final EditText ders7Final = (EditText) findViewById(R.id.ders7Final);
final EditText ders7Ortalama = (EditText) findViewById(R.id.ders7Ortalama);
//
/*
*
*
* */
kapatButon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// kapatma islemi
Toast.makeText(getApplicationContext(), "kapat",
Toast.LENGTH_LONG).show();
}
});
/*
*
*
* */
hesaplaButon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// hesap islemi
int d1v = Integer.parseInt(ders1Vize.getText().toString());
int d1f = Integer.parseInt(ders1Final.getText().toString());
int ort1 = (int) (d1v * 0.4 + d1f * 0.6);
ders1Ortalama.setText("" + ort1);
//
int d2v = Integer.parseInt(ders2Vize.getText().toString());
int d2f = Integer.parseInt(ders2Final.getText().toString());
int ort2 = (int) (d2v * 0.4 + d2f * 0.6);
ders2Ortalama.setText("" + ort2);
//
int d3v = Integer.parseInt(ders3Vize.getText().toString());
int d3f = Integer.parseInt(ders3Final.getText().toString());
int ort3 = (int) (d3v * 0.4 + d3f * 0.6);
ders3Ortalama.setText("" + ort3);
//
int d4v = Integer.parseInt(ders4Vize.getText().toString());
int d4f = Integer.parseInt(ders4Final.getText().toString());
int ort4 = (int) (d4v * 0.4 + d4f * 0.6);
ders4Ortalama.setText("" + ort4);
//
int d5v = Integer.parseInt(ders5Vize.getText().toString());
int d5f = Integer.parseInt(ders5Final.getText().toString());
int ort5 = (int) (d5v * 0.4 + d5f * 0.6);
ders5Ortalama.setText("" + ort5);
//
int d6v = Integer.parseInt(ders6Vize.getText().toString());
int d6f = Integer.parseInt(ders6Final.getText().toString());
int ort6 = (int) (d6v * 0.4 + d6f * 0.6);
ders6Ortalama.setText("" + ort6);
//
int d7v = Integer.parseInt(ders7Vize.getText().toString());
int d7f = Integer.parseInt(ders7Final.getText().toString());
int ort7 = (int) (d7v * 0.4 + d7f * 0.6);
ders7Ortalama.setText("" + ort7);
//
Toast.makeText(getApplicationContext(), "hesapla",
Toast.LENGTH_LONG).show();
}
});

Related

Where am I wrong setOnClickListener is always in red [duplicate]

This question already has answers here:
OnClickListener in Android Studio
(5 answers)
Closed 6 years ago.
I am new to android studio and tried a tutorial where the presenter demonstrated his program but when I type out the code I am persistently getting an error like Cannot resolve Symbol setOnClickListener where the setOnClickListener is highlighted in red.
TextView Resultant = (TextView) findViewById(R.id.Resultant);
EditText Percentage_Input = (EditText) findViewById(R.id.Percentage_Input);
EditText Number_Input = (EditText) findViewById(R.id.Percentage_Input);
#Override
public View findViewById(#IdRes int id) {
return super.findViewById(R.id.Percentage_Input);
}
Button calc_btn = (Button) findViewById(R.id.calc_btn);
calc_btn.setOnClickListener(new View.OnClickListener(){
public void onClick((View) view); {
float percent = Float.parseFloat(Percentage_Input.getText().toString());
float dec = percent/100;
float Qty = Float.parseFloat(Number_Input.getText().toString());
float total = dec*Qty;
Resultant.setText(Float.toString(total));
}
})
I think your code is not in the right place. I see you are overriding findViewById (I wonder why) and rest of your code is also at the same level. You need to put all this code within a lifecycle method.
Maybe in onCreate()
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView Resultant = (TextView) findViewById(R.id.Resultant);
EditText Percentage_Input = (EditText) findViewById(R.id.Percentage_Input);
EditText Number_Input = (EditText) findViewById(R.id.Percentage_Input);
Button calc_btn = (Button) findViewById(R.id.calc_btn);
calc_btn.setOnClickListener(new View.OnClickListener() {
public void onClick((View) view); {
float percent = Float.parseFloat(Percentage_Input.getText().toString());
float dec = percent / 100;
float Qty = Float.parseFloat(Number_Input.getText().toString());
float total = dec * Qty;
Resultant.setText(Float.toString(total));
}
});
}
Also you are missing a semicolon ; at the end of setting OnClickListener.
Move ; and put at the end, this:
TextView Resultant = (TextView) findViewById(R.id.Resultant);
EditText Percentage_Input = (EditText) findViewById(R.id.Percentage_Input);
EditText Number_Input = (EditText) findViewById(R.id.Percentage_Input);
#Override
public View findViewById(#IdRes int id) {
return super.findViewById(R.id.Percentage_Input);
}
Button calc_btn = (Button) findViewById(R.id.calc_btn);
calc_btn.setOnClickListener(new View.OnClickListener(){
public void onClick((View) view) {
float percent = Float.parseFloat(Percentage_Input.getText().toString());
float dec = percent/100;
float Qty = Float.parseFloat(Number_Input.getText().toString());
float total = dec*Qty;
Resultant.setText(Float.toString(total));
}
});
Remove you method findViewById, this is some weird stuff, returning always the same view.
Put the rest of your code inside onCreate and add the missing ; at the end.

Android run time error

I am a beginner Android developer and I have a runtime error in my code: when I want to run it in a emulator or a device it show "force close" massage. My log is here:
http://upir.ir/934/1_5e07a.jpg
My Java code:
public class Third extends Activity
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button d = (Button) findViewById(R.id.btn4);
d.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
dialog();
}
});
}
public void dialog(){
final Dialog dialog = new Dialog(Third.this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("واحد عدد وارد شده را انتخاب کنید");
dialog.show();
RadioGroup rg = (RadioGroup) dialog.findViewById(R.id.rg);
final RadioButton rb1 = (RadioButton) dialog.findViewById(R.id.rb1);
final RadioButton rb2 = (RadioButton) dialog.findViewById(R.id.rb2);
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
if(rb1.isChecked()) {
dialog.dismiss();
Button t = (Button)findViewById(R.id.btn5);
t.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EditText ft1 = (EditText)findViewById(R.id.f3);
TextView foot = (TextView)findViewById(R.id.foot);
TextView mile = (TextView)findViewById(R.id.mile);
TextView inch = (TextView)findViewById(R.id.inch);
TextView yard = (TextView)findViewById(R.id.yard);
TextView mm = (TextView)findViewById(R.id.millymeter);
TextView dm = (TextView)findViewById(R.id.decimeter);
TextView mim = (TextView)findViewById(R.id.micrometer);
TextView nm = (TextView)findViewById(R.id.nanometer);
TextView hand = (TextView)findViewById(R.id.hand);
TextView iron = (TextView)findViewById(R.id.iron);
TextView point = (TextView)findViewById(R.id.point);
if(ft1.getText().toString().length() == 0 ){return;}
int first = Integer.parseInt(ft1.getText().toString());
double equal = first *0.0328;
DecimalFormat formatf = new DecimalFormat("#.####");
String x = formatf.format(equal)+" فوت";
foot.setText(x);
first = Integer.parseInt(ft1.getText().toString());
equal = first * 0.000005;
DecimalFormat formatm = new DecimalFormat("#.####");
x = formatm .format(equal)+"مایل";
mile.setText(x);
equal = first * 0.393;
DecimalFormat formati = new DecimalFormat("#.####");
x = formati.format(equal)+"اینچ";
inch.setText(x);
equal = first * 0.0109;
DecimalFormat formaty = new DecimalFormat("#.#####");
x = formaty.format(equal)+"یارد";
yard.setText(x);
equal = first / 10;
DecimalFormat formatmi = new DecimalFormat("#.##");
x = formatmi.format(equal)+"دسی متر";
dm.setText(x);
int equalmm = first * 10;
x = equalmm+"میلی متر";
mm.setText(x);
int equalm = first * 10000;
x = equalm+"میکرو متر";
mim.setText(x);
int equaln = first * 10000000;
x = equaln + "نانو متر";
nm.setText(x);
equal = first * 0.098;
DecimalFormat formath = new DecimalFormat("#####.#####");
x = formath.format(equal)+"هَند";
hand.setText(x);
equal = first * 19;
x = equal+"آیرون";
iron.setText(x);
equal = first * 28;
x = equal+"پوینت";
point.setText(x);
}
});
}
You need to inflate your activity with a layout resource first before you can use the findViewById() method to retrieve views. If there's no layout, then there are no views which could possibly be found.
You are missing an important part. You need to add a view to your Activity in order to find the elements of that view like the Button you are trying to instantiate.
In your OnCreate method add this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.the_xml_file); //Here add the xml file with the view you want to show
Button d = (Button) findViewById(R.id.btn4);
d.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
dialog();
}
});
}
After your super.onCreate(savedInstanceState); are you setting the content view?
e.g.
setContentView(R.layout.nameofxmlfilehere);

Hi! How do I store the fields and display the results on a different activity ? Please

I want the fields entered by the user to be displayed as a list view of the studentnoText and courseField in a new activity..
public class Student extends Activity {
private String totalStudents [];
private EditText studentnoText;
private EditText studentnameText;
private EditText courseField;
private Spinner departmentSpinner;
private EditText dobField;
private Button registerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student);
studentnoText = (EditText) findViewById(R.id.studentnoText);
studentnameText = (EditText) findViewById(R.id.studentnameText);
dobField = (EditText) findViewById(R.id.dobField);
courseField = (EditText) findViewById(R.id.courseField);
departmentSpinner = (Spinner) findViewById(R.id.departmentSpinner);
registerButton = (Button) findViewById(R.id.registerButton);
}
public void registerButtonPressed (View view){
Log.v("Register","Register Pressed!");
}
}
USE PUT EXTRA TO SEND DATA
mIntent.putExtra("TEXT", studentnoText.gettext().toString());
mIntent.putExtra("TEXT_1", studentName.gettext().toString());
USE GET EXTRA TO GET DATA
String strNO,strName;
strNO= extras.getString("TEXT");
strName = extras.getString("TEXT_1");

how do call another class in android?

I have a problem. I do not know how to call a different class. the code is for a button (when you click the button a message appears in random) so i thought it would be better if i placed it in a different class as i have also used arrays.Now i do not know how to call the class.
This is my code.I want to call "Firstin" inside SecondActivity.
public class SecondActivity extends Activity {
private Firstin mFirst = new Firstin ();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//finds textview
final Text Ftext = (Text) findViewById(R.id.textView2);
#SuppressWarnings("unused")
final Text Stext = (Text) findViewById(R.id.textView3);
//finds button view
Button btnView = (Button) findViewById(R.id.button1);
#SuppressWarnings("unused")
Button btnView2 = (Button) findViewById(R.id.button2);
btnView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String Answer = mFirst.firstAnswer();
Ftext.setTextContent(Answer);
}
});
this is the class I'm trying to call:
package com.example.insultgenerator;
import java.util.Random;
public class Firstin {
public String firstAnswer(){
String [] mResults={
"its cool",
"we cool",
"im cool",
"he cool",
"she cool"
};
// the button was clicked so replace the answer label with answer
String Answer = "" ;
// the two double is a 'empty string
Random RandomGen = new Random();// telling the program to construct a random generator
int RandomNum= RandomGen.nextInt(mResults.length);
Answer = mResults[RandomNum];
return(Answer);
}
}
You should cast to TextView
final TextViewFtext = (TextView) findViewById(R.id.textView2);
#SuppressWarnings("unused")
final TextViewStext = (TextView) findViewById(R.id.textView3);
then use TextView.setText(...) method:
String Answer = mFirst.firstAnswer();
Ftext.setText(new Firstin().firstAnswer());
}
});
then last call the method from the other class with new Firstin().firstAnswer() which creates a instance of the class and executes the method.

I want to use a self made Class in android

I am currently new to Android Development and i am having a difficult time trying to use a self made class in my MainActivity Android class.
Let me give you an example;
I created a SquareArea class and want to use it in the MainActivity Class
public class SquareArea{
private double _length;
private double _width;
public SquareArea(double length , double width){
_length = length;
_width = width;
area();
}
private double area(){
return _length
}
}
When i instantiate the SquareClass in MainActivity class i want to be able to use the area() method and return when values that are Extracted from(EditText)
I want to use the value in order to place it in a text view;however this does not seem to happen.
I can do it with methods but i want to use my own classes instead.
Please help, I am getting frustrated with this.
///Below is my MainActivity Class///
public class MainActivity extends Activity {
EditText mEditText1;
EditText mEditText2;
EditText mEditText3;
TextView mTextView;
Button mButton;
Double value1, value2;
SquareArea sq1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText1 = (EditText) findViewById(R.id.editText1);
mEditText2 = (EditText) findViewById(R.id.editText2);
mEditText3 = (EditText) findViewById(R.id.editText3);
mTextView = (TextView) findViewById(R.id.textView1);
mEditText1.setBackgroundColor(Color.GREEN);
mEditText2.setBackgroundColor(Color.GREEN);
mEditText3.setBackgroundColor(Color.RED);
mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//When the button is clicked, call the calucate method.
// calculate();
try {
value1 = Double.parseDouble(mEditText1.getText().toString());
value2 = Double.parseDouble(mEditText2.getText().toString());
sq1 = new SquareArea(value1, value2);
mTextView.setText(sq1.toString());
} catch (NumberFormatException e) {
mTextView.setText("Please use numbers");
}
});
}
}
You declare area() private, so cannot you call it
public double area(){
return _length
}
and you just have to call your area()
mTextView.setText(String.ValueOf(sq1.area()));
I see several problems
mTextView.setText(sq1.toString());
The toString method in SquareArea is not overridden. So the toString will return the default information about the object (location in memory, name, etc.)
public SquareArea(double length , double width){
_length = length;
_width = width;
area();
}
In the code above, you are inside the constructor. Why are you calling area() from here? A constructor can't return anything and the result from area() is being lost because area() returns a double.
And lastly:
private double area(){
return _length
}
This method is private. It cannot be called from outside the class/object.
To make your code work this is what I would change.
public class SquareArea{
private double _length;
private double _width;
public SquareArea(double length , double width){
_length = length;
_width = width;
}
public double area(){
return _length * _width;
}
}
///Below is my MainActivity Class///
public class MainActivity extends Activity {
EditText mEditText1;
EditText mEditText2;
EditText mEditText3;
TextView mTextView;
Button mButton;
Double value1, value2;
SquareArea sq1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText1 = (EditText) findViewById(R.id.editText1);
mEditText2 = (EditText) findViewById(R.id.editText2);
mEditText3 = (EditText) findViewById(R.id.editText3);
mTextView = (TextView) findViewById(R.id.textView1);
mEditText1.setBackgroundColor(Color.GREEN);
mEditText2.setBackgroundColor(Color.GREEN);
mEditText3.setBackgroundColor(Color.RED);
mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//When the button is clicked, call the calucate method.
// calculate();
try {
value1 = Double.parseDouble(mEditText1.getText().toString());
value2 = Double.parseDouble(mEditText2.getText().toString());
sq1 = new SquareArea(value1, value2);
mTextView.setText(String.ValueOf(sq1.area()));
} catch (NumberFormatException e) {
mTextView.setText("Please use numbers");
}
});
}
}

Categories

Resources