Android Studio app crashes on button click [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Recently I fixed an error, but now I'm stuck at clearing the canvas for my draw project. I already took a look at some other topics with the same question, but it didn't fix my problem.
package org.arkmap.klaas.testdrawing;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class WriteOnScreenActivity extends AppCompatActivity {
Button clear;
TouchEventView myView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write_on_screen);
clear=(Button)findViewById(R.id.clearbutton);
myView = new TouchEventView(this, null);
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vw) {
myView.clearCanvas();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_write_on_screen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
WriteOnScreenActivity.java
package org.arkmap.klaas.testdrawing;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.Random;
/**
* Created by Startklaar on 19-1-2016.
*/
public class TouchEventView extends View {
public Paint paint = new Paint();
private Path path = new Path();
public boolean cc = false;
Random rnd = new Random();
public TouchEventView(Context ctx, AttributeSet attrs) {
super(ctx, attrs);
paint.setAntiAlias(true);
paint.setARGB(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
//paint.setColor(Color.WHITE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(10f);
}
#Override
protected void onDraw(Canvas canvas) {
if (cc) {
path = new Path();
Paint clearPaint = new Paint();
clearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawRect(0, 0, 0, 0, clearPaint);
cc = false;
}
canvas.drawPath(path, paint);
}
public void clearCanvas()
{
cc = true;
invalidate();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float xPos = event.getX();
float yPos = event.getY();
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(xPos, yPos);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(xPos,yPos);
break;
case MotionEvent.ACTION_UP:
break;
default:
return false;
}
invalidate();
return true;
}
}
TouchEventView.java
Hope to get some help here!
EDIT: The error has been fixed, the only problem I have is that the button is not functioning.

myView is not being initialized. You should set it:
myView = (TouchEventView) findViewById(R.id.XXXX);

Related

Android Studio Clear DrawView with a Button

I've setup a fragment with a custom View for drawing strokes.
Right now I want to create a button for clearing the strokes, but this is not possible.
I have two classes
extending fragment class
extending the view class
To clear the canvas I've learned to do something like this:
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
The problem is that the Canvas object is stuck inside the onDraw() method.
But I need the canvas object in the button.setOnClickListener the clear the canvas.
How can I do this?
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.app.ssl.R;
import com.app.ssl.databinding.FragmentDrawviewBinding;
public class DrawviewFragment extends Fragment {
private FragmentDrawviewBinding binding;
private View root;
private View drawView;
private Button btnClear;
private Button btnSave;
public View onCreateView(
#NonNull LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceStage) {
root = inflater.inflate(R.layout.fragment_drawview,container,false);
drawView = root.findViewById(R.id.DrawingView);
btnClear = root.findViewById(R.id.btnClean1);
btnSave = root.findViewById(R.id.btnSave);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
System.out.println("CLEAR");
//drawView.setBackgroundColor(Color.WHITE);
// CLEAR CANVAS
//DrawView.canvas.drawColor(Color.WHITE);
//DrawView.canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
DrawView.canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.MULTIPLY);
//DrawView.onDraw(new Canvas());
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
System.out.println("SAVE");
}
});
return root;
}
}
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 DrawView extends View {
private Paint drawPaint;
private Path path = new Path();
static Canvas canvas;
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
setFocusableInTouchMode(true);
setupPaint();
}
// Setup paint with color and stroke styles
private void setupPaint() {
drawPaint = new Paint();
drawPaint.setColor(Color.BLACK);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(5);
drawPaint.setStyle(Paint.Style.STROKE); // draw with stroke
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
DrawView.canvas = canvas;
canvas.drawPath(path, drawPaint);
}
// Get x and y and append them to the path
public boolean onTouchEvent(MotionEvent event) {
float pointX = event.getX();
float pointY = event.getY();
// Checks for the event that occurs
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Starts a new line in the path
path.moveTo(pointX, pointY);
break;
case MotionEvent.ACTION_MOVE:
// Draws line between last point and this point
path.lineTo(pointX, pointY);
break;
default:
return false;
}
postInvalidate(); // Indicate view should be redrawn
return true; // Indicate we've co
}
}
I found the solution based on this Tutorial

