Muaz Usmani
Muaz Usmani

Reputation: 1318

ColorPicker in android NullPointerException

I am using this file, to choose color, its a nice dialog, I am using the following code

public class Main extends Activity implements
        ColorPickerDialog.OnColorChangedListener {

    Button b;
    Context c = this;
    ColorPickerDialog.OnColorChangedListener cc;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                new ColorPickerDialog(c, cc, "tag", 16777215, 0).show();

            }
        });
    }

    @Override
    public void colorChanged(String key, int color) {
        Log.d("debug", "key is " + key + " color is " + color);

    }
}

in my main.xml there is just one button. this code is working fine when I click on a button and dialog box appear, but when I select a color a NullPointerException is coming, I dont know why, any help will be thankful. Regards

Upvotes: 0

Views: 270

Answers (2)

Muaz Usmani
Muaz Usmani

Reputation: 1318

I changed my code to this that worked, I need to make onColorChangedListener inside the onCreate like this

public class Main extends Activity  {
Button b;
OnColorChangedListener cc;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    cc=new OnColorChangedListener() {

        @Override
        public void colorChanged(String key, int color) {
            Log.d("tag", "key is " + key + " color is " + color);

        }
    };
    b = (Button) findViewById(R.id.button1);
    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            new ColorPickerDialog(Main.this, cc, "tag", 16777215, 0).show();

        }
    });
}
}

reference

Upvotes: 0

user370305
user370305

Reputation: 109237

In your case,

Context c = this;
ColorPickerDialog.OnColorChangedListener cc;

both are null,

new ColorPickerDialog(c, cc, "tag", 16777215, 0).show();

so, this line cause NPE..

Upvotes: 1

Related Questions