Change Pictures by clicking Button [duplicate] - java

This code, with the block at the top commented, runs successfully:
public class MainActivity extends AppCompatActivity {
/*
EditText username = (EditText)findViewById(R.id.editText_Username);
EditText password = (EditText)findViewById(R.id.editText_Password);
TextView inputdata = (TextView)findViewById(R.id.textView_InputData);
TextView welcome = (TextView)findViewById(R.id.textView_Welcome);
Button login=(Button)findViewById(R.id.button_Login);
Button anotherLogin=(Button)findViewById(R.id.button_Login_Another);
*/
public void doLoginOnClick(View v)
{
String s1=username.getText().toString();
inputdata.setText(s1);
}
#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)
{
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
I am trying to capture id of component using
findViewById(R.id.***)
as you can see, I put this code in comment at the very beginning of the code.
EditText username = (EditText)findViewById(R.id.editText_Username);
EditText password = (EditText)findViewById(R.id.editText_Password);
TextView inputdata = (TextView)findViewById(R.id.textView_InputData);
TextView welcome = (TextView)findViewById(R.id.textView_Welcome);
Button login=(Button)findViewById(R.id.button_Login);
Button anotherLogin=(Button)findViewById(R.id.button_Login_Another);
If I remove the comment above and run it (both in emulator and real device), the program crashes immediately, I am surprised what's wrong here?
even I have tried to initialize the same thing using constructor.
But if I put it inside onCreate() there's no crash? Why?
I was trying to fetch info of username and password and display it to the textview in textView_Inputdata using
EditText username = (EditText)findViewById(R.id.editText_Username);
EditText password = (EditText)findViewById(R.id.editText_Password);
TextView inputdata = (TextView)findViewById(R.id.textView_InputData);
inputdata.setText(username.getText.toString()+" "+password.getText.toString());
Is there better or easier way to do that?

Instance member variables are initialized when the instance itself is initialized. It's too early for findViewById()
Before onCreate() your activity does not yet have a Window that findViewById() needs internally. Before setContentView() (that you should be calling in onCreate()) there are no views to be found either.
Therefore init your view references in onCreate() and after setContentView().

Add this code
EditText username = findViewById(R.id.editText_Username);
EditText password = findViewById(R.id.editText_Password);
TextView inputdata = findViewById(R.id.textView_InputData);
TextView welcome = findViewById(R.id.textView_Welcome);
Button login = findViewById(R.id.button_Login);
Button anotherLogin = findViewById(R.id.button_Login_Another);
in
onCreate();
method after
setContentView(R.layout.activity_main);

Hey I see that you are defining and initialising the instance variables.
What I do is I define the the instance variables - EditText username and then in the onCreate method I initialise them - username = (EditText) findViewById(R.id.editText_Username);
The reason you don't initialize the instance variables is because the elements are not ready until after the setContentView in onCreate method - I could be wrong with this, but my best practice is define the instance variable and then initialize them in the onCreate method

Before setting setContentView() you are not able to initialize the view items.Because view will not be exists for activity at that time.
Keep the initializations in one separate method and call that method after setting the view to the activity.

You must call findViewById() after setContentView() in onCreate(), before that there isn't UI/Layout initialize thats why your findViewById() unable to find ids and throws NullPointerException.
public class MainActivity extends AppCompatActivity {
public void doLoginOnClick(View v){
String s1 = username . getText ().toString();
inputdata.setText(s1);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar =(Toolbar) findViewById (R.id.toolbar);
setSupportActionBar(toolbar);
EditText username =(EditText) findViewById (R.id.editText_Username);
EditText password =(EditText) findViewById (R.id.editText_Password);
TextView inputdata =(TextView) findViewById (R.id.textView_InputData);
TextView welcome =(TextView) findViewById (R.id.textView_Welcome);
Button login =(Button) findViewById (R.id.button_Login);
Button anotherLogin =(Button) findViewById (R.id.button_Login_Another);
FloatingActionButton fab =(FloatingActionButton) findViewById (R.id.fab);
fab.setOnClickListener(new View . OnClickListener ()
{
#Override
public void onClick(View view)
{
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}

Initialize all your views after onCreate() Method
Read More about activity lifecycle here

Think of it this way - until you tell the activity which user interface layout(xml) to use, it will not know where to get those views from.
You would do setContentView(R.layout.your_xml) to tell the activity which layout to use as the user interface for the activity. You would do this in the onCreate callback because this is the callback to do 'one-time activity level set up' tasks. setContentView() is one such task.
Once you do this, you can begin to access the views that are present within the layout file R.layout.your_xml.
onCreate(...)
{
...
setContentView(R.layout.your_xml)
// Ready to use the views from above xml.
findViewById(R.id.your_view)
...
}

View Binding will help you prevent from these issues:
https://developer.android.com/topic/libraries/view-binding
Or declare the views on top, and initialize them after setContentView() in onCreate().
public class MainActivity extends AppCompatActivity {
//Declare view on top
EditText username, password;
TextView inputdata,welcome;
Button login,notherLogin;
public void doLoginOnClick(View v)
{
String s1=username.getText().toString();
inputdata.setText(s1);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set view
username = findViewById(R.id.editText_Username);
password = findViewById(R.id.editText_Password);
inputdata = findViewById(R.id.textView_InputData);
welcome = findViewById(R.id.textView_Welcome);
login = findViewById(R.id.button_Login);
anotherLogin = findViewById(R.id.button_Login_Another);
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)
{
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
} }

setContentView() is responsible for inflating the layout of the activity. If any of the components are used before inflation of the layout, it will crash with a NullPointerException.
#Override
protected void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.activity_layout);
username = findViewById(R.id.editText_Username);
password = findViewById(R.id.editText_Password);
inputdata = findViewById(R.id.textView_InputData);
welcome = findViewById(R.id.textView_Welcome);
login = findViewById(R.id.button_Login);
anotherLogin = findViewById(R.id.button_Login_Another);
}
You can still declare the variable in the beginning of the class, but you have to initialize it in onCreate.

Related

setOnClickListener does not work in android studio

that is my code, very simple and basic
public Button btn1;
public TextView txt1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.txt1);
findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txt1.setText("finalyyyyyyyyyyy");
}
});
and the error showing is:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
The problem is here
findViewById(R.id.txt1);
findViewById(R.id.btn1);
you are getting the views from the .xml file but you are not actually assigning the value to any object... so when you try to call a method to the btn1 it's null (empty) and throws an error
So just assign the value you are getting to the views objects like so:
txt1 = findViewById(R.id.txt1);
btn1 = findViewById(R.id.btn1);
This will fix the problem
Save the element in variable and set onClick method to that particular variable as below:
btn1 = findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txt1.setText("finalyyyyyyyyyyy");
}
});

