Search code examples
androidcolor-picker

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


Solution

  • 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