I am developing an Android drawing app.
When I run this code it says application is doing too much work on it's main thread in logcat.I am not able to draw.PLEASE HELP ME.Thank you
THIS IS MY DRAWIT CLASS
public class Drawit extends Activity {
LinearLayout linearLayout;
ImageButton oclear,save,ocancel;
View mview;
DrawCanvas drawCanvas;
public static String tempDir;
public static String unique_id;
public static String current=null;
public Bitmap mBitmap;
public EditText yourName;
File myPath;
protected void onCreate(Bundle savedInsatnceState) {
// TODO Auto-generated method stub
super.onCreate(savedInsatnceState);
setContentView(R.layout.drawit);
linearLayout = (LinearLayout) findViewById(R.id.linearLayout11);
tempDir = Environment.getExternalStorageDirectory()+"/"+getResources().getString(R.string.external_dir);
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory= contextWrapper.getDir(getResources().getString(R.string.external_dir),MODE_PRIVATE);
preparedirectory();
yourName = (EditText) findViewById(R.id.editText1);
myPath = new File(directory,current);
drawCanvas = new DrawCanvas(this, null);
drawCanvas.setBackgroundColor(Color.WHITE);
linearLayout.addView(drawCanvas,LayoutParams.FILL_PARENT);
}
}
THIS IS MY DRAW CANVAS METHOD
public class DrawCanvas extends View
{
public Paint paint = new Paint();
public Path path = new Path();
public final RectF dirtyRect = new RectF();
public float lastTouchX;
public float lastTouchY;
public DrawCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
paint.setColor(Color.BLACK);
paint.setStrokeWidth(5f);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setAntiAlias(true);
}
protected void ondraw(Canvas canvas) {
canvas.drawPath(path,paint);
}
public void save(View mview) throws IOException{
// TODO Auto-generated method stub
if(mBitmap == null)
{
mBitmap = Bitmap.createBitmap(linearLayout.getWidth(),linearLayout.getHeight(),Bitmap.Config.RGB_565);
}
Canvas canvas = new Canvas(mBitmap);
try {
FileOutputStream fileoutputstream = new FileOutputStream(myPath);
mview.draw(canvas);
mBitmap.compress(Bitmap.CompressFormat.PNG , 90, fileoutputstream);
fileoutputstream.flush();
fileoutputstream.close();
String uri = Images.Media.insertImage(getContentResolver(),mBitmap,"title",null);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void clear() {
// TODO Auto-generated method stub
path.reset();
invalidate();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
lastTouchX = eventX;
lastTouchY = eventY;
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
resetDirtyRect(eventX,eventY);
int historyRectSize = event.getHistorySize();
for(int i=0;i<historyRectSize;i++)
{
float historicalx = event.getHistoricalX(i);
float historicaly = event.getHistoricalY(i);
expandDirtyRect(historicalx,historicaly);
path.lineTo(historicalx, historicaly);
}
break;
}
return true;
}
private void expandDirtyRect(float historicalx, float historicaly) {
// TODO Auto-generated method stub
if(historicalx < dirtyRect.left)
{
dirtyRect.left = historicalx;
} else if(historicalx >dirtyRect.right)
{
dirtyRect.left = historicalx;
}
if(historicaly < dirtyRect.top)
{
dirtyRect.top = historicaly;
} else if(historicaly >dirtyRect.bottom)
{
dirtyRect.bottom = historicaly;
}
}
private void resetDirtyRect(float eventX, float eventY) {
// TODO Auto-generated method stub
dirtyRect.left = Math.min(lastTouchX,eventX);
dirtyRect.right = Math.max(lastTouchX,eventX);
dirtyRect.top = Math.min(lastTouchY,eventY);
dirtyRect.bottom = Math.max(lastTouchY,eventY);
}
}
}
Related
2020-04-22 16:14:49.759 1809-1809/? E/servicemanager: Could not find android.hardware.power.IPower/default in the VINTF manifest.
This keeps popping up. Am coding a camera, that when a button is clicked, an image is cropped.
Here is a custom view I am adding to a fragment.
public class DrawView extends View {
Point[] points = new Point[4];
/**
* point1 and point 3 are of same group and same as point 2 and point4
*/
int groupId = -1;
private ArrayList<ColorBall> colorballs = new ArrayList<>();
private int mStrokeColor = Color.parseColor("#AADB1255");
private int mFillColor = Color.parseColor("#55DB1255");
private Rect mCropRect = new Rect();
// array that holds the balls
private int balID = 0;
// variable to know what ball is being dragged
Paint paint;
public DrawView(Context context) {
this(context, null);
}
public DrawView(Context context, AttributeSet attrs) {
this(context, attrs, -1);
}
public DrawView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
paint = new Paint();
setFocusable(true); // necessary for getting the touch events
}
private void initRectangle(int X, int Y) {
//initialize rectangle.
points[0] = new Point();
points[0].x = X - 200;
points[0].y = Y - 100;
points[1] = new Point();
points[1].x = X;
points[1].y = Y + 30;
points[2] = new Point();
points[2].x = X + 30;
points[2].y = Y + 30;
points[3] = new Point();
points[3].x = X + 30;
points[3].y = Y;
balID = 2;
groupId = 1;
// declare each ball with the ColorBall class
for (int i = 0; i < points.length; i++) {
colorballs.add(new ColorBall(getContext(), R.drawable.gray_circle, points[i], i));
}
}
// the method that draws the balls
#Override
protected void onDraw(Canvas canvas) {
if(points[3]==null) {
//point4 null when view first create
initRectangle(getWidth() / 2, getHeight() / 2);
}
int left, top, right, bottom;
left = points[0].x;
top = points[0].y;
right = points[0].x;
bottom = points[0].y;
for (int i = 1; i < points.length; i++) {
left = left > points[i].x ? points[i].x : left;
top = top > points[i].y ? points[i].y : top;
right = right < points[i].x ? points[i].x : right;
bottom = bottom < points[i].y ? points[i].y : bottom;
}
paint.setAntiAlias(true);
paint.setDither(true);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(5);
//draw stroke
paint.setStyle(Paint.Style.STROKE);
paint.setColor(mStrokeColor);
paint.setStrokeWidth(2);
mCropRect.left = left + colorballs.get(0).getWidthOfBall() / 2;
mCropRect.top = top + colorballs.get(0).getWidthOfBall() / 2;
mCropRect.right = right + colorballs.get(2).getWidthOfBall() / 2;
mCropRect.bottom = bottom + colorballs.get(3).getWidthOfBall() / 2;
canvas.drawRect(mCropRect, paint);
//fill the rectangle
paint.setStyle(Paint.Style.FILL);
paint.setColor(mFillColor);
paint.setStrokeWidth(0);
canvas.drawRect(mCropRect, paint);
// draw the balls on the canvas
paint.setColor(Color.RED);
paint.setTextSize(18);
paint.setStrokeWidth(0);
for (int i =0; i < colorballs.size(); i ++) {
ColorBall ball = colorballs.get(i);
canvas.drawBitmap(ball.getBitmap(), ball.getX(), ball.getY(),
paint);
canvas.drawText("" + (i+1), ball.getX(), ball.getY(), paint);
}
}
// events when touching the screen
public boolean onTouchEvent(MotionEvent event) {
int eventAction = event.getAction();
int X = (int) event.getX();
int Y = (int) event.getY();
switch (eventAction) {
case MotionEvent.ACTION_DOWN: // touch down so check if the finger is on
// a ball
if (points[0] == null) {
initRectangle(X, Y);
} else {
//resize rectangle
balID = -1;
groupId = -1;
for (int i = colorballs.size()-1; i>=0; i--) {
ColorBall ball = colorballs.get(i);
// check if inside the bounds of the ball (circle)
// get the center for the ball
int centerX = ball.getX() + ball.getWidthOfBall();
int centerY = ball.getY() + ball.getHeightOfBall();
paint.setColor(Color.CYAN);
// calculate the radius from the touch to the center of the
// ball
double radCircle = Math
.sqrt((double) (((centerX - X) * (centerX - X)) + (centerY - Y)
* (centerY - Y)));
if (radCircle < ball.getWidthOfBall()) {
balID = ball.getID();
if (balID == 1 || balID == 3) {
groupId = 2;
} else {
groupId = 1;
}
invalidate();
break;
}
invalidate();
}
}
break;
case MotionEvent.ACTION_MOVE: // touch drag with the ball
if (balID > -1) {
// move the balls the same as the finger
colorballs.get(balID).setX(X);
colorballs.get(balID).setY(Y);
paint.setColor(Color.CYAN);
if (groupId == 1) {
colorballs.get(1).setX(colorballs.get(0).getX());
colorballs.get(1).setY(colorballs.get(2).getY());
colorballs.get(3).setX(colorballs.get(2).getX());
colorballs.get(3).setY(colorballs.get(0).getY());
} else {
colorballs.get(0).setX(colorballs.get(1).getX());
colorballs.get(0).setY(colorballs.get(3).getY());
colorballs.get(2).setX(colorballs.get(3).getX());
colorballs.get(2).setY(colorballs.get(1).getY());
}
invalidate();
}
break;
case MotionEvent.ACTION_UP:
// touch drop - just do things here after dropping
break;
}
// redraw the canvas
invalidate();
return true;
}
public Drawable doTheCrop(Bitmap sourceBitmap) throws IOException {
//Bitmap sourceBitmap = null;
//Drawable backgroundDrawable = getBackground();
/*
if (backgroundDrawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) backgroundDrawable;
if(bitmapDrawable.getBitmap() != null) {
sourceBitmap = bitmapDrawable.getBitmap();
}
}*/
//source bitmap was scaled, you should calculate the rate
float widthRate = ((float) sourceBitmap.getWidth()) / getWidth();
float heightRate = ((float) sourceBitmap.getHeight()) / getHeight();
//crop the source bitmap with rate value
int left = (int) (mCropRect.left * widthRate);
int top = (int) (mCropRect.top * heightRate);
int right = (int) (mCropRect.right * widthRate);
int bottom = (int) (mCropRect.bottom * heightRate);
Bitmap croppedBitmap = Bitmap.createBitmap(sourceBitmap, left, top, right - left, bottom - top);
Drawable drawable = new BitmapDrawable(getResources(), croppedBitmap);
return drawable;
/*
setContentView(R.layout.fragment_dashboard);
Button btn = (Button)findViewById(R.id.capture);
if (btn == null){
System.out.println("NULL");
}
try{
btn.setText("HI");
}
catch (Exception e){
}
//setBackground(drawable);*/
//savebitmap(croppedBitmap);
}
private File savebitmap(Bitmap bmp) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ "/" + "testimage.jpg");
Toast.makeText(getContext(), "YUP", Toast.LENGTH_LONG).show();
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
return f;
}
public static class ColorBall {
Bitmap bitmap;
Context mContext;
Point point;
int id;
public ColorBall(Context context, int resourceId, Point point, int id) {
this.id = id;
bitmap = BitmapFactory.decodeResource(context.getResources(),
resourceId);
mContext = context;
this.point = point;
}
public int getWidthOfBall() {
return bitmap.getWidth();
}
public int getHeightOfBall() {
return bitmap.getHeight();
}
public Bitmap getBitmap() {
return bitmap;
}
public int getX() {
return point.x;
}
public int getY() {
return point.y;
}
public int getID() {
return id;
}
public void setX(int x) {
point.x = x;
}
public void setY(int y) {
point.y = y;
}
}
}
Here is the fragment that I have added a camera do, basically the main part of the application that I am working on.
public class DashboardFragment extends Fragment {
private DashboardViewModel dashboardViewModel;
//All my constants
private DrawView mDrawView;
private Drawable imgDraw;
private TextureView txtView;
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static{
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 180);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
private String cameraID;
private String pathway;
CameraDevice cameraDevice;
CameraCaptureSession cameraCaptureSession;
CaptureRequest captureRequest;
CaptureRequest.Builder captureRequestBuilder;
private Size imageDimensions;
private ImageReader imageReader;
private File file;
Handler mBackgroundHandler;
HandlerThread mBackgroundThread;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
dashboardViewModel =
ViewModelProviders.of(this).get(DashboardViewModel.class);
View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
try{
txtView = (TextureView)root.findViewById(R.id.textureView);
txtView.setSurfaceTextureListener(textureListener);
mDrawView = root.findViewById(draw_view);
Button cap = (Button)root.findViewById(R.id.capture);
cap.setClickable(true);
cap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Log.i("HOLA","HOLA");
takePicture();
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
});
}
catch (Exception e){
Log.i("HI",e.toString());
}
/*
txtView = (TextureView)root.findViewById(R.id.textureView);
txtView.setSurfaceTextureListener(textureListener);
mDrawView = root.findViewById(R.id.draw_view);
Button cap = (Button)root.findViewById(R.id.capture);
cap.setClickable(true);
cap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Log.i("HOLA","HOLA");
takePicture();
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
});*/
return root;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults){
if (requestCode == 101){
if (grantResults[0] == PackageManager.PERMISSION_DENIED){
Toast.makeText(getActivity().getApplicationContext(), "Permission is required",Toast.LENGTH_LONG);
}
}
}
TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
try {
openCamera();
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
}
};
private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(#NonNull CameraDevice camera) {
cameraDevice = camera;
try {
createCameraPreview();
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void onDisconnected(#NonNull CameraDevice cameraDevice) {
cameraDevice.close();
}
#Override
public void onError(#NonNull CameraDevice cameraDevice, int i) {
cameraDevice.close();
cameraDevice = null;
}
};
private void createCameraPreview() throws CameraAccessException {
SurfaceTexture texture = txtView.getSurfaceTexture(); //?
texture.setDefaultBufferSize(imageDimensions.getWidth(), imageDimensions.getHeight());
Surface surface = new Surface(texture);
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession session) {
if (cameraDevice == null){
return;
}
cameraCaptureSession = session;
try {
updatePreview();
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(getActivity().getApplicationContext(), "CONFIGURATION", Toast.LENGTH_LONG);
}
}, null);
}
private void updatePreview() throws CameraAccessException {
if (cameraDevice == null){
return;
}
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
cameraCaptureSession.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
}
private void openCamera() throws CameraAccessException {
CameraManager manager = (CameraManager) getActivity().getSystemService(Context.CAMERA_SERVICE);
cameraID = manager.getCameraIdList()[0];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraID);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
imageDimensions = map.getOutputSizes(SurfaceTexture.class)[0];
if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
return;
}
manager.openCamera(cameraID, stateCallback, null);
}
private void takePicture() throws CameraAccessException {
if (cameraDevice == null) {
Log.i("NOt working", "hi");
return;
}
CameraManager manager = (CameraManager) getActivity().getSystemService(Context.CAMERA_SERVICE);
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
Size[] jpegSizes = null;
jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
int width = 640;
int height = 480;
if (jpegSizes != null && jpegSizes.length > 0) {
width = jpegSizes[0].getWidth();
height = jpegSizes[0].getHeight();
}
final ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
List<Surface> outputSurfaces = new ArrayList<>(2);
outputSurfaces.add(reader.getSurface());
outputSurfaces.add(new Surface(txtView.getSurfaceTexture()));
final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(reader.getSurface());
captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
int rotation = getActivity().getWindowManager().getDefaultDisplay().getRotation();
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
file = new File(Environment.getExternalStorageDirectory() + "/" + ts + ".jpg");
pathway = Environment.getExternalStorageDirectory() + "/" + ts + ".jpg";
//cameraDevice.close();
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader imageReader) {
Image image = null;
//image = reader.acquireLatestImage();
image = reader.acquireNextImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes , 0, bytes.length);
try {
Drawable back = mDrawView.doTheCrop(bitmap);
Button btn = (Button)getView().findViewById(R.id.capture);
btn.setBackground(back);
} catch (IOException e) {
e.printStackTrace();
}
/*
try {
save(bytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (image != null){
image.close();
}
}*/
}
};
reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback(){
#Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result){
super.onCaptureCompleted(session, request, result);
try {
createCameraPreview();
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
};
cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession session) {
try {
session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
}
}, mBackgroundHandler);
}
private void save (byte[] bytes) throws IOException {
OutputStream outputStream = null;
outputStream = new FileOutputStream(file);
outputStream.write(bytes);
Toast.makeText(getActivity().getApplicationContext(),pathway,Toast.LENGTH_LONG).show();
outputStream.close();
imgDraw = Drawable.createFromPath(pathway);
//mDrawView.doTheCrop(imgDraw);
}
#Override
public void onResume(){
super.onResume();
startBackgroundThread();
if (txtView.isAvailable()){
try {
openCamera();
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
else{
txtView.setSurfaceTextureListener(textureListener);
}
}
private void startBackgroundThread() {
mBackgroundThread = new HandlerThread("Camera Background");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
protected void stopBackgroundThread() throws InterruptedException{
mBackgroundThread.quitSafely();
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
}
#Override
public void onPause(){
try {
stopBackgroundThread();
} catch (InterruptedException e) {
e.printStackTrace();
}
super.onPause();
}
}
Here is the xml file for that fragment.
<?xml version="1.0" encoding="utf-8"?>
<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=".ui.dashboard.DashboardFragment">
<TextureView
android:id = "#+id/textureView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.PeavlerDevelopment.OpinionMinion.ui.dashboard.DrawView
android:id="#+id/draw_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:id="#+id/capture"
android:layout_width="100dp"
android:layout_height="200dp"
android:clickable="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"></Button>
</androidx.constraintlayout.widget.ConstraintLayout>
The problem seems to lie somewhere in the doCrop method of the DrawView class.
If there is anything else that would help make the problem more clear, let me know! I will gladly share the github repo with you.
Thank you.
As you can see in Android Design Documenation the VINTF stands for Vendor Interface and its a Manifest structure to aggregate data form the device. That specific log means that your manifest is missing something like this:
<hal>
<name>android.hardware.power</name>
<transport>hwbinder</transport>
<version>1.1</version>
<interface>
<name>IPower</name>
<instance>default</instance>
</interface>
</hal>
which basically is hardware power information.
I think it's not related to what you are trying to do, but I need more info than that log.
I have been stuck on this problem for the past week and a half. I made a game using the "Kilobolt" framework, and I have been trying to implement in App Purchase's in my app and i've tried every way possible but I keep getting the same error, that there is a null pointer exception.
06-13 21:40:18.991: E/AndroidRuntime(16384): java.lang.NullPointerException
06-13 21:40:18.991: E/AndroidRuntime(16384): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
I have 1 activity where I have my method levelTwoButtonClicked() and I am calling that method from a java class, this is where the null pointer exception is coming from and it is because of getPackageName().
I have this in a try catch statement:
skuDetails = mService.getSkuDetails(3, getPackageName(), "inapp", querySkus);.
I have done some research and I read that there could be a issue with the context and calling getPackageName() but havent been able to figure out the issue yet thanks for any one who can help me resolve this!
public abstract class AndroidGame extends Activity implements Game {
public static Context mContext;
IInAppBillingService mService;
ServiceConnection mServiceConn;
static final String ITEM_SKU = "android.test.purchased";
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
int frameBufferWidth = isPortrait ? 480: 800;
int frameBufferHeight = isPortrait ? 800: 480;
Bitmap frameBuffer = Bitmap.createBitmap(frameBufferWidth,
frameBufferHeight, Config.RGB_565);
float scaleX = (float) frameBufferWidth
/ getWindowManager().getDefaultDisplay().getWidth();
float scaleY = (float) frameBufferHeight
/ getWindowManager().getDefaultDisplay().getHeight();
renderView = new AndroidFastRenderView(this, frameBuffer);
graphics = new AndroidGraphics(getAssets(), frameBuffer);
fileIO = new AndroidFileIO(this);
audio = new AndroidAudio(this);
input = new AndroidInput(this, renderView, scaleX, scaleY);
screen = getInitScreen();
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(renderView);
setContentView(layout);
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "MyGame");
mContext = getBaseContext();
mServiceConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name,
IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
}
};
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
public void levelTwoButtonClicked(){
Assets.click.play(1.00f);
ArrayList<String> skuList = new ArrayList<String> ();
skuList.add("android.test.purchased");
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
Bundle skuDetails;
try {
skuDetails = mService.getSkuDetails(3, getPackageName(), "inapp", querySkus);
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList) {
JSONObject object = new JSONObject(thisResponse);
String sku = object.getString("productId");
String price = object.getString("price");
if (sku.equals("android.test.purchased")) {
Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
}
}
}
} catch (RemoteException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (SendIntentException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1001) {
int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
if (resultCode == RESULT_OK) {
try {
JSONObject jo = new JSONObject(purchaseData);
String sku = jo.getString("android.test.purchased");
Toast.makeText(mContext,"You have bought the " + sku + ". Excellent choice,adventurer!", Toast.LENGTH_LONG).show();
}
catch (JSONException e) {
Toast.makeText(mContext,"Failed to parse purchase data.", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
}
public static Context getContext(){
return mContext;
}
#Override
public void onResume() {
super.onResume();
wakeLock.acquire();
screen.resume();
renderView.resume();
mAdView.resume();
if(Assets.mainmenuloop.isStopped()){
Assets.mainmenuloop.play();
}
}
#Override
public void onPause() {
super.onPause();
wakeLock.release();
renderView.pause();
screen.pause();
mAdView.pause();
if(Assets.mainmenuloop.isPlaying()){
Assets.mainmenuloop.stop();
}
SharedPreferences HighScoreData = getSharedPreferences("high", 0);
SharedPreferences.Editor editor = HighScoreData.edit();
editor.putInt("score", highScore);
editor.putInt("secondScore", secondHighScore);
editor.putInt("thirdScore", thirdHighScore);
editor.putInt("fourthScore", fourthHighScore);
editor.commit();
if (isFinishing())
screen.dispose();
}
#Override
public Input getInput() {
return input;
}
#Override
public FileIO getFileIO() {
return fileIO;
}
#Override
public Graphics getGraphics() {
return graphics;
}
#Override
public Audio getAudio() {
return audio;
}
#Override
public void onDestroy() {
super.onDestroy();
mAdView.destroy();
/*
if (mService != null) {
unbindService(mServiceConn);
}
*/
}
#Override
public void setScreen(Screen screen) {
if (screen == null)
throw new IllegalArgumentException("Screen must not be null");
this.screen.pause();
this.screen.dispose();
screen.resume();
screen.update(0);
this.screen = screen;
}
public Screen getCurrentScreen() {
return screen;
}
}
// END OF ACTIVITY CLASS
// BEGIN REGULAR JAVA CLASS
public class InAppPurchase extends Screen {
AndroidGame Buy = new PurchaseLevels();
public InAppPurchase(Game game) {
super(game);
}
#Override
public void update(float deltaTime) {
// TODO Auto-generated method stub
#SuppressWarnings("unused")
Graphics g = game.getGraphics();
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
int len = touchEvents.size();
for(int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
if(event.type == TouchEvent.TOUCH_UP) {
if(inBounds(event, 195, 142, 235, 55)) {
// UNLOCK LEVEL TWO
Buy.levelTwoButtonClicked();
}
if(inBounds(event, 195, 310, 235, 55)) {
// UNLOCK LEVEL THREE
}
if(inBounds(event, 195, 490, 235, 55)) {
// UNLOCK LEVEL FOUR
}
if(inBounds(event, 70, 630, 210, 55)) {
// RESTORE BUTTON
Assets.click.play(1.00f);
}
if(inBounds(event, 330, 635, 130, 130)) {
game.setScreen(new MainMenuScreen(game));
Assets.click.play(1.00f);
}
}
}
}
private boolean inBounds(TouchEvent event, int x, int y, int width,
int height) {
if (event.x > x && event.x < x + width - 1 && event.y > y
&& event.y < y + height - 1){
return true;
} else {
return false;
}
}
public void updateUI(){
}
#Override
public void paint(float deltaTime) {
// TODO Auto-generated method stub
}
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
// TODO Auto-generated method stub
}
#Override
public void backButton() {
// TODO Auto-generated method stub
}
}
// MAIN ACTIVITY SUBCLASS HAD TO MAKE THIS TO CREATE AN INSTANCE OF MY ABSTRACT MAIN ACTIVITY "ANDROIDGAME" IN MY IN APP PURCHASE CLASS, IN ORDER TO CALL "LEVELTWOBUTTONCLICKED"
public class PurchaseLevels extends AndroidGame {
#Override
public Screen getInitScreen() {
// TODO Auto-generated method stub
return null;
}
}
So Im doing a little up, not a big deal, just learning graphics, but when i click on the back button, the app crashes and it gives me fatal error 11.
Code:
public class MyPachuSurface extends SurfaceView implements Runnable{
SurfaceHolder myHolder;
Thread myThread = null;
boolean isRunning = false;
public float x,y,startX,startY,finalX,finalY,dx,dy,tx,ty;
public MyPachuSurface(Context context)
{
super(context);
// TODO Auto-generated constructor stub
myHolder = getHolder();
this.x = 0;
this.y = 0;
this.startX = 0;
this.startY = 0;
this.finalX = 0;
this.finalY = 0;
this.dx = 0;
this.dy = 0;
this.tx = 0;
this.ty = 0;
}
public void pause()
{
isRunning = false;
try
{
myThread.join();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
myThread = null;
}
public void resume ()
{
isRunning = true;
myThread = new Thread(this);
myThread.start();
}
#Override
public void run()
{
// TODO Auto-generated method stub
while(isRunning)
{
if(!myHolder.getSurface().isValid())
continue;
Canvas canvas = myHolder.lockCanvas();
canvas.drawRGB(02, 02, 254);
if(this.x != 0 && this.y != 0)
{
Bitmap test = BitmapFactory.decodeResource(getResources(), R.drawable.plus1);
canvas.drawBitmap(test, this.x - test.getWidth()/2 - this.tx, this.y - test.getHeight()/2 - this.ty, null);
this.tx += this.dx/30;
this.ty += this.dy/30;
}
myHolder.unlockCanvasAndPost(canvas);
}
}
}
This is the view, and this is the activity :
public class MyGraphicsSurface extends Activity implements OnTouchListener{
MyPachuSurface pachuSurf;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
pachuSurf = new MyPachuSurface(this);
pachuSurf.setOnTouchListener(this);
setContentView(pachuSurf);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
pachuSurf.resume();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
pachuSurf.resume();
}
#Override
public boolean onTouch(View v, MotionEvent event)
{
// TODO Auto-generated method stub
this.pachuSurf.x = event.getX();
this.pachuSurf.y = event.getY();
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
pachuSurf.startX = event.getX();
pachuSurf.startY = event.getY();
pachuSurf.tx = 0;
pachuSurf.ty = 0;
break;
case MotionEvent.ACTION_UP:
pachuSurf.finalX = event.getX();
pachuSurf.finalY = event.getY();
pachuSurf.dx = pachuSurf.finalX - pachuSurf.startX;
pachuSurf.dy = pachuSurf.finalY - pachuSurf.startY;
break;
}
return true;
}
}
And This is The Loc Cat:
06-06 17:37:20.104: E/AndroidRuntime(22781): FATAL EXCEPTION: Thread-29865
06-06 17:37:20.104: E/AndroidRuntime(22781): java.lang.NullPointerException
06-06 17:37:20.104: E/AndroidRuntime(22781): at com.example.myfirstapp.MyPachuSurface.run(MyPachuSurface.java:68)
06-06 17:37:20.104: E/AndroidRuntime(22781): at java.lang.Thread.run(Thread.java:856)
I had written a code to move a ball with the help of accelerometer in android such that if it touches any of 4 edges it reappears on opposide edge my problems are
1.ball is not reappearing on opposite edge
2.orientation changes to lanscape
here is my code
public class Accelerate extends Activity implements SensorEventListener {
float x, y, sensorX, sensorY, a, b, centerX, centerY;
Bitmap ball;
SensorManager sm;
NixSurface ourSurfaceView;
public class NixSurface extends SurfaceView implements Runnable {
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = false;
public NixSurface(Context context) {
super(context);
ourHolder = getHolder();
}
public void pause() {
isRunning = false;
while (true) {
try {
ourThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
ourThread = null;
}
public void resume() {
isRunning = true;
ourThread = new Thread(this);
ourThread.start();
}
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
if (!ourHolder.getSurface().isValid())
continue;
Canvas canvas = ourHolder.lockCanvas();
canvas.drawRGB(255, 255, 255);
centerX = canvas.getWidth() / 2;
centerY = canvas.getHeight() / 2;
x += sensorX;
y += sensorY;
a = centerX + x;
b = centerY + y;
if (a > canvas.getWidth())
a = 0;
if (b > canvas.getHeight())
b = 0;
if (a < 0)
a = canvas.getWidth();
if (b < 0)
b = canvas.getHeight();
canvas.drawBitmap(ball, a, b, null);
ourHolder.unlockCanvasAndPost(canvas);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sm.getSensorList(Sensor.TYPE_ACCELEROMETER).size() != 0) {
Sensor s = sm.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
sm.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL);
}
x = y = sensorY = sensorX = 0;
ball = BitmapFactory.decodeResource(getResources(), R.drawable.nix);
ourSurfaceView = new NixSurface(this);
ourSurfaceView.resume();
setContentView(ourSurfaceView);
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
sm.unregisterListener(this);
super.onStop();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
// nothing to do here
}
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
try {
Thread.sleep(16);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sensorX = -event.values[0];
sensorY = event.values[1];
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
I guess your problem is that you assume that the sensor origin (x=0,y=0) is the screen center. The sensor origin is the top left corner of the screen (X pointing left and Y pointing down), so comparing a & b to canvas.getWidth() & canvas.getHeight() is not correct since you already added centerX & centerY. Also, negating sensorX will cause the condition a > canvas.getWidth() to never occur since X is never negative.
I am working on application in which i want to display different text on image.when i touch the different position.I am working on the different image.In my program I have used one class to change the image and one class to draw a text on the image.
my activity class is as follow......
public class VideosActivity extends Activity implements OnTouchListener
{
//DrawView draw;
float a=0;
float b=0;
ImageView image;
MotionEvent event;
Button back ;
Button next;
TextView t;
String info = "";
int count =0;
FirstImage i;
ViewFlipper c;
Infoview v;
String huma="human";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.videos_layout);
i=new FirstImage(this);
c=(ViewFlipper) findViewById(R.id.viewFlipper1);
back = (Button) findViewById(R.id.button1);
next = (Button) findViewById(R.id.button2);
t=(TextView) findViewById(R.id.textView1);
if(count==0)
i.changeImage(R.drawable.human );
i.invalidate();
c.addView(i,0);
c.setOnTouchListener(this);
c.onTouchEvent(event);
}
public void pageinfo(float a,float b)
{
t.setText(Float.toString(a)+"x"+Float.toString(b)+"y");
i.display( a, b);
}
public boolean onTouch(View v, MotionEvent me)
{
// TODO Auto-generated method stub
switch(me.getAction())
{
case MotionEvent.ACTION_DOWN:
a=me.getX();
b= me.getY();
pageinfo(a,b);
break;
case MotionEvent.ACTION_MOVE:
a=me.getX();
b= me.getY();
pageinfo(a,b);
break;
case MotionEvent.ACTION_UP:
a=me.getX();
b= me.getY();
pageinfo(a,b);
break;
case MotionEvent.ACTION_OUTSIDE:
a=me.getX();
b= me.getY();
pageinfo(a,b);
break;
default: return false;
}
return true;
}
}
the class which is used to change the image is as follow...
public class FirstImage extends LinearLayout {
ImageView i;
int x;
Infoview v;
String huma ="human";
public FirstImage(Context context) {
super(context);
v=new Infoview(context);
i= new ImageView (context);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
addView(i, lp);
addView(v,lp);
}
public FirstImage(Context context, AttributeSet attrs) {
super(context, attrs);
}
protected void changeImage(int id){
i.setImageResource(id);
x=id;
}
public int getSrc() {
// TODO Auto-generated method stub
return x;
}
public void display(float a, float b) {
// TODO Auto-generated method stub
if(i.getId()==R.drawable.human){
v.updateInfo(huma, a, b);
i.invalidate();
v.invalidate();
}
}
}
class which is used for drawing text on the image is as follow..
public class Infoview extends View {
String info = "";
float x = 0; //init value
float y = 0; //init value
int color = Color.WHITE;
public Infoview(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public Infoview(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public Infoview(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setColor(color);
paint.setStrokeWidth(2);
paint.setTextSize(30);
canvas.drawLine(x-10, y, x+10, y, paint);
canvas.drawLine(x, y-10, x, y+10, paint);
canvas.drawText(info, x, y, paint);
}
public void updateInfo(String t_info, float t_x, float t_y){
info = t_info;
x = t_x;
y = t_y;
invalidate();
}
public void clearInfo(){
info = "";
x = 0;
y = 0;
invalidate();
}
I am not understanding why it is not displaying text on the image ......I think in the time of image drawing i am using one layout.so i have to include drawing class(Infoview) into that layout to...
If any one thinking that i am re asking this question then i am sorry ...
any help is appreciated...
I did get time to read the full code but if you override onDraw, you are not supposed to invoke super.onDraw() inside that method since that will mean that the base class will draw everything first.