How to update text field on button click? - java

I need help in the MainActivity.java coding such that the value of the text field is stored into a variable on button click so that i could use it for search query later.
The activity_main.xml contains the following:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:text="Search"
android:ems="10"
android:id="#+id/SearchText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:text="Search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/button2" />
Could anyone suggest what the MainActivity.java file should contain as to recieve the text value as i am new to coding?

Add onClick on your button
onClick:"btnClicked"
Like
<Button
android:text="Search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/button2"
android:onClick="btnClicked" />
Add these code in Java file
public void btnClicked(View view){
EditText et = (EditText)findViewById(R.id.SearchText);
String value = et.getText().toString();// your edit text value
}

//Variable to store value.
String variable;
//References to the views.
Button btnClick = (Button)findViewById(R.id.button2);
EditText etText = (EditText)findViewById(R.id.SearchText);
//Setting click to the button
btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
// Do Your stuff.
variable = etText.getText().toString();
}
});

what the MainActivity.java file should contain as to receive the text value as i am new to coding?
Write This Code in Your MainActivity.java Whatever you will give in Text field and click Button , It will update and show in Toast Message.
public class MainActivity extends Activity {
EditText et;
Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
et = (EditText)findViewById(R.id.SearchText);
bt = (Button)findViewById(R.id.button2);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String eText = et.getText().toString();
Toast.makeText(getApplicationContext(),"Your Text is here"+eText,Toast.LENGTH_SHORT).show();
}
});
}

String YOUR_VARIABLE = "";
Button btn= (Button)findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtText = (Edittext)findViewById(R.id.SearchText);
if(!edtText.isEmpty()){
YOUR_VARIABLE = edtText.getText().toString();
}
});
This will store your EditText text in your Variable
if you want to use That variable Globally you should make if public static

button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String value = SearchText.getText().toString();
}
});

Related

Button is not reacting to click

I created a simple activity that is intended to send two pieces of information to another activity. However, my button isn't registering any click events. Does anyone have any idea why this would be? I expected that by adding the onClick = "onClickWrite" to the XML file that they would be linked but there is no response when clicked. If anyone could help me out, I would greatly appreciate it. I have tried implementing the onClickListener, however, with that implementation, it throws an error on my Toasts.
Activity
public class InitializeClass extends Activity {
private Service service;
private Button button;
EditText infoOne;
EditText infoTwo;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.button_control);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(clicked);
infoOne= (EditText) findViewById(R.id.editText);
infoTwo= (EditText) findViewById(R.id.editText1);
}
private View.OnClickListener clicked = new View.OnClickListener(){
#Override
public void onClick(View view) {
if (service != null) {
int size = 100;
byte[] byteArray = new byte[size];
byte[] byteArrayTwo = new byte[size];
byteArray = infoOne.getText().toString().getBytes(Charset.defaultCharset());
byteArrayTwo= infoTwo.getText().toString().getBytes(Charset.defaultCharset());
if ((!(infoOne.getText().toString().isEmpty())) && (!(infoTwo.getText().toString().isEmpty()))) {
service.setInfo(byteArray);
service.setInfoTwo(byteArrayTwo);
intentMethod();
}
}
}
};
public void intentMethod() {
Intent intent = new Intent(this, DeviceScanActivity.class);
startActivity(intent);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".InitializeClass">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="#string/send_info"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColor="#color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText1" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="150dp"
android:ems="10"
android:inputType="textPersonName"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColorHint="#android:color/white"
android:textCursorDrawable="#drawable/color_cursor"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="info"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColorHint="#android:color/white"
android:textCursorDrawable="#drawable/color_cursor"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText" />
</android.support.constraint.ConstraintLayout>
You need to initialize your button first.
Button button = (Button) findViewById(R.id.button);
Hope this helps!
In your activity class assign the button to the id of the button in the xml:
private Button btn = findViewById(R.id.button);
You will then create an OnClickListener:
private View.OnClickListener clicked = new View.OnClickListener(){
#Override
public void onClick(View view) {
//Insert Code here
}
};
In your onCreate method in the same activity class you will instantiate the button and assign the button to the onClickListener:
btn = new Button(this);
btn.setOnClickListener(clicked);
There are couple of things you need to do for that.
Create Field.
private Button button;
Initialize button.
Button button = (Button) findViewById(R.id.button);
Set Listener on button.
button.setOnClickListener();
I found the answer. Service in if (service != null) was never being initialized. Stupid mistake on my part. Thanks, everyone for the help and directing me in a way to implement onClickListener!
You need to cast the button (name) with you Java code .
for example on xml you have id/button (name)
declare it on your Java file, and do the casting.
and the onClickListener will look like this :
Cast the button : Button button ;
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});

How to permanently remove a linearlayout?