Unable to display textview on button click in android

I want to create this textview, and then display it after this button is clicked, but no textview is displayed.
I dont't want to use findViewById(), if possible, because I want to create a new textview every time the button is pressed. I've tried making a linear layout first, but I've seen a lot of websites say that you don't need to, and I would prefer not to. Any advice would be helpful. Thank you.
EditText name=layout.findViewById(R.id.enterName);
final String Name=name.getText().toString();
Button create=layout.findViewById(R.id.create);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView ProgrammaticallyTextView = new TextView(MainActivity.this);
ProgrammaticallyTextView.setText(Name);
ProgrammaticallyTextView.setTextSize(22);
popup.dismiss();
}
});
There are no error messages and the logcat doesn't say that anything is wrong.
Try like this :
private LinearLayout lLayout;
private EditText lEditText;
private Button lButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lLayout = (LinearLayout) findViewById(R.id.linearLayout);
lButton = (Button) findViewById(R.id.button);
lEditText = (EditText) findViewById(R.id.editText);
lButton.setOnClickListener(onClick());
TextView textView = new TextView(this);
textView.setText("Text New");
}
private OnClickListener onClick() {
return new OnClickListener() {
#Override
public void onClick(View v) {
lLayout.addView(createTextView(lEditText.getText().toString()));
}
};
}
private TextView createTextView(String text) {
final LayoutParams loutParams = new
LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(loutParams );
textView.setText("Text is " + text);
return textView;
}
Use the activity's findViewById() method to reference your layout views. For example, you can replace
EditText name=layout.findViewById(R.id.enterName);
Button create=layout.findViewById(R.id.create);
with
EditText name=getActivity().findViewById(R.id.enterName);
Button create=getActivity().layout.findViewById(R.id.create);
Note: if you are not using fragments then there is no need to use getActivity since findViewById() is a method of the superclass AppCompactActvity( or Activity).
I guess your code is not working because the Button View and Editext Views have not been reference when activity starts for the oncreate() method

if statement in Android Studio

