I have a custom view and I overrided the ondraw. When I run my program the method invalidate updates the ondraw on my emulator but it doesn't work on real phone at all and the view is fixed on phone.
Anybody knows why?
here is my code:
package com.example.canvas;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.view.View;
public class Myview extends View{
String second="0";
int r=100;
public Myview(Context context) {
super(context);
}
#Override
protected void onDraw(Canvas canvas) {
Paint paint=new Paint();
paint.setColor(Color.GREEN);
paint.setStrokeWidth(12);
canvas.drawLine(getWidth()/2f, getHeight()/2f,getWidth()/2f+ ((r-18.0f)*(float)Math.cos(Math.toRadians((Float.valueOf(second)/60f*360f) -90.0f))) ,getHeight()/2f+((r-18.0f)*(float)Math.sin(Math.toRadians ((Float.valueOf(second)/60f*360f)-90.0f))), paint);
update();
super.onDraw(canvas);
}
private void update() {
Handler h=new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
Calendar c=Calendar.getInstance();
SimpleDateFormat ss=new SimpleDateFormat("ss");
second=ss.format(c.getTime());
invalidate();
}
}, 1000);
}
}
Bingo!when I set timezone for calendar object to my country,invalidate worked and ondraw was updated on emulator and real phone.
Related
Here is my code for the activity main
package com.example.dell_7560.experiment6;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new TouchScreen(this,null));
}
}
Here is the touch screen code
package com.example.dell_7560.experiment6;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class TouchScreen extends View {
private Paint paint=new Paint();
private Path path=new Path();
public TouchScreen(Context context, AttributeSet attributeSet) {
super(context,attributeSet);
paint.setAntiAlias(true);
paint.setStrokeWidth(6f);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
protected void onDraw(Canvas canvas)
{
canvas.drawPath(path,paint);
}
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX,eventY);
return true;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX,eventY);
break;
default:
return false;
}
invalidate();
return true;
}
}
Now the app works as follows:
Touch the screen.
Drag the finger (it creates the red light)
Untouch the screen, the red line creation stops.
Till here it is cool.
My doubt is, how can I clear the content in the ACTION_UP event?
i.e. on untouching the screen, the screen should be as good as new.
What you need to do is tell the view that it's invalid on ActionUp (you do this). Then it will automatically call onDraw again. The trick then is to not draw anything. All you need to do is either clear the path, or set a variable that will cause the draw routine to not draw. The background always clears anyway, so all you need it to not draw the path after the invalidate.
As #Mike M mentioned,
path.reset() works in ACTION_UP case
It clears the screen i.e. canvas when I lift up my finger/touch.
I'm writing a very simple Android drawing program, for which I wrote a class DoodleCanvas.java, which includes (at the very bottom) a function to clear the canvas by filling it with white.
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class DoodleCanvas extends View {
private Paint mPaint; //Paint object for setting attr
private Path mPath; //Path object for tracing Paint over
public Canvas canvas; //Canvas object for calling Paint
public DoodleCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(10);
mPath = new Path();
}
//Draw mPaint over mPath
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(mPath, mPaint);
super.onDraw(canvas);
}
//Create mPath from touch events
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
mPath.moveTo(event.getX(), event.getY());
break;
case MotionEvent.ACTION_MOVE:
mPath.lineTo(event.getX(), event.getY());
invalidate();
break;
}
return true;
}
//Class function for filling canvas with white, effectively cleaning it
public void clearcanvas(Canvas canvas) {
canvas.drawColor(Color.WHITE);
}
}
In my MainActivity.java, I have set up a clear button to call clearcanvas.
package brianslho.basiccanvas;
import android.graphics.Canvas;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
DoodleCanvas dcanvas; //Custom class DoodleCanvas (from "DoodleCanvas.java")
Button btn; //Button for clearing screen
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dcanvas = findViewById(R.id.canvas);
btn = findViewById(R.id.btn);
btn.setOnClickListener(clearcanvas);
}
//Clear screen on button click
protected Button.OnClickListener clearcanvas = new View.OnClickListener() {
#Override
public void onClick(View v) {
//ERROR: canvas is null
Canvas canvas = dcanvas.canvas;
dcanvas.clearcanvas(canvas);
}
};
}
The app crashes whenever I press the clear button. The error message is, in essence, java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Canvas.drawColor(int)' on a null object reference. I've declared the canvas inside onClick, which I'm very sure is not "good coding", but just as an attempt to fix the null problem. I've searched StackOverflow for similar problems (and boy there are a LOT) but couldn't find anything that'd solve this.
Thank you in advance for your help!
Your problem is you have declare variable with the same name: public Canvas canvas; vs public void clearcanvas(Canvas canvas) => program will understand that canvas in your function is the global instead of the parameter of function. => solution: change variable name
you have to call the constructor and you have declared variable with the same name public Canvas canvas; and public void clearcanvas(Canvas canvas).So change the variable.
dcanvas = new DoodleCanvas(Context context, AttributeSet attrs);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am new to android programming and am trying to draw a circle on the screen. Eventually I'd like to have the circle move around. But for now I have been having trouble getting the circle to draw. When I run the code, it gives me an error:
"Attempt to invoke virtual method 'long
android.graphics.Paint.getNativeInstance()' on a null"
My Code:
package com...
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
class MyView extends View {
private Bitmap b;
public Paint p;
public MyView(Context context) {
super(context);
Paint p = new Paint();
p.setColor(Color.GREEN);
b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawCircle(50, 50, 10, p);
}
}
}
Problem with your code is
public MyView(Context context) {
super(context);
Paint p = new Paint();// Problem is here this is local declaration
p = new Paint() // do like this and remove above line
p.setColor(Color.GREEN);
b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
}
I want to add a timer that, on every tick of the timer (1second), causes the line to refresh. How do I use the timer in my code?
The following is my code:
LineRefresh.java:
package LineRefresh.xyz.com;
import java.util.Timer;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
public class LineRefresh extends Activity {
DrawView drawView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
}
}
DrawView.java:
package LineRefresh.xyz.com;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class DrawView extends View {
Paint paint = new Paint();
public DrawView(Context context) {
super(context);
}
#Override
public void onDraw(Canvas canvas) {
paint.setColor(Color.BLACK);
canvas.drawLine(50, 200, 270, 200, paint);
}
}
Here the sollution with Java's Timertask:
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
hereYourMethod();
}
}
};
timer.schedule(task, 1000,1000);// (the task, when to start, when to repeat)
Another way you can do this is the following:
Handler updateHandler;
#Override
public void onCreateBundle savedInstanceState) {
super.onCreate(savedInstanceState);
updateHandler = new Handler();
// Do this first after 1 second
updateHandler.postDelayed(RecurringTask, 1000);
}
Runnable RecurringTask = new Runnable() {
public void run() {
// Do whatever you want
// Call this method again every 30 seconds
updateHandler.postDelayed(this, 30000);
}
};
I had some trouble marshaling to the UI thread with the Timer/TimerTask solution, so here is another one that ended up working for me!
An alternative would be using a Handler.
mHandler = new Handler(new Handler.Callback()
{
#Override
public boolean handleMessage(Message msg)
{
if(msg.what == REFRESH)
{
// TODO Refresh Code
return true;
}
return false;
}
});
mHandler.sendEmptyMessageDelayed(REFRESH, mMilliSecondsToRefresh);
Then when you want it to stop (this should also go in onStop() so that it doesn't continue in the background when your app isnt active):
mHandler.removeMessages(REFRESH);
You can let the thread to sleep for 1 second:
Thread.sleep(1000); //1000 milliseconds = 1 second
If you're using Swing, best to use Swing timer: http://download.oracle.com/javase/tutorial/uiswing/misc/timer.html
In your case, maybe you should use Timer: http://download.oracle.com/javase/6/docs/api/javax/swing/Timer.html
i am making an app to make the hands of a clock.That is, i draw a simple line on the screen and want it rotate like the hands of a clock.how do i do this using a timer?(so that the position of the line refreshes).Only one end point of the line should rotate,while the other remains staionary.In the folllowing code,i only draw a line on the screen:
DrawView.java:
package LineRefresh.xyz.com;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class DrawView extends View {
Paint paint = new Paint();
public DrawView(Context context) {
super(context);
}
#Override
public void onDraw(final Canvas canvas) {
paint.setColor(Color.BLACK);
canvas.drawLine(50, 200, 270, 200, paint);
}
}
LineRefresh.java:
package LineRefresh.xyz.com;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
public class LineRefresh extends Activity {
DrawView drawView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
}
}
Try something like this:
private Handler mHandler = new Handler();
private Runnable MethodToDrawClockLine = new Runnable()
{
public void run()
{
//execute here your drawing routine.
// after drawing set the timer for another x period of time
mHandler.postDelayed(MethodToDrawClockLine, 1000); //it'll re-execute it after 1sec.
}
}
in you OnCreate or any method where you want to Start the Timer you can use:
mHandler.removeCallbacks(mUpdateTimeTask); //be sure to remove any handler before add a new one
mHandler.postDelayed(MethodToDrawClockLine, 1000); //it'll execute it after 1sec.
when you're done, remember to remove the handler.
mHandler.removeCallbacks(mUpdateTimeTask);
That shold be it.