In this program, I want to delete ll2 (LinearLayout) when mButton is pressed. I.e I don't want this layout to appear the second time I enter this activity. When I push the button, the layout is gone for as long as I am in the activity, but when I come back into the activity, the layout is there.
How do I permanently delete it? Thanks in advance!
LinearLayout ll,ll2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
location_btn = (Button)findViewById(R.id.location_btn);
menu_btn = (Button)findViewById(R.id.bt_menu);
mButton = (Button) findViewById(R.id.buttone);
mEdit = (EditText) findViewById(R.id.edittexte);
ll2 = (LinearLayout)findViewById(R.id.llayout);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
number = mEdit.getText().toString();
mEdit.setText("");
ll2.setVisibility(View.GONE);
ll2.removeAllViewsInLayout();
}
});
}
My layout file
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/llayout"
android:visibility="visible">
<EditText
android:id="#+id/edittexte"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName"
android:text="Name" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="SAVE"
android:id="#+id/buttone"/>
</LinearLayout>
Just keep a SharedPreference and save the state that you have pressed the button earlier. Then each time you enter the activity, check the value stored in your SharedPreference and if its found that the button is already pressed before, just hide the LinearLayout.
LinearLayout ll,ll2;
SharedPreference pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
pref = getSharedPreferences("MyApplication", Activity.MODE_PRIVATE);
location_btn = (Button)findViewById(R.id.location_btn);
menu_btn = (Button)findViewById(R.id.bt_menu);
mButton = (Button) findViewById(R.id.buttone);
mEdit = (EditText) findViewById(R.id.edittexte);
ll2 = (LinearLayout)findViewById(R.id.llayout);
// Check the preference value when activity is launched each time and hide of the button was pressed before
if(pref.getBoolean("ButtonPressed", false)) ll2.setVisibility(View.GONE);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
number = mEdit.getText().toString();
mEdit.setText("");
// Save the sate of the button pressed in the SharedPreference
pref.edit().putBoolean("ButtonPressed", true).apply();
ll2.setVisibility(View.GONE);
}
});
}
You can try saving a boolean in SharedPreferences...
For e.g.
Keep the boolean as false in the beginning.
As soon as you press the button, remove the View (LinearLayout), change the boolean to true & save it to SharedPreferences...
In the onCreate(),
try as
if(booleanisTrue) {
ll2.setVisibility(View.GONE);
ll2.removeAllViewsInLayout();
}

When I try to get the text of an EditText it throws a Null Pointer Exception. [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Okay, this is my first post to stack so please bear with me. I have searched and have tried many things. I think another set of eyes might see something I don't. I get the NPE when i call the getText() function. I have included my scaled down version of my code, but the same error is happening. I have even looked that I have the right View any help will be appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ArrayList<Task> taskList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater inflater2 = (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View customView2 = inflater2.inflate(R.layout.task_add_operations,null);
final PopupWindow mPopupWindow2 = new PopupWindow(customView2,
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT, true);
Button closeButton2 = (Button)customView2.findViewById(R.id.closeButton2);
closeButton2.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View view) {
mPopupWindow2.dismiss();
}
});
Button addButton = (Button)customView2.findViewById(R.id.addButton);
addButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View customView2) {
EditText text = customView2.findViewById(R.id.editText);
//This is where my java.lang.NullPointerException pops
String title = text.getText().toString();
taskList = Task.addTask(taskList, title);
mPopupWindow2.dismiss();
}
});
mPopupWindow2.showAtLocation(findViewById(R.id.activityMain),
CENTER,0, 0);
}
});
}
task_add_operations.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="74dp"
android:text="Add Task"
android:textSize="18sp" />
<EditText
android:id="#+id/editText"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="text"
android:text="Title" />
<Button
android:id="#+id/closeButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText"
android:layout_alignStart="#+id/editText"
android:layout_below="#+id/editText"
android:layout_marginTop="28dp"
android:text="Cancel" />
<Button
android:id="#+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/closeButton2"
android:layout_alignBottom="#+id/closeButton2"
android:layout_alignEnd="#+id/editText"
android:layout_alignRight="#+id/editText"
android:text="Add Task" />
</RelativeLayout>
You need to Bind Your EditText Outside addButton.setOnClickListener
EditText text =(EditText) customView2.findViewById(R.id.editText);
OR Try this change the view name of public void onClick(View View2) method like below code
Button addButton = (Button)customView2.findViewById(R.id.addButton);
addButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View View2) {
EditText text = (EditText)customView2.findViewById(R.id.editText);
//This is where my java.lang.NullPointerException pops
String title = text.getText().toString();
taskList = Task.addTask(taskList, title);
mPopupWindow2.dismiss();
}
});
From looking at this other Stack Overflow post:
Null Pointer Exception - Getting EditText Value
Looks like you might want to try to declare the EditText in OnCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addButton = (Button)customView2.findViewById(R.id.addButton);
EditText text = customView2.findViewById(R.id.editText);
addButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View customView2) {
//This is where my java.lang.NullPointerException pops
String title = text.getText().toString();
taskList = Task.addTask(taskList, title);
mPopupWindow2.dismiss();
}
});

