Onclick listener throwing NullPointerException - java

I've setup a button and I'm trying to display a toast when the user clicks on it. Here's my Java code -
file = (Button) findViewById(R.id.file);
file.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Display the file chooser dialog
//showChooser();
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)", Toast.LENGTH_LONG).show();
}
});
Here's my XML code to setup the button -
<Button
android:id="#+id/file"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/plt"
android:text="File" />
This throws a NullPointerException on the line file.setOnClickListener(new OnClickListener() { . What am I doing wrong?

Are you initializing the Button inside the onCreate() method of your Activity?
If so, please check if you are calling
setContentView(R.id.yourlayoutfile);
before initializing the Button with findViewById(R.id.file);
Your error occurs because your Button "file" is null, which means that findViewById(...) didn't find any View with that id. The reason therefore can either be that there is no such ID in the inflated layout, or that you didn't call setContentView(...)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourlayoutfile);
// initialize your button here
}

try to clean project
project-->clean-->choose your project-->ok,
then run again.
if you still facing the same problem you can use another way to set click action
in your XML
<Button
android:id="#+id/file"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/plt"
<!--added line-->
android:onClick="anyName"
android:text="File" />
and then in you activity remove the initialization of the button and click listner too
and make the code looks like that
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.id.yourlayoutfile);
}
public void anyName(View v){
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
Toast.LENGTH_LONG).show();
}
Hope this help.

If there is a Null pointer exception on this line:
file.setOnClickListener(new OnClickListener()
then it mean your file object is null
Make sure you initialize your file object before adding a listener to it.

Related

OnClick() isn't working

I'm having trouble taking in text from a few text boxes with one button. I can't seem to get OnClick() to work. I have setContentView(R.layout.activity_load_xactivity); as a test I know it doesn't have anything to do with input.
Button button = (Button)findViewById(R.id.create);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
setContentView(R.layout.activity_load_xactivity);
}
});
Is in my protected void onCreate(Bundle savedInstanceState). Doesn't work. No errors, just doesn't do anything.
Button button = (Button)findViewById(R.id.create);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
setContentView(R.layout.activity_home2);
}
});
On It's own Doesn't resolve setOnClickListener. I have import android.view.View.OnClickListener set. I've tried entering different code where it says setContentView(R.layout.activity_home2);
Try adding an ID to the Layout holding the Views, Buttons (RelativeLayout, ContrasintLayout ect...) in XML. Then in java make a new Layout, and use layout.addContentView(XML) in your button:
Layout a = findViewById(R.id.layout_name);//Use whatever layout TYPE is used in XML
Button button = (Button)findViewById(R.id.create);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
a.addContentView(R.layout.activity_load_xactivity);
}
});
Also, In you XML, you should give an ID to your layout then define it in java.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_name">
<!--You can use any Layout Type -->
...
</RelativeLayout>
EDIT:
I know this has nothing to with your question, but if you want to switch activity's use this instead:
Intent b = new Intent(this, JavaActivtyName.class);
startActivity(b);

How do I create a custom toast message that displays random messages

xml for the button:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button001"
android:text="#string/text_7"
android:textStyle="bold"
android:layout_gravity="center"/>
I want to display messages ("Hello", "Bonjour", "Good day", "Lets Go") as toasts randomly.
The java code for the toast function:
Button button001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
button001 = (Button) findViewById(R.id.kabutton);
button001.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] {"Hello","Bonjour!","Good day","Lets Go"};
Toast.makeText(getApplicationContext(),[String],Toast.LENGTH_LONG);
}
});
}
}
You can create your string array and then get a random index every time you click the button.
#Override
public void onClick(View v) {
String[] randomStrings = new String[] {"Hello","Bonjour!","Good day","Lets Go"};
Toast.makeText(getApplicationContext(),randomStrings[new Random().nextInt(randomStrings.length - 1)],Toast.LENGTH_LONG).show();
}
You can create custom view for the Toast message using setView() method. Check this.
For the random, you Java's Random class nextInt() method and have those strings as list and using the int that random gave you to access one at a time.

