-1

I am trying to use a button made in XML in a alert dialog but the app crashes when the activity tries to load.

package dtt.bob.rsrpechhulp;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

public class CallWindow extends DialogFragment implements View.OnClickListener{
LayoutInflater inflater;
View v;

@Override
@NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Button annuleren = (Button) v.findViewById(R.id.annuleren); //here is the problem I assume
    annuleren.setOnClickListener(this);

    inflater = getActivity().getLayoutInflater();
    v = inflater.inflate(R.layout.call, null);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(v);
    return builder.create();
}

public void onClick(View v) {
    switch(v.getId()){
        case R.id.annuleren:
            annulerenClick();
            break;
    }
}

//annuleren
private void annulerenClick(){
    dismiss();
}

Any ideas on how to fix this? I have used the onClickListeners in other activities but they were in onCreate methods instead of onCreateDialog methods.

B. Bob
  • 225
  • 1
  • 2
  • 6

2 Answers2

1

You are trying to call findViewById(...) on the object v(View) even before it is inflated.
I'm assuming your getting a NullPointerException which is causing the crash.
Have a look at this link - http://www.mkyong.com/android/android-custom-dialog-example/ for further info.

niranjan_b
  • 132
  • 5
0

You tried to find the button id before instantiating the View v.....

First instantiate your inflater and the View object, then your button.

    public Dialog onCreateDialog(Bundle savedInstanceState) {
        inflater = getActivity().getLayoutInflater();
        v = inflater.inflate(R.layout.call, null);
        Button annuleren = (Button) v.findViewById(R.id.annuleren); //here is the problem I assume
        annuleren.setOnClickListener(this);


        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(v);
        return builder.create();
    }
hashcode55
  • 5,622
  • 4
  • 27
  • 40