Android application with switch statement crashes on my phone

When I run this code on my Android Phone, it keeps on crashing.
My java code is as follows
public class MainActivity extends Activity {
EditText edit = (EditText) findViewById(R.id.text);
Button button = (Button) findViewById(R.id.button);
String string = edit.getText().toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (string){
case "c":
MediaPlayer mp1 = MediaPlayer.create(getApplicationContext(), R.raw.sample1);
mp1.start();
break;
My XML code:
<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="pembroke.com.example.algorhythmic.MainActivity">
<EditText
android:id="#+id/box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="308dp" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.781" />
The code is crashing, but I don't know why. I might not be using the string correctly.
No errors in the code but it is still crashing. Is it because the Android IDE can't compute my code?
There are 3 problems with the code :
For doing the findViewById, we do this after setContentView in onCreate method of activity. This is because, before setContentView, all views are null. Hence, I moved the findViewById code for both EditText and button after setContentView(R.layout.activity_main) in onCreate method of activity.
For the edittext, the ID which you used is R.id.text in java code, but in xml, it is R.id.box. So I have changed that to R.id.box in java code when doing the findViewById.
To find the value present in EditText, we have to get text present in EditText inside the onClickListener since the value inside EditText keeps on changing as user enters inside EditText.
Hence we assign the value to variable string inside the onClickListener's onClick method.
So final code would be :
public class MainActivity extends Activity {
EditText edit;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText) findViewById(R.id.box);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String string = edit.getText().toString();
switch (string){
case "c":
MediaPlayer mp1 = MediaPlayer.create(getApplicationContext(), R.raw.sample1);
mp1.start();
break;
}
}
}
}

How to add a reset button to clear numbers on Edittext field

I want to add a button to clear the numbers on textfield by tapping on the button.
(Reset my EditText back to an empty "space" after a button has pressed that would have completed an activity with input from the EditText field.)
Cheers! Thanks!
ActivityMain XML file!
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/back"
android:orientation="vertical"
tools:context="com.miuapps.unitconverter.Centimetres_Metres" >
<TextView
android:id="#+id/textView1" //first textview
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter a Value(cm) :"
android:layout_gravity="center"
android:gravity="center"
android:textSize="30dp"/>
<EditText
android:id="#+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number" />
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Convert" />
<TextView
android:id="#+id/tvDisplay1" //output textview
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="In Metres: 0"
android:textSize="30dp" />
</LinearLayout>
double counter, counter2 = 100;
double x;
Button conv;
TextView dis1, dis2;
EditText ent1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
conv = (Button)findViewById(R.id.button1);
dis1 = (TextView)findViewById(R.id.tvDisplay1);
//dis2 = (TextView)findViewById(R.id.tvDisplay2);
ent1 = (EditText)findViewById(R.id.editText1);
conv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
x = new Integer(ent1.getText().toString());
counter = x/100;
//counter2++;
dis1.setText("In Metres: " +counter);
//dis2.setText("In Centimetres: " +counter2);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
How about this:
ent1.setText("");
just put it at the end of your onClick Method
Edit:
conv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// here you get the text from your editText
x = new Integer(ent1.getText().toString());
// do something with the text
counter = x/100;
// set result in another TextView
dis1.setText("In Metres: " +counter);
// work is done, so the editText can be cleared
ent1.setText("");
}
});
Edit 2 (reset button):
resetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// reset only by another button
ent1.setText("");
}
});
Simply add a button in your layout.
<Button
android:id="#+id/buttonReset"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Reset" />
Find that button in your activity:
Button mButtonReset = (Button) findViewById(R.id.buttonReset);
mButtonReset.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view){
ent1.setText("");
}
});
First Create Design,
Activity_main.xml like below,
<EditText
android:id="#+id/txt_1"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:ems="10"
android:hint="Enter Name"
android:inputType="textPersonName"
android:minHeight="48dp" />
<Button
android:id="#+id/btn_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Button" />
<Button
android:id="#+id/btn_cln"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Clear" />
**Then go to MainActivity.java edit code like below, **
**
public class MainActivity extends AppCompatActivity {
Button button,button2;
EditText editText;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btn_ok);
editText = findViewById(R.id.txt_1);
button2 = findViewById(R.id.btn_cln);
//create text add button
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = editText.getText().toString();
}
});
//clean,reset text button
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editText.setText("");
}
});
}
}
**

Categories

Resources