How do I determine which image the user selected in a button click event handler? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I don't know what to compare in my if statements for my order.setOnClickerListener to get my code working properly. I'm trying to setText based on which image is selected from the array when the button is pressed.
Right now, when the button is pressed, I am trying to look at each image in turn to decide whether or not the user selected it. However, I'm not sure how I can tell whether the user selected a particular image or not. What should I replace the **** with to determine that?
public class Breakfast extends AppCompatActivity {
Integer[]Foods = {R.drawable.pancakes, R.drawable.frenchtoast, R.drawable.waffles,
R.drawable.omelet};
ImageView pic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
setContentView(R.layout.activity_breakfast); GridView grid = (GridView) findViewById(R.id.gridView);
final ImageView pic = (ImageView) findViewById(R.id.imgLarge);
final TextView food = (TextView) findViewById(R.id.txtFood);
Button back = (Button) findViewById(R.id.btnBack);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Breakfast.this, MainActivity.class));
}
});
final Button order = (Button) findViewById(R.id.btnOrder);
order.setEnabled(false);
order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Foods[0] == ****){
Toast.makeText(getBaseContext(), "Pancakes added to your order", Toast.LENGTH_SHORT).show();
food.setText("You've selected Pankcakes");}
if(Foods[1] == ****){
Toast.makeText(getBaseContext(), "French Toast added to your order", Toast.LENGTH_SHORT).show();
food.setText("You've selected French Toast");}
if(Foods[2] == ****){
Toast.makeText(getBaseContext(), "Waffles added to your order", Toast.LENGTH_SHORT).show();
food.setText("You've selected Waffles");}
if(Foods[3] == ****){
Toast.makeText(getBaseContext(), "Omelet added to your order", Toast.LENGTH_SHORT).show();
food.setText("You've selected Omelet");}
}
});
grid.setAdapter(new ImageAdapter(this));
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pic.setImageResource(Foods[position]);
order.setEnabled(true);
}
});
}
}
There's a little more code but I don't think it's relevant.
Use multiple (4 in your case), ImageView in your layout XML:
<ImageView
android:id="#+id/pancakes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/pancakes"/>
<ImageView
android:id="#+id/frenchtoast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/frenchtoast"/>
<ImageView
android:id="#+id/waffles"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/waffles"/>
<ImageView
android:id="#+id/omelet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/omelet"/>
Then, add a listener to all of them in your activity and keep track of the image clicked by updating the imageSelected variable:
public class Breakfast extends AppCompatActivity implements View.OnClickListener {
private int imageSelected;
ImageView pancakes;
ImageView frenchtoast;
ImageView waffles;
ImageView omelet;
#Override
protected void onCreate(Bundle savedInstanceState) {
// ... your code
pancakes.setOnClickListener(this);
frenchtoast.setOnClickListener(this);
waffles.setOnClickListener(this);
omelet.setOnClickListener(this);
// ... more code
}
#Override
public void onClick(View v) {
imageSelected = v.getId();
}
}
And this is the OnClickListener of your order Button:
order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (imageSelected == pancakes.getId()) {
Toast.makeText(getBaseContext(), "Pancakes added to your order", Toast.LENGTH_SHORT).show();
food.setText("You've selected Pankcakes");
}
if (imageSelected == frenchtoast.getId()) {
Toast.makeText(getBaseContext(), "French Toast added to your order", Toast.LENGTH_SHORT).show();
food.setText("You've selected French Toast");
}
if (imageSelected == waffles.getId()) {
Toast.makeText(getBaseContext(), "Waffles added to your order", Toast.LENGTH_SHORT).show();
food.setText("You've selected Waffles");
}
if (imageSelected == omelet.getID()) {
Toast.makeText(getBaseContext(), "Omelet added to your order", Toast.LENGTH_SHORT).show();
food.setText("You've selected Omelet");
}
}
});
I don't think that you want to do this the way you're trying to do it (i.e. you don't want to just replace the **** in your code sample with some condition and call it a day).
You have a few options here (and there are lots of code samples available online). One is to use either a HorizontalScrollView or a ListView. This has the advantage of making it easier to change what images you're displaying later (as opposed to hardcoding it, which would require a code update and redeploy every time you changed what image was being displayed).
There's also a Gallery class, but it's deprecated.
If you definitely want to hardcode the values and are OK with the potential maintenance and deployment problems that this could cause later, you can try to use an ImageButton for each. From the documentation, an ImageButton
Displays a button with an image (instead of text) that can be pressed or clicked by the user. By default, an ImageButton looks like a regular Button, with the standard button background that changes color during different button states. The image on the surface of the button is defined either by the android:src attribute in the XML element or by the setImageResource(int) method.
#lalongooo shows a code sample for how to do something similar to this in his answer.
There's also a tutorial here on creating a ListView with check boxes. I haven't gone through the tutorial that carefully yet, but the image of what they're trying to implement looks pretty nice ad it may suit your purposes. You may want to try implementing that or something similar. (I searched the phrase "check box list view android" in Bing to find that if you're curious or want to find more tutorials/examples on the same topic).

