Search code examples
androidnullpointerexceptionandroid-alertdialogtogglebutton

using layout(toggleButton) inside alert dialog, always returns nullPointerExpection


in my MainActivity i have a method showPopUp that is called by a button's listener. So MainActivity's layout only contain a button.

ShowPopUp method reads button states and returns null pointer expception. activity_toggle is my layout that contains toggleButton. following is my mainactivity code snippet.

public class MainActivity extends ActionBarActivity {
  ToggleButton toggleButton;
  String i;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    showAlertDialog(MainActivity.this);
}

public void showAlertDialog(final Context context){
AlertDialog.Builder ab = new AlertDialog.Builder(context);
View v = LayoutInflater.from(context).inflate(R.layout.activity_toggle,null);
ab.setView(v);
ab.setTitle("toggle mera dil toggle meri jaan");
   toggleButton = (ToggleButton)findViewById(R.id.toggleButton1);


toggleButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if(toggleButton.isChecked()){
                i+=i;
                Toast.makeText(MainActivity.this,"Button is on "+i,Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(MainActivity.this,"Button is off  mode",Toast.LENGTH_SHORT).show();
            }
    }
});
ab.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
    Toast.makeText(MainActivity.this,"ok button pressed",Toast.LENGTH_SHORT).show();
    boolean tButton = toggleButton.isChecked();
    if(tButton){
        Toast.makeText(MainActivity.this,"Button is off on a ",Toast.LENGTH_SHORT).show();
    }

    dialog.dismiss();
}
});
ab.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
    }
});
ab.create().show();
}
}

Solution

  • Try below code. You have to give reference of View when you find view from inflater view.

    toggleButton = (ToggleButton)v.findViewById(R.id.toggleButton1);

    View v = LayoutInflater.from(context).inflate(R.layout.activity_toggle,null);
    ab.setView(v);
    ab.setTitle("toggle mera dil toggle meri jaan");
    toggleButton = (ToggleButton)v.findViewById(R.id.toggleButton1);