1

I'm new to android app development.While developing my first app I found null point exception at button1.setonClickListener().What value can I initialise to variable type Button to avoid null point exception. package com.example.first;

 public class MainActivity extends ActionBarActivity { 
 private Button
> btn1;
> 
> private ImageView imagetoshow;
>     @Override
>     protected void onCreate(Bundle savedInstanceState) {
>         super.onCreate(savedInstanceState);
>         setContentView(R.layout.activity_main);
>         
>         btn1=(Button)findViewById(R.id.button1);
>          
>           imagetoshow=(ImageView)findViewById(R.id.imageView1);
>        
>         if(btn1!=null){       btn1.setOnClickListener(new View.OnClickListener() {
>               @Override
>               public void onClick(View v) {
>               
>             imagetoshow.setImageResource(R.drawable.image1);
>                   
>               }
>             }); }
>      
>         if (savedInstanceState == null) {
>             getSupportFragmentManager().beginTransaction()
>                     .add(R.id.container, new PlaceholderFragment())
>                     .commit();
>         }
>     }
> 
> 
>       @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);
>     }
> 
>     /**
>      * A placeholder fragment containing a simple view.
>      */
>     public static class PlaceholderFragment extends Fragment {
> 
>         public PlaceholderFragment() {
>         }
> 
>         @Override
>         public View onCreateView(LayoutInflater inflater, ViewGroup container,
>                 Bundle savedInstanceState) {
>             View rootView = inflater.inflate(R.layout.fragment_main, container, false);
>             return rootView;
>         }
>     }
> 
>    }
Bhavesh Jethani
  • 3,891
  • 4
  • 24
  • 42
vamshi
  • 47
  • 8

3 Answers3

0

You should to check if button1 is not null before trying to invoke method on that object like :

if(button1 != null) {
    button1.setonClickListener()
}

But I wonder why button is null ? something must be wrong with your code ...

Kasper Ziemianek
  • 1,329
  • 8
  • 15
  • Most of the time you can be pretty sure the Button is not null. If it is null, it will always be null. So if you need a check it will always fail and the button will never be clickable. – TmKVU Jun 21 '14 at 11:56
  • Most of time doesn't mean always, that's why we have checks, or we are sure what's happening in our code. – Kasper Ziemianek Jun 21 '14 at 11:57
  • @vamshi please see my answer, you need to initialize it. – TmKVU Jun 21 '14 at 12:06
  • @xwid I do mean all of the time. If you initialize an Object it will not be null, unless you are doing something wrong. Rather than catching you should fix the error. There are usecases where an Object is only sometimes null, but not this one. – TmKVU Jun 21 '14 at 12:07
0

Well, you need to initialize it either by getting it from your xml with:

button1 = (Button) findViewById(R.id.myButton);

Or initialize it manually by creating a new Object(But you would then also need to add it as a child to a ViewGroup)

button1 = new Button(this);
parentLayout.addView(button1);

I strongly recommend the first option for most use cases where content is not generated dynamically.

--EDIT--

Judging from your code I can only conclude the button with id 'button1' is not in the activity_main.xml file. You can only use Views defined in the layout file you have set as content view. You should define the buttons in activity_main.xml of change the content view to the correct layout file.

--EDIT--

It seems you want to use the Button in a Fragment. You should then, inside your Fragment (which is called PlaceholderFragment in your code), initialize the Button:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_main,
                container, false);
                button1 = (Button) v.findViewById(R.id.button1);
        return v;
}
TmKVU
  • 2,910
  • 2
  • 16
  • 30
  • But my relative layout is in fragment_main.xml and frame layout is in activity_main.XML and I have defined button in fragment_main.xml – vamshi Jun 21 '14 at 12:27
  • There is your problem. That is not possible. If you use findViewById() to find a View you need to add the button to the View defined in setContentView. But it sounds you want to use the Button in the Fragment. You should then set the OnCLickListener in the Fragment class – TmKVU Jun 21 '14 at 12:32
  • Where do I find fragment class? – vamshi Jun 21 '14 at 12:41
  • Where can I find fragment class? – vamshi Jun 21 '14 at 12:43
  • probably in on of your packages in src. Judging from your posted code it is called PlaceHolderFragment – TmKVU Jun 21 '14 at 12:44
  • May I know why my relative layout is in fragment_main.xml? How can bring it activity_main.xml? – vamshi Jun 21 '14 at 12:59
  • It is there because you put it there. If you want a `RelativeLayout`in main.xml, just put one there – TmKVU Jun 21 '14 at 13:04
  • Then what about iinear layout already present in activity_main.xml – vamshi Jun 21 '14 at 13:15
  • @vamshi because you put it there.. your question was about the Button. the Button won't be null in the Fragment. If you do not understand basic layout in Android read the [documentation](http://developer.android.com/guide/topics/ui/declaring-layout.html) – TmKVU Jun 21 '14 at 13:23
0

As per my guess. as you don't have post your xml files.

i can just give you suggestion that.

       public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) 
      {
                View v = inflater.inflate(R.layout.fragment_main,
                        container, false);
                            button1 = (Button) v.findViewById(R.id.button1);


button1.setOnClickListner(new View.OnClickListener() 
    {
                   @Override
                   public void onClick(View v)
                  {

                    imagetoshow.setImageResource(R.drawable.image1);

                   }
                 });
    }

            return v;
    }

Second Suggestion

If you don't want to use fragment concept than extend with Activity. and remove all extra code and change in xml files, add button on your activity_main.xml.

Bhavesh Jethani
  • 3,891
  • 4
  • 24
  • 42
  • Please say me how I can I have relative layout in activity_main.xml by default? As I'm unaware of fragments concept.Please help me as I'm stuck up – vamshi Jun 21 '14 at 16:05
  • try to create new .xml in layout you will get the layout options select Relative layout . – Bhavesh Jethani Jun 23 '14 at 04:44
  • Whenever create new project you will find fragment concept in new adt-eclipse.. But it is not require in your project just remove it.. all unwanted methods, extend with Activity , remove framents and made changes in activity_main.xml. – Bhavesh Jethani Jun 23 '14 at 04:47