getting data from EditText

I am trying to make a simple android application which contains a EditText and a Button . User will enter his data and this application will show him the data as a Toast.
Now The problem I am facing is , whenever button is pressed by user it's just showing a blank toast.Here is my code
EditText et;
String data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bsave=(Button) findViewById(R.id.bsave);
et=(EditText) findViewById(R.id.editText1);
data=et.getText().toString();
bsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.v("EditText",et.getText().toString());
Intent in=new Intent(MainActivity.this,SecondAct.class);
in.putExtra("DATA", data);
Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show();
}
});
}
please help me . Thanks in Advance!!!!
You are calling gettext() in oncreate(),when there is no text at all in editbox.. So your log inside onClick() will show data but toast will never show any thing with this code as variable data is ""..
You should do like
bsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
data=et.getText().toString();
Toast.makeText(MainActivity.this,data, Toast.LENGTH_SHORT).show();
}
});
in button onClick(...)
As shown above you need to save the data in the EditText inside of the Button's on click listener. As your code is now as soon as the edit text is created the text is being saved into the data variable, but you want it to set as soon as the button is clicked.

When the button is pressed, the app crashes

I've been having problems with Android buttons. I try to set an onClick listener, but it fails, crashes and doesn't print any helpeul error messages. Here is my code:
Button button;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.choose_level);
}
});
I've tried putting in a try catch statement so it won't display annoying errors but the button still doesn't work. Would it be because the layout hasn't been loaded? or is it something else?
Thanks in advance.
you must call setContentView(R.layout.XML_LAYOUT); method before you callfindViewById for your button.
here XML_LAYOUT must be the Layout containing your Button ID.
Note:- it is not recommanded to call setContentView method multiple times. if you want to show a different layout/screen add it into Another activity and start that activity on button click.
you are calling setContentView(R.Layout.XML_LAYOUT) in your button onClick listener where as it should be above in oncreate method
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/
Button play = (Button)findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
show ur text here
}
});
I guess what u r trying to do is to set view for an XML file
which is some layout file i guess check out inflator and intent
I put that in a try, catch statement so it won't put annoying errors...
A catch block will not magically stop your error from occurring - you cannot use it to stop the application "putting annoying errors".
You use them to handle errors when it's possible to recover from those cases (e.g. wait and retry, fall back to a slower alternative, etc.)
What is the implementation of your catch block? If you're simply swallowing the error, your app will still fail - only you won't have any diagnostic information with which to deal with it.
You'll need to go back to your original "annoying error", work out why it was happening and then fix it rather than just suppressing its output.

Categories

Resources