I am new to android programming and I am trying to create a green circle image out of the screen. I tried using canvas to draw but it always show an error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Paint.setColor(int)' on a null object reference
at com.example.jordanong09.handeyegame.GameActivity.onDraw(GameActivity.java:61)
at com.example.jordanong09.handeyegame.GameActivity.onCreate(GameActivity.java:47)
Below are my codes for my programme:
public class GameActivity extends Activity {
TextView textViewTime, textViewScore;
int timeLeft,score;
float xcoord,ycoord,radius = 100;
Paint paint;
Canvas canvas1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
String timeData = getIntent().getExtras().getString("timeDuration");
if(timeData == "30sec"){
timeLeft = 30;
}
textViewTime = (TextView)findViewById(R.id.textViewTime);
textViewScore = (TextView)findViewById(R.id.textViewScore);
textViewTime.setText(timeData);
final CounterClass timer = new CounterClass (30000, 1000);
timer.start();
onDraw(canvas1);
}
protected void onDraw (Canvas canvas)
{
Display display = getWindowManager().getDefaultDisplay();
Point screenSize = new Point();
display.getSize(screenSize);
int width = screenSize.x;
int height = screenSize.y;
Random random = new Random();
xcoord = random.nextFloat() * width;
ycoord = random.nextFloat() * height;
paint.setColor(Color.GREEN);
paint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(xcoord, ycoord, radius, paint);
}
I really dunno what is wrong with it because I have been researching online for solutions. Hope I could hear some advice. Thanks
The Paint object is not initialised correctly. You should call
paint = new Paint();
before calling
paint.setColor();
Otherwise paint is null, and you can't call methods on null.
You should go by creating a custom view and adding it as a child to one of your view group. Here is an example code. Hope this will help.
/**
* Created by sanjeet on 2/2/16.
*/
public class GameActivity extends AppCompatActivity {
TextView textViewTime, textViewScore;
int timeLeft, score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
textViewTime = (TextView)findViewById(R.id.textViewTime);
textViewScore = (TextView)findViewById(R.id.textViewScore);
/*Create a ViewGroup in your layout to contain this custom GameView instance */
LinearLayout gameViewContainer = (LinearLayout)findViewById(R.id.custom_view_container);
gameViewContainer.addView(new GameView(this));
}
class GameView extends View {
Paint paint;
int width;
int height;
private float radius=100;
Random random;
public GameView(Context context) {
super(context);
paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStyle(Paint.Style.STROKE);
Display display = getWindowManager().getDefaultDisplay();
Point screenSize = new Point();
display.getSize(screenSize);
width = screenSize.x;
height = screenSize.y;
random = new Random();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float xcoord = random.nextFloat() * width;
float ycoord = random.nextFloat() * height;
canvas.drawCircle(xcoord, ycoord, radius, paint);
}
}
}
Related
I have to make a gradient color effect in the view that generated dynamically according to the scenario and also the view would be of any shape (diagonal or square)
As shown in image, gradient effect could be in any shape.
Also, if I create custom view for every possible case and play with Visibility, then how I will manage these views to fit perfectly on every device screen size?
Just need a small help to start.
Thanks in advance.
I have solved the issue using this approach.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new CustomView(this));
}
}
and now create a CustomView class
public class CustomView extends View {
Rect rect;
private Rect rectangle;
private Paint paint;
public CustomView(Context context) {
super(context);
int x = 50;
int y = 50;
int sideLength = 200;
int sideLength1 = 100;
rectangle = new Rect(x, y, sideLength, sideLength1);
paint = new Paint();
paint.setColor(Color.GRAY);
}
#Override
protected void onDraw(Canvas canvas) {
int width = this.getMeasuredWidth();
int height = this.getMeasuredHeight();
BitmapShader shader;
//shader = new BitmapShader(header, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
//paint.setShader(shader);
Path path = new Path();
path.moveTo(40,40);
path.lineTo(5,height/2);
path.lineTo(width/2,height/4);
path.lineTo(width/2,0);
canvas.drawPath(path,paint);
}
I have a project in which I am trying to draw rectangles to fill the screen
MainActivity.java
public class MainActivity extends Activity {
private int vScreenHeight, vScreenWidth;
private int vLeftPos = 0;
private int vTopPos = 0;
private int vRightPos = 154;
private int vBottomPos = 154;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
vGetScreenHeightAndWidth();
while(vTopPos < vScreenHeight) {
while(vLeftPos < vScreenWidth) {
RectView rectView = new RectView(getApplicationContext(), vLeftPos, vTopPos, vRightPos, vBottomPos);
vLeftPos += 154;
vRightPos += 154;
setContentView(rectView);
}
vLeftPos = 0;
vTopPos += 154;
vRightPos = 154;
vBottomPos += 154;
}
}
private void vGetScreenHeightAndWidth() {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size); // this will work only in API level 13 above.
vScreenWidth = size.x;
vScreenHeight = size.y;
}
}
RectView.java
public class RectView extends View implements OnClickListener
{
private int vLeftPos;
private int vTopPos;
private int vRightPos;
private int vBottomPos;
Rect r;
private Paint paint = new Paint();
private final String TAG = "Canvas Application";
public RectView(Context pAppContext, int pLeftPos, int pTopPos, int pRightPos, int pBottomPos)
{
super(pAppContext);
vLeftPos = pLeftPos;
vTopPos = pTopPos;
vRightPos = pRightPos;
vBottomPos = pBottomPos;
r = new Rect();
this.setOnClickListener(this);
}
public void onDraw(Canvas pCanvasObj)
{
r.set(vLeftPos, vTopPos, vRightPos, vBottomPos);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
pCanvasObj.drawRect(r, paint);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.BLACK);
pCanvasObj.drawRect(r, paint);
}
#Override
public void onClick(View v)
{
Toast.makeText(null, "tapped", Toast.LENGTH_SHORT).show();
}
}
In this Activity, I am calculating the positions of the rectangles and creating a RectView object to draw the rectangles.
I am not able to understand what am I doing wrong ?
The problem is in RectView. You can try this:
public class RectView extends View {
private RectF rect;
private Paint paint;
/**
* #param context
*/
public RectView(Context context) {
super(context);
paint=new Paint();
paint.setColor(Color.RED);
rect=new RectF();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
rect.set(0, 0, MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(rect, paint);
}
Hey I am trying to make a new icon every 800 milliseconds, and position their x values randomly, and their y below the android screen. I want to get these icon to move across the screen vertically, but instead getting to work I keep getting multiple icons stacked on top of each other. Any Help is appreciated.
public class GameView extends SurfaceView{
Bitmap icon;
LinkedList<Sprite> balloonList;
Timer spawnTimer;
TimerTask spawnTask;
Random rand;
SurfaceHolder holder;
int spawnTime;
final int SPAWN_DIFFERENCE = 10;
public GameView(Context context){
super(context);
icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
holder = getHolder();
balloonList = new LinkedList<Sprite>();
rand = new Random();
spawnTime = 1;
spawnTimer = new Timer();
spawnTask = new TimerTask() {
#Override
public void run() {
spawnNewBalloon();
}
};
spawnTimer.scheduleAtFixedRate(spawnTask, 800, 800);
}
private void spawnNewBalloon(){
Canvas canvas = holder.lockCanvas();
if(spawnTime == 0){
balloonList.insertTail(new Sprite(icon, rand.nextInt(getWidth() - icon.getWidth() / 2), getHeight()));
balloonList.getTailData().draw(canvas);
spawnTime = SPAWN_DIFFERENCE;
}
else spawnTime--;
if(balloonList.length() == 0){
for(int i = 0; i < balloonList.length(); i++) {
balloonList.getData(i).update(canvas);
}
}
holder.unlockCanvasAndPost(canvas);
}
}
class Sprite{
public Bitmap image;
public int x, y;
public Sprite(Bitmap image, int x, int y){
this.image = image;
this.x = x;
this.y = y;
}
public void draw(Canvas canvas){
canvas.drawBitmap(image, x, y, null);
}
public void update(Canvas canvas){
if(y > 0) y -= 15;
draw(canvas);
}
}
I want to make a note editor. It will have an EditText with lines. Here is my code:
LinedEditText.java
public class LinedEditText extends EditText {
private Rect mRect;
private Paint mPaint;
public LinedEditText(Context context) {
super(context);
// TODO Auto-generated constructor stub
mRect = new Rect();
mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setColor(Color.BLUE); //SET YOUR OWN COLOR HERE
}
#Override
protected void onDraw(Canvas canvas) {
//int count = getLineCount();
int height = getHeight();
int line_height = getLineHeight();
int count = height / line_height;
if (getLineCount() > count)
count = getLineCount();
Rect r = mRect;
Paint paint = mPaint;
int baseline = getLineBounds(0, r);//first line
for (int i = 0; i < count; i++) {
canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
baseline += getLineHeight();//next line
}
super.onDraw(canvas);
}
TextEditorActivity.java
public class TextEditorActivity extends Activity {
private LinedEditText text;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.text=new LinedEditText(getApplicationContext());
this.setContentView(text);
}
}
And result:
result http://bekirmavus.com/k-resimler/image/android/device-2012-07-17-222950.png
What mistake am i making?
Thanks...
The line are being drawn from the position of the cursor on down. Simply move the cursor's default position from vertically centered, to the top-left, with Gravity:
text.setGravity(Gravity.NO_GRAVITY);
Or set it by default for all LinedEditTexts:
public LinedEditTexts(Context context) {
super(context);
setGravity(Gravity.NO_GRAVITY); // or Gravity.TOP | Gravity.LEFT
...
}
I am trying to apply a scale animation to a rectangle, using code not xml. I want to make the rectangle grow taller, pretty simple.
RectDrawableView - creates a RectShape ShapeDrawable
public class RectDrawableView extends View {
Paint paint;
public RectDrawableView(Context context) {
super(context);
paint = new Paint();
paint.setColor(Color.parseColor("#aacfcce4"));
paint.setStyle(Paint.Style.FILL);
}
protected void onDraw(Canvas canvas) {
int x = 35;
int y = 250;
int width = 50;
int height = 300;
ShapeDrawable shapeDrawable = new ShapeDrawable(new RectShape());
Rect rect = new Rect(x, y, x+width, y+height);
shapeDrawable.setBounds(rect);
shapeDrawable.getPaint().set(paint);
shapeDrawable.draw(canvas);
}
}
Activity: - Creates a new RectDrawableView and adds to layout. OnResume an animation is triggered, which should make the rectangle grow taller.
public class RectActivity extends Activity {
final String TAG = "RectActivity";
TextView rect1;
RectDrawableView rectView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic);
LinearLayout linear = (LinearLayout) findViewById(R.id.basicLayout);
rectView = new RectDrawableView(this);
linear.addView(rectView);
}
#Override
public void onResume() {
super.onResume();
RunAnimations();
}
private void RunAnimations() {
Animation rectAnim1 = new ScaleAnimation(1, 1, 1, 1.3f, ScaleAnimation.RELATIVE_TO_SELF, 0,
ScaleAnimation.RELATIVE_TO_SELF, 1);
rectAnim1.setFillBefore(false);
rectAnim1.setFillAfter(true);
rectAnim1.setStartOffset(500);
rectAnim1.setDuration(500);
rectView.startAnimation(rectAnim1);
}
}
basic.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/basicLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
</LinearLayout>
Result: The rect is growing taller, good, but the location of the rect is also changing, bad. The whole rectangle is being positioned higher up the screen.
When I use this exact same animation code, but apply it to a TextView instead of a ShapeDrawable, all is good.
I've trawled through all the related articles on SO, but I'm still struggling with this one. Any help would be appreciated, thanks.
Complete code, i had changed the height of the rectangle.
public class RectActivity extends Activity {
final String TAG = "RectActivity";
TextView rect1;
RectDrawableView rectView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic);
LinearLayout linear = (LinearLayout) findViewById(R.id.rectangle);
rectView = new RectDrawableView(this);
linear.addView(rectView);
Button sbutton = (Button)findViewById(R.id.sbutton);
sbutton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
RectActivity.this.RunAnimations();
}
});
Button tbutton = (Button)findViewById(R.id.tbutton);
tbutton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
RectActivity.this.runTranslateAnimation();
}
});
}
#Override
public void onResume() {
super.onResume();
RunAnimations();
}
private void RunAnimations() {
Animation rectAnim1 = new ScaleAnimation(1, 1, 1, 1.3f,
ScaleAnimation.RELATIVE_TO_SELF, 0,
ScaleAnimation.ABSOLUTE, 250);
rectAnim1.setFillBefore(false);
rectAnim1.setFillAfter(true);
rectAnim1.setStartOffset(500);
rectAnim1.setDuration(500);
rectView.startAnimation(rectAnim1);
}
private void runTranslateAnimation() {
float x = rectView.getX();
float y = rectView.getY();
TranslateAnimation trans = new TranslateAnimation(0, 0, 0, (90));
trans.setFillAfter(true);
trans.setStartOffset(500);
trans.setDuration(500);
rectView.startAnimation(trans);
}
}
public class RectDrawableView extends View {
Paint paint;
Rect rect;
public RectDrawableView(Context context) {
super(context);
paint = new Paint();
paint.setColor(Color.parseColor("#aacfcce4"));
paint.setStyle(Paint.Style.FILL);
}
protected void onDraw(Canvas canvas) {
int x = 50;
int y = 150;
int width = 50;
int height = 100;
ShapeDrawable shapeDrawable = new ShapeDrawable(new RectShape());
rect = new Rect(x, y, x+width, y+height);
shapeDrawable.setBounds(rect);
shapeDrawable.getPaint().set(paint);
shapeDrawable.draw(canvas);
}
}
Try this code. Keep the pivotYType as ABSOLUTE with value 550 ( y + height )
Animation rectAnim1 = new ScaleAnimation(1, 1, 1, 1.3f,
ScaleAnimation.RELATIVE_TO_SELF, 0,
ScaleAnimation.ABSOLUTE, 550);