1 year ago

#74231

test-img

BadProgrammer

How to properly reference a class which extends from View in MainActivity?

I'm learning by doing and reading from the Android docs but I have stumbled upon this problem while building a drawing app.

public class MainActivity extends AppCompatActivity {

    private Button colourButton;
    private Spinner spinner;

    private DrawTool drawTool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.spinner = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this,
                R.array.spinner_options,
                android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);


        this.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int
                    i, long l) {

                String selected = adapterView.getSelectedItem().toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


    }
}

The MainActivity controls a Spinner with color options ("RED", "BLUE", etc) and sets the paint to the selected color using the DrawTool method setColor(String color) from this class.

public class DrawTool extends View {

    public static DrawTool drawToolInstance;

    private float xPos, yPos = 0;

    private Path path;
    private Paint paint;
    private List<Path> pathsList;
    private List<Paint> paintList;


    public DrawTool(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.pathsList = new ArrayList<>();
        this.paintList = new ArrayList<>();
        this.drawToolInstance = this;
    }

    public static DrawTool getInstance() {
        return drawToolInstance;
    }

    public void setPaint(String paint) {

        switch(paint.toUpperCase()) {
            case "RED":
                this.paint.setColor(Color.RED);
                break;
            case "BLUE":
                this.paint.setColor(Color.BLUE);
                break;
            case "YELLOW":
                this.paint.setColor(Color.YELLOW);
                break;
            case "BLACK":
                this.paint.setColor(Color.BLACK);
                break;
            case "WHITE":
                this.paint.setColor(Color.WHITE);
                break;
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int i = 0;
        for (Path path : pathsList) {
            canvas.drawPath(path, paintList.get(i++));
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        xPos = event.getX();
        yPos = event.getY();


        switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //System.out.println("Action Down");
                paint = new Paint();
                paint.setStrokeWidth(20);
                paint.setARGB(255, 255, 0, 0);
                //setPaint(s.getSelectedItem().toString());
                paint.setStyle(Paint.Style.STROKE);
                paintList.add(paint);

                //Trazado
                path = new Path();
                path.moveTo(xPos, yPos);
                pathsList.add(path);

                System.out.println();
                break;
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                //System.out.println("Action up");

                int puntosHistoricos = event.getHistorySize();
                for(int i = 0; i < puntosHistoricos; i++) {
                    path.lineTo(event.getHistoricalX(i), event.getHistoricalY(i));
                }

        }
        invalidate(); //Actualizar pantalla
        return true;
    }

    @Override
    public String toString() {
        return "DrawTool{" +
                "xPos=" + xPos +
                ", yPos=" + yPos +
                ", path=" + path +
                ", paint=" + paint +
                ", pathsList=" + pathsList +
                ", paintList=" + paintList +
                '}';
    }
}

DrawTool extends from view and controls a canvas from MainActivity.

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.example.draw.DrawTool
        android:id="@+id/lienzo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="50dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="110dp"
        android:layout_height="50dp"
        android:layout_marginStart="1dp"
        android:layout_marginEnd="298dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/lienzo"
        app:layout_constraintVertical_bias="0.0" />

</androidx.constraintlayout.widget.ConstraintLayout>

I have tried accessing DrawTool.setPaint by:

  • Returning an instance from DrawTool getInstance()
  • Find the view with findViewById(id) and cast it to DrawTool
  • Access the spinner from DrawTool to get the option

but every time I just got NullReference.

android

oop

nullpointerexception

0 Answers

Your Answer

Accepted video resources