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();
}
Related
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();
}
});
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;
}
}
}
}
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();
}
});
I was working on a different code site before Android studio, and how they made buttons in a second activity open was different than here. So far I have my second activity button and it opens..
My fifthactivity.java is below
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fifth_layout);
Button button = (Button) findViewById(R.id.button10);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(FifthActivity.this, AmazonActivity.class);
FifthActivity.this.startActivity(intent);
}
});
}
}
I understand I need to make a new .java and a new layout to direct the button, I just need help with the code to put into my fifth activity.java
Below is my layout for the other button that i need to open.
<Button
tools:ignore="HardcodedText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="PlayStation"
android:drawableLeft="#drawable/playstation"
android:drawableStart="#drawable/playstation"
android:layout_weight="0.07"
android:textSize="35sp"
android:id="#+id/button5" />
Button button;
Button anotherButton; // the second button OP required
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fifth_layout);
Button button = (Button) findViewById(R.id.button10);
anotherButton = (Button)findViewById(R.id.button5);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(FifthActivity.this, AmazonActivity.class);
FifthActivity.this.startActivity(intent);
}
});
/* new button to open a new activity */
anotherButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// creating the intent
Intent intent = new Intent(FifthActivity.this, AnotherActivity.class);
// starting activity with the created intent
startActivity(intent);
}
});
}
}
Add new Button to your xml file and style it how do you like and add new id like
android:id="#+id/button6" :
<Button
tools:ignore="HardcodedText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="PlayStation"
android:drawableLeft="#drawable/playstation"
android:drawableStart="#drawable/playstation"
android:layout_weight="0.07"
android:textSize="35sp"
android:id="#+id/button5" />
<Button
android:id="#+id/button6"
tools:ignore="HardcodedText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SomeText"
android:textSize="35sp" />
In your fifthactivity.java add new Button:
Button button, button2;
and, like your previous button, add click listener to that button. Create new Java class with its own layout and open it thru Intent with that button.
So I have seen multiple examples of this done and for some reason I cannot get onSaveInstanceState to save the value of my EditText properly.
I have a very simple example that looks just like the image below.
first a TextView, then an EditText followed by a Button.
When clicking the Button it saves the value in EditText and then applies it to the TextView.
So the problem is it only works once, meaning I start in Portrait mode then turn my phone to Landscape and it saves then back to Portrait and it does not so the TextView appears blank.
My Example code is below:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="50dp"
android:paddingLeft="50dp"
android:paddingRight="50dp"
android:paddingTop="50dp"
tools:context="mydomain.com.savetest.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Default Text"
android:textSize="48sp"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:hint="choose a word"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SAVE WORD"
android:id="#+id/bu"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
MainActivity.java
package mydomain.com.savetest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
private EditText mEditText;
private Button mButton;
private String editTextValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.textView);
mEditText = (EditText) findViewById(R.id.editText);
mButton = (Button) findViewById(R.id.button);
editTextValue = mEditText.getText().toString();
mTextView.setText(editTextValue);
if(savedInstanceState != null){
mTextView.setText( savedInstanceState.getString("text") ); //setting the saved value to the TextView
}
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editTextValue = mEditText.getText().toString();
mTextView.setText(editTextValue);
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("text", editTextValue); //saving EditText value
}
}
So the whole goal of this is to get the TextView to save the word that was int the EditText and maintain it switching from portrait to landscape. As of now if I type lets say "Car" it will update the TextView with "Car" and will also have the value of Car even turning to Landscape mode, BUT when turning back to portrait the TextView value is gone and has nothing. I Cant seem to figure out whats going on here because I have set the value of EditText to TextView in the beginning on onCreate() so when the app starts again it should take the saved value just fine.
You have to get the current text directly from EditText instead of relying on a String variable being initialized in OnClickListener() once. It works only once because you've pressed the button once.. After the 2nd orientation change, the button wasn't pressed and hence String editTextValue is more likely null, because you would have to press the button after each orientation..
Change somethings as follows:
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//don't save EditText value in a variable, instead directly get it from the EditText.
outState.putString("text", mEditText.getText().toString());
}
also remove the variable initialization from OnClickListener() Its not needed
editTextValue = mEditText.getText().toString(); // remove this.