I am getting a null pointer exception but I don't know why and the supposed saved drawing won't load

I am building an app that has multiple fragments and about half of those fragments contain a custom view that a user can draw lines with a finger (we'll call canvas), I am using a test app before I add new code to the main app. What I'm trying to do is to save the lines drawn by the user who then leaves the fragment for another one and draws some lines on the canvas in that fragment and can go back to the previous fragment (the drawing of the second will get saved) where the drawing for that fragment only will show in the canvas. If the user goes back to the second fragment, the drawing for the second fragment only will show, and also, the drawings should still be there when the app closes. I am using SharedPreferences.
When I go to one fragment (LineLHwFragment), I can draw on the canvas and click on save (I'll show where in the code) and it'll say "Data saved". If I close the app and load it again and go to that fragment, the drawing is not loaded.
Also, if I go to the other fragment (ChatFragment) either after clicking the first fragment or going to it first, the app crashes and I get this error message:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Iterator java.util.ArrayList.iterator()' on a null object reference
at com.josullivan.mytestapplication.PaintView.onDraw(PaintView.java:112)
I am not sure as to why it is not loading the drawing or why it crashes
LineLHwFragment
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class LineLHwFragment extends Fragment {
private PaintView paintView;
public ArrayList test;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_line_l_hw, container, false);
paintView = v.findViewById(R.id.lineLPaintView);
//This should get the drawing to load
loadData();
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
paintView.init(metrics);
setHasOptionsMenu(true);
return v;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.normal:
paintView.normal();
//this is where the saving should happen when clicked
saveData();
return true;
case R.id.clear:
paintView.clear();
return true;
}
return super.onOptionsItemSelected(item);
}
private void saveData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("line test 1",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(paintView.getPaths());
editor.putString("line test", json);
editor.apply();
Toast.makeText(this.getActivity(), "Data saved", Toast.LENGTH_SHORT).show();
}
private void loadData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("line test 1",
Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("line test", null);
Type type = new TypeToken<ArrayList<FingerPath>>() {}.getType();
test = paintView.getPaths();
test = gson.fromJson(json, type);
paintView.setPaths(test);
}
}
ChatFragment
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class ChatFragment extends Fragment {
private PaintView paintView;
public ArrayList test;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_chat, container, false);
paintView = v.findViewById(R.id.paintView1);
loadData();
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
paintView.init(metrics);
setHasOptionsMenu(true);
return v;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.normal:
paintView.normal();
saveData();
return true;
case R.id.clear:
paintView.clear();
return true;
}
return super.onOptionsItemSelected(item);
}
private void saveData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("chat test 1",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(paintView.getPaths());
editor.putString("chat test", json);
editor.apply();
Toast.makeText(this.getActivity(), "Data saved", Toast.LENGTH_SHORT).show();
}
private void loadData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("chat test 1",
Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("chat test", null);
Type type = new TypeToken<ArrayList<FingerPath>>() {}.getType();
test = paintView.getPaths();
test = gson.fromJson(json, type);
paintView.setPaths(test);
}
}
PaintView.java
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.EmbossMaskFilter;
import android.graphics.MaskFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
public class PaintView extends View {
public static int BRUSH_SIZE = 10;
public static final int DEFAULT_COLOR = Color.WHITE;
public static int DEFAULT_BG_COLOR = Color.GRAY;
private static final float TOUCH_TOLERANCE = 4;
private float mX, mY;
private Path mPath;
private Paint mPaint;
private static ArrayList<FingerPath> paths = new ArrayList<>();
private int currentColor;
private int backgroundColor = DEFAULT_BG_COLOR;
private int strokeWidth;
private boolean emboss;
private boolean blur;
private MaskFilter mEmboss;
private MaskFilter mBlur;
private Bitmap mBitmap;
private Canvas mCanvas;
private Paint mBitmapPaint = new Paint(Paint.DITHER_FLAG);
public PaintView(Context context) {
this(context, null);
}
public PaintView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(DEFAULT_COLOR);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setXfermode(null);
mPaint.setAlpha(0xff);
mEmboss = new EmbossMaskFilter(new float[] {1, 1, 1}, 0.4f, 6, 3.5f);
mBlur = new BlurMaskFilter(5, BlurMaskFilter.Blur.NORMAL);
}
public ArrayList getPaths() {
return paths;
}
public ArrayList setPaths(ArrayList<FingerPath> list) {
return this.paths = list;
}
//public Path getMPath() {
//return mPath;
// }
public void init(DisplayMetrics metrics) {
int height = metrics.heightPixels;
int width = metrics.widthPixels;
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
currentColor = DEFAULT_COLOR;
strokeWidth = BRUSH_SIZE;
}
public void normal() {
emboss = false;
blur = false;
}
public void clear() {
backgroundColor = DEFAULT_BG_COLOR;
paths.clear();
normal();
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.save();
mCanvas.drawColor(backgroundColor);
//The null pointer exception points to this line
for (FingerPath fp: paths) {
mPaint.setColor(fp.color);
mPaint.setStrokeWidth(fp.strokeWidth);
mPaint.setMaskFilter(null);
if (fp.emboss)
mPaint.setMaskFilter(mEmboss);
else if (fp.blur)
mPaint.setMaskFilter(mBlur);
mCanvas.drawPath(fp.path, mPaint);
}
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.restore();
}
private void touchStart(float x, float y) {
mPath = new Path();
FingerPath fp = new FingerPath(currentColor, emboss, blur, strokeWidth, mPath);
paths.add(fp);
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touchMove(float x, float y) {
float dx = Math.abs(x-mX);
float dy = Math.abs(y-mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touchUp() {
mPath.lineTo(mX, mY);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN :
touchStart(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE :
touchMove(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP :
touchUp();
invalidate();
break;
}
return true;
}
}

Problem with Button. I want to hold down on an image and drag it to an specific location, which should open an activity

Honestly I dont know how to proceed. I looked up some feeds on this website and got a bit confused. The imageview button should be invisibly dragged at the specific location of an other image and as long as my pressed thumb relocates to the other image, a activity should be called. In an earlier version, the activity was functional but not while moving the button while it is hold down with my thumb. Hopefully someone knows an answer for this (for me very challenging question.
#Override
public boolean onTouchEvent(MotionEvent event) {
if (imageRect == null) {
imageRect = new Rect();
imageView2.getGlobalVisibleRect(imageRect);
}
int x = (int) event.getX();
int y = (int) event.getY();
if (imageRect.contains(x, y)) {
openActivity();
}
return super.onTouchEvent(event);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
detectorCompat = new GestureDetectorCompat(this, new GestureListener());
imageViewPlayButton = findViewById(R.id.PlayButton_Image_White_Base);
imageView2 = findViewById(R.id.register_Icon_Base);
imageView3 = findViewById(R.id.navigation_Background_Image_Register);
imageView4 = findViewById(R.id.Login_Icon_Base);
imageViewPlayButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
imageView2.setVisibility(View.VISIBLE);
imageView3.setVisibility(View.VISIBLE);
imageView4.setVisibility(View.VISIBLE);
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
imageView2.setVisibility(View.INVISIBLE);
imageView3.setVisibility(View.INVISIBLE);
imageView4.setVisibility(View.INVISIBLE);
}
return true;
}
});
}
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GestureDetectorCompat;
import android.annotation.SuppressLint;
import android.app.RemoteInput;
import android.content.Intent;
import android.graphics.Rect;
import android.media.effect.Effect;
import android.os.Bundle;
import android.os.Handler;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ImageView imageViewPlayButton, imageView2, imageView3, imageView4;
private Rect imageRect;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
detectorCompat = new GestureDetectorCompat(this, new GestureListener());
imageViewPlayButton = findViewById(R.id.PlayButton_Image_White_Base);
imageView2 = findViewById(R.id.register_Icon_Base);
imageView3 = findViewById(R.id.navigation_Background_Image_Register);
imageView4 = findViewById(R.id.Login_Icon_Base);
imageViewPlayButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
imageView2.setVisibility(View.VISIBLE);
imageView3.setVisibility(View.VISIBLE);
imageView4.setVisibility(View.VISIBLE);
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
imageView2.setVisibility(View.INVISIBLE);
imageView3.setVisibility(View.INVISIBLE);
imageView4.setVisibility(View.INVISIBLE);
}
return false;
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (imageRect == null) {
imageRect = new Rect();
imageView2.getGlobalVisibleRect(imageRect);
}
int x = (int) event.getX();
int y = (int) event.getY();
if (imageRect.contains(x, y)) {
openActivity();
}
return true;
}
private void openActivity() {
Intent intent = new Intent(this, Register.class);
startActivity(intent);
overridePendingTransition(0, 0);
}
}