I'm new to Android development, I am currently trying to see if a value entered is equal to a value. Here I am seeing if the user input equals to 5, they are currently set as strings as to is the text field.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uk_postage);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button home = (Button) findViewById (R.id.btnHome);
Button calculate = (Button) findViewById (R.id.btnCalculate);
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ukPostage.this, MainActivity.class));
}
});
EditText lengthInput = (EditText) findViewById(R.id.editTextLength);
final String lengths = lengthInput.getText().toString();
final TextView amount = (TextView) findViewById (R.id.txtAmount);
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
if (lengths.equals("5")) {
amount.setVisibility(View.VISIBLE);
}
}
});
The text goes to visible if i click the button without the if statement there however won't once I write the if statement.
Thanks in advance.
if (lengths.equals("5")) {
String is immutable and once you reference it you need to reference it again with your edit text to reflect the latest value.
Instead of the above code you need to reference the lengths back with the lengthInput value each time you click the calculate button.
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
lengths = lengthInput.getText().toString();
if (lengths.equals("5")) {
amount.setVisibility(View.VISIBLE);
}
}
});
IMPORTANT: You need to set the lengths as a global variable instead of being a final variable since it can only be initialized once.

How to make a button change a label [duplicate]

This question already has answers here:
Change button text and action - android development
(2 answers)
Closed 6 years ago.
I am new to java, and I am making a small little game that says "yes" or "no" when the user presses a button. I am not sure how to code to make the label change based on the user pushing the button. The code is below. Any other problems that you see with the code, I am interested in discovering those also.
public class FirstProject extends AppCompatActivity {
TextView answerTextView;
EditText name1Txt;
EditText name2Txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
answerTextView = (TextView) findViewById(R.id.answerLbl);
name1Txt = (EditText) findViewById(R.id.nameoneTxt);
name2Txt = (EditText) findViewById(R.id.name2Txt);
Button compBtn = (Button) findViewById(R.id.compBtn);
compBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
//where I want to make the button react
}
});
}
Every EditText has a method you have to call
EditText#setText(...);
Example:
name1Txt = (EditText) findViewById(R.id.nameoneTxt);
name2Txt = (EditText) findViewById(R.id.name2Txt);
Button compBtn = (Button) findViewById(R.id.compBtn);
compBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
//where I want to make the button react
name1Txt.setText("Hello...");
name2Txt.setText("...world");
}
});

Getting a NullExceptionPointer on my setOnClickListener()

I'm getting a NullException error on my Button setOnClickListener() method. I'm a bit flabbergasted as to why this is happening. Please bear in my mind that this is my first Android app, and I assume that there are bound to be some runtime errors (there are no compilation errors).
btnNaira.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dollarToNaira();
}
});
The dollarToNaira() method can be found here:
public void dollarToNaira() {
try {
dollarAmt = txtAmount.getText().toString();
nairaAmt = (Double.parseDouble(dollarAmt) * 199.00);
lblOutput.setText(dollarAmt + "U.S. Dollars = " + nairaAmt + " Nigerian Naira.");
}catch(Exception ex) {
message = "Please enter a valid numerical amount";
lblOutput.setText(message);
}finally {
txtAmount.requestFocus();
txtAmount.selectAll();
}
}
Please tell me what I am doing wrong I would like to know what causes the setOnClickListener method to return NULL. Thanks!
EDIT: this is the entire onCreate() method, I don't believe that I made an error:
protected void onCreate(Bundle savedInstanceState) {
txtAmount = (EditText) findViewById(R.id.txtAmount);
btnNaira = (Button) findViewById(R.id.btnNaira);
btnCFA = (Button) findViewById(R.id.btnCFA);
lblOutput = (TextView) findViewById(R.id.lblOutput);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//set up event listener on btnNaira and btnCFA
btnNaira.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dollarToNaira();
}
});
btnCFA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dollarToCFA();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
there is no problem in your code.
i guess you've made a mistake in initializing buttons and text views.
1- make sure that you define your listener inside a method, like onCreate(),
i think you had defined that in class body.
2- i guess that you had defined your button or text views,
but you did not initialized them , so they are null.
here is an example of initializing a Button
Button btnDoSomething = (Button)findViewById(R.id.idOfButton);
now you can setOnClickListener for it .
You should write in this way
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtAmount = (EditText) findViewById(R.id.txtAmount);
btnNaira = (Button) findViewById(R.id.btnNaira);
btnCFA = (Button) findViewById(R.id.btnCFA);
lblOutput = (TextView) findViewById(R.id.lblOutput);
Make sure you call setContentView(R.layout.activity_main); before initialize your button View.
Hope it helps.

Categories