How to move Image after zooming in android

I just need your help about how we can move our images when after zooming it. I have done all rest of the things but only facing problem with moving images while zooming and get back to their normal size ? Please help me
here is my code;
MainActivity.java
package com.example.saeed.zooming;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.BatteryManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
public class MainActivity extends Activity {
private ImageView iv;
private Matrix matrix = new Matrix();
private float scale = 1f;
private ScaleGestureDetector SGD;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv=(ImageView)findViewById(R.id.imageView);
SGD = new ScaleGestureDetector(this,new ScaleListener());
}
public boolean onTouchEvent(MotionEvent ev) {
SGD.onTouchEvent(ev);
return true;
}
private class ScaleListener extends ScaleGestureDetector.
SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
scale *= detector.getScaleFactor();
scale = Math.max(0.1f, Math.min(scale, 5.0f));
matrix.setScale(scale, scale);
iv.setImageMatrix(matrix);
return true;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Please try MultiTouchLibrary . It will fulfill your need This library provide you below functionality
Rotate
Scale Image (Pinch to zoom)
Move

Performing stop of activity that is not resumed?

I am making a simple Android app just to become familiar with the concept. I have an app with two activities, the first should just be a splash screen that displays for one second, the second is a canvas w/ a black square that turns cyan when you click it. When I run it, it stops with an error in the log saying "performing stop of activity that is not resumed".
Main Activity:
package com.example.test;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
Thread.sleep(1000);
}catch(Exception e){}
Intent in = new Intent(this, Afspl.class);
startActivity(in);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Next Activity:
package com.example.test;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
public class Afspl extends Activity {
public DrawView vi;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
vi = new DrawView(this);
}
class DrawView extends View{
Paint paint = new Paint();
public DrawView(Context context){
super(context);
}
public void onDraw(Canvas c){
paint.setColor(col);
c.drawRect(40, 40, 200, 200, paint);
}
private int col = Color.BLACK;
public void setToColor(int c){
col=c;
}
}
public boolean onTouchEvent(MotionEvent me){
if(me.getX()>=30 && me.getX() <= 320 && me.getY() >=30 && me.getY() <= 320)vi.setToColor(Color.CYAN);
return super.onTouchEvent(me);
}
}
Do you have any idea why I'm getting this error or what it means or how I can fix this? All help is appreciated.
Insted of using:
try{
Thread.sleep(1000);
}catch(Exception e){}
Intent in = new Intent(this, Afspl.class);
startActivity(in);
You could try using new
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent in = new Intent(getApplicationContext(), Afspl.class);
startActivity(in);
}
}, 1000);
You should never put to sleep the main thread. If you want to do something in the future use a Handler and a Runnable.
Also, you should declare a View on both Activities, not just the first one. Create a View and set it with "setContentView()" on your second activity.

Categories

Resources