aplication crash and take me this errors - android

I have the following problem. Applications crash and shows error sladnje, ideas are welcome
09-07 20:10:55.896: D/dalvikvm(1347): GC freed 782 objects / 55712 bytes in 109ms
09-07 20:10:56.066: D/dalvikvm(1347): GC freed 162 objects / 7192 bytes in 47ms
09-07 20:10:56.116: W/dalvikvm(1347): threadid=15: thread exiting with uncaught exception (group=0x4001b188)
09-07 20:10:56.126: E/AndroidRuntime(1347): Uncaught handler: thread Thread-9 exiting due to uncaught exception
09-07 20:10:56.126: E/AndroidRuntime(1347): java.lang.NullPointerException
09-07 20:10:56.126: E/AndroidRuntime(1347): at aa.bb.cc.Panel.onDraw(Panel.java:372)
09-07 20:10:56.126: E/AndroidRuntime(1347): at aa.bb.cc.TutorialThread.run(Panel.java:502)
09-07 20:10:56.146: I/dalvikvm(1347): threadid=7: reacting to signal 3
09-07 20:10:56.218: E/dalvikvm(1347): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
09-07 20:10:57.916: I/Process(1347): Sending signal. PID: 1347 SIG: 9
AndroidPaint.java
package aa.bb.cc;
public class AndroidPaint extends Activity {
static final int REQUEST_CODE = 1001;
public Shape currentGraphicObject;
public int ShapeObject_to_be_created;
public int ShapeLine = 1;
public int ShapeRect = 2;
public int ShapeCircle = 3;
public int ShapeOval = 4;
public int ShapeFreehand =5;
public int ShapeErase = 6;
public Paint mPaint;
public float BrushWidth;
public double[] color;
public Panel p;
public int number_of_graphicObjects;
public boolean shapemenuclicked;
public boolean colormenuclicked;
public boolean erasemenuclicked;
public boolean brushwidthmenuclicked;
public ArrayList<Shape> graphicobjects;
private Bitmap wallPaperBitmap;
static WallpaperManager wallpaperManager;
public int wallpaperHeight;
public int wallpaperWidth;
private String mImagePath = Environment.getExternalStorageDirectory() + "/androidpaint";
File file;
public Canvas bitmapCanvas;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
color = new double[3];
requestWindowFeature(Window.FEATURE_NO_TITLE);
graphicobjects = new ArrayList<Shape>();
currentGraphicObject = new Shape();
mPaint = new Paint();
InitializePaint();
shapemenuclicked = false;
colormenuclicked = false;
BrushWidth = 3;
Display display = getWindowManager().getDefaultDisplay();
wallpaperHeight = display.getHeight();
wallpaperWidth = display.getWidth();
wallPaperBitmap = Bitmap.createBitmap(wallpaperWidth, wallpaperHeight, Bitmap.Config.ARGB_8888);
bitmapCanvas = new Canvas(wallPaperBitmap);
}
public void onPause(){
super.onPause();
p.surfaceDestroyed(p.getHolder());
}
public void onStop(){
super.onStop();
p.surfaceDestroyed(p.getHolder());
/*graphicobjects.clear();
number_of_graphicObjects = 0;*/
}
public void onDestroy(){
super.onDestroy();
p.surfaceDestroyed(p.getHolder());
graphicobjects.clear();
number_of_graphicObjects = 0;
}
public void onResume(){
super.onResume();
}
public void onStart(){
super.onStart();
p = new Panel(this,null);
// setContentView(p/*new Panel(this)*/);
setContentView(R.layout.main);
p=(Panel)findViewById(R.id.yourID) ;
/* if (getLastNonConfigurationInstance() != null)
{
//GraphicObject = (Shape)getLastNonConfigurationInstance();
graphicobjects.set(number_of_graphicObjects-1, (Shape)getLastNonConfigurationInstance());
}
int n = graphicobjects.size();
if (getLastNonConfigurationInstance() != null)
{
//GraphicObject = (Shape)getLastNonConfigurationInstance();
//graphicobjects.set(number_of_graphicObjects-1, (Shape)getLastNonConfigurationInstance());
//graphicobjects.addAll((Shape)getLastNonConfigurationInstance());
Object[] temp = getLastNonConfigurationInstance();
for(int i = 0; i<n; i++){
graphicobjects.set(i,(Shape)getLastNonConfigurationInstance());
}
}*/
}
public void onSaveInstanceState(Bundle savedInstanceState){
//savedInstanceState.p
}
public void onRestoreInstanceState(Bundle savedInstanceState){
}
//test
/* public Object onRetainNonConfigurationInstance()
{
// if (GraphicObject != null) // Check that the object exists
//return(GraphicObject);
//if(!graphicobjects.isEmpty())
return graphicobjects.toArray();//.get(number_of_graphicObjects-1);
// return super.onRetainNonConfigurationInstance();
}*/
private void InitializePaint()
{
mPaint.setDither(true);
mPaint.setColor(Color.rgb(100, 100,100));
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(BrushWidth);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.itemLine:
ShapeObject_to_be_created = ShapeLine;
//GraphicObject = new Line();
shapemenuclicked = true;
erasemenuclicked = false;
brushwidthmenuclicked = false;
return true;
case R.id.itemFreehand:
ShapeObject_to_be_created = ShapeFreehand;
//GraphicObject = new FreeHand();
shapemenuclicked = true;
erasemenuclicked = false;
brushwidthmenuclicked = false;
return true;
case R.id.itemRectangle:
ShapeObject_to_be_created = ShapeRect;
//GraphicObject = new Rectangle();
shapemenuclicked = true;
erasemenuclicked = false;
brushwidthmenuclicked = false;
return true;
case R.id.itemCircle:
ShapeObject_to_be_created = ShapeCircle;
//GraphicObject = new Circle();
shapemenuclicked = true;
erasemenuclicked = false;
brushwidthmenuclicked = false;
return true;
case R.id.itemOval:
ShapeObject_to_be_created = ShapeOval;
//GraphicObject = new Oval();
shapemenuclicked = true;
erasemenuclicked = false;
brushwidthmenuclicked = false;
return true;
case R.id.itemColor:
LaunchColorPicker();
colormenuclicked = true;
erasemenuclicked = false;
brushwidthmenuclicked = false;
return true;
case R.id.itemErase:
ShapeObject_to_be_created = ShapeErase;
//GraphicObject = new Erase();
erasemenuclicked = true;
shapemenuclicked = false;
colormenuclicked = false;
brushwidthmenuclicked = false;
//BrushWidth = 8;
return true;
case R.id.itemBrushWidth3:
BrushWidth = 3;
brushwidthmenuclicked = true;
return true;
case R.id.itemBrushWidth4:
BrushWidth = 6;
brushwidthmenuclicked = true;
return true;
case R.id.itemBrushWidth5:
BrushWidth =9;
brushwidthmenuclicked = true;
return true;
case R.id.itemBrushWidth6:
BrushWidth = 12;
brushwidthmenuclicked = true;
return true;
case R.id.itemSetWallPaper:
//wallPaperBitmap = Bitmap.createBitmap(p.getWidth(),p.getHeight(),Bitmap.Config.ARGB_8888);
//Bitmap temp = p.getDrawingCache(true);
//wallPaperBitmap = Bitmap.createBitmap(temp);
//Canv
//Canvas canvas = p.getHolder().lockCanvas();
//p.getHolder().lockCanvas().drawBitmap(wallPaperBitmap, 0,0, mPaint);
//p.draw(canvas);
//try{
//getApplicationContext().setWallpaper(wallPaperBitmap);
//}
//catch(IOException e){
//e.printStackTrace();
//}
//p.saveScreenshot();
//wallPaperBitmap = Bitmap.createBitmap(this.p.getWidth(), this.p.getHeight(), Bitmap.Config.ARGB_8888);
//File file = new File(mScreenshotPath + "/" + "screeshot.jpg");
/*try{
FileInputStream fIS = new FileInputStream(file);
//wallPaperBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fIS);
fIS.close();
} catch (FileNotFoundException e) {
Log.e("Panel", "FileNotFoundException", e);
} catch (IOException e) {
Log.e("Panel", "IOEception", e);
}*/
return true;
case R.id.itemSaveImage:
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter= new SimpleDateFormat("yyyyMMMddHmmss");
String dateNow = formatter.format(currentDate.getTime());
file = new File(mImagePath + "/" + dateNow +".9.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
wallPaperBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.e("Panel", "FileNotFoundException", e);
}
catch (IOException e) {
Log.e("Panel", "IOEception", e);
}
}
return false;
}
private void LaunchColorPicker(){
Intent launchcolorpicker = new Intent();
launchcolorpicker.setClassName("somitsolutions.training.android.colorpicker", "somitsolutions.training.android.colorpicker.ColorPicker");
launchcolorpicker.setAction("somitsolutions.training.android.colorpicker.android.intent.action.COLORPICKER");
launchcolorpicker.addCategory("CATEGORY_DEFAULT");
launchcolorpicker.setType("vnd.somitsolutions.color/vnd.somitsolutions.color-value");
try {
startActivityForResult(launchcolorpicker,REQUEST_CODE);
}
catch(ActivityNotFoundException e){
Log.e("IntentExample", "Activity could not be started...");
}
}
public void onActivityResult(int requestcode, int resultcode, Intent result ) {
if(requestcode == REQUEST_CODE){
if(resultcode == RESULT_OK){
color[0] = (result.getDoubleArrayExtra("somitsolutions.training.android.colorpicker.color_of_the_shape"))[0];
color[1] = (result.getDoubleArrayExtra("somitsolutions.training.android.colorpicker.color_of_the_shape"))[1];
color[2] = (result.getDoubleArrayExtra("somitsolutions.training.android.colorpicker.color_of_the_shape"))[2];
//mPaint.setColor(Color.rgb((int)color[0], (int)color[1],(int)color[2]));
//GraphicObject.setPaintColor((int)color[0], (int)color[1],(int)color[2]);
//test
//onStart();
}
}
}}
Palete.java
package aa.bb.cc;
public class Panel extends SurfaceView implements Callback {
private Shape currentGraphicObject;
AndroidPaint a;
public Panel(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
getHolder().addCallback(this);
_thread = new TutorialThread(getHolder(), this);
setFocusable(true);
Bitmap.createBitmap(this.getWidth(),this.getHeight(),Bitmap.Config.ARGB_8888);
setDrawingCacheEnabled(true);
}
public Panel(Context context) {
super(context);
getHolder().addCallback(this);
_thread = new TutorialThread(getHolder(), this);
setFocusable(true);
Bitmap.createBitmap(this.getWidth(),this.getHeight(),Bitmap.Config.ARGB_8888);
setDrawingCacheEnabled(true);
}
public ArrayList<Shape> getGraphicObjects(){
return a.graphicobjects;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//if(shapemenuclicked == true && erasemenuclicked == false){
synchronized (_thread.getSurfaceHolder()) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
if(a.shapemenuclicked == true && a.erasemenuclicked == false){
//if(GraphicObject instanceof Line){
if(a.ShapeObject_to_be_created == a.ShapeLine){
currentGraphicObject = new Line();
((Line) currentGraphicObject).getBegin().setX(event.getX());
//((Line)(GraphicObject).getBegin().setX(event.getX()));//.setX(event.getX());
//begin.setY(event.getY());
((Line) currentGraphicObject).getBegin().setY(event.getY());
}
//if(GraphicObject instanceof FreeHand){
if(a.ShapeObject_to_be_created == a.ShapeFreehand){
currentGraphicObject = new FreeHand();
((FreeHand)currentGraphicObject).getPath().moveTo(event.getX(), event.getY());
((FreeHand)currentGraphicObject).getPath().lineTo(event.getX(), event.getY());
}
if(a.ShapeObject_to_be_created == a.ShapeRect){
currentGraphicObject = new Rectangle();
Point temp = new Point(event.getX(), event.getY());
((Rectangle) currentGraphicObject).settemppointOfOneEndRectangle(temp);
}
if(a.ShapeObject_to_be_created == a.ShapeCircle){
currentGraphicObject = new Circle();
((Circle)currentGraphicObject).getOneEndOfTheCircle().setX(event.getX());
((Circle)currentGraphicObject).getOneEndOfTheCircle().setY(event.getY());
}
if(a.ShapeObject_to_be_created == a.ShapeOval){
currentGraphicObject = new Oval();
((Oval)currentGraphicObject).getoneEndOfTheOval().setX(event.getX());
((Oval)currentGraphicObject).getoneEndOfTheOval().setY(event.getY());
}
}
if(a.shapemenuclicked == false && a.erasemenuclicked == true){
if(a.ShapeObject_to_be_created == a.ShapeErase){
currentGraphicObject = new Erase();
((Erase)currentGraphicObject).getPath().moveTo(event.getX(), event.getY());
((Erase)currentGraphicObject).getPath().lineTo(event.getX(), event.getY());
}
}
}
else if(event.getAction() == MotionEvent.ACTION_MOVE){
if(a.shapemenuclicked == true && a.erasemenuclicked == false){
if(a.ShapeObject_to_be_created == a.ShapeFreehand){
((FreeHand)currentGraphicObject).getPath().lineTo(event.getX(), event.getY());
}
if(a.ShapeObject_to_be_created == a.ShapeLine){
}
if(a.ShapeObject_to_be_created == a.ShapeRect){
}
if(a.ShapeObject_to_be_created == a.ShapeCircle){
}
if(a.ShapeObject_to_be_created == a.ShapeOval){
}
}
if(a.shapemenuclicked == false && a.erasemenuclicked == true){
if(a.ShapeObject_to_be_created == a.ShapeErase){
((Erase)currentGraphicObject).getPath().lineTo(event.getX(), event.getY());
}
}
else if(event.getAction() == MotionEvent.ACTION_UP){
if(a.shapemenuclicked == true && a.erasemenuclicked == false){
//if(GraphicObject instanceof Line){
if(a.ShapeObject_to_be_created == a.ShapeLine){
((Line) currentGraphicObject).getEnd().setX(event.getX());
((Line) currentGraphicObject).getEnd().setY(event.getY());
Point temp_begin = ((Line)currentGraphicObject).getBegin();
Point temp_end = ((Line)currentGraphicObject).getEnd();
((Line) currentGraphicObject).setBegin(temp_begin);
((Line)currentGraphicObject).getPath().moveTo(temp_begin.getX(), temp_begin.getY());
((Line)currentGraphicObject).getPath().lineTo(temp_end.getX(), temp_end.getY());
//currentGraphicObject.setrgb((int)color[0],(int)color[1],(int)color[2]);
}
if(a.ShapeObject_to_be_created == a.ShapeFreehand){
((FreeHand)currentGraphicObject).getPath().lineTo(event.getX(), event.getY());
((FreeHand)currentGraphicObject).getGraphicsPath().add(((FreeHand)currentGraphicObject).getPath());
}
if(a.ShapeObject_to_be_created == a.ShapeRect){
float tempX = ((Rectangle) currentGraphicObject).gettemppointOfOneEndRectangle().getX();
float tempY = ((Rectangle) currentGraphicObject).gettemppointOfOneEndRectangle().getY();
float tempX1 = event.getX();
float tempY1 = event.getY();
if(tempX<tempX1 && tempY>tempY1){
((Rectangle)currentGraphicObject).getPath().addRect(tempX, tempY1, tempX1, tempY, Path.Direction.CW);
}
if(tempX<tempX1 && tempY<tempY1){
((Rectangle)currentGraphicObject).getPath().addRect(tempX, tempY, tempX1, tempY1, Path.Direction.CW);
}
if(tempX>tempX1 && tempY>tempY1){
((Rectangle)currentGraphicObject).getPath().addRect(tempX1, tempY1, tempX, tempY, Path.Direction.CW);
}
if(tempX>tempX1 && tempY<tempY1){
((Rectangle)currentGraphicObject).getPath().addRect(tempX1, tempY, tempX, tempY1, Path.Direction.CW);
}
}
//if(GraphicObject instanceof Circle){
if(a.ShapeObject_to_be_created == a.ShapeCircle){
float tempX1 = ((Circle)currentGraphicObject).getOneEndOfTheCircle().getX();
float tempY1 = ((Circle)currentGraphicObject).getOneEndOfTheCircle().getY();
float tempX2 = event.getX();
float tempY2 = event.getY();
double temp = Math.pow((tempX1-tempX2),2) + Math.pow((tempY1-tempY2),2);
float radius = (float)Math.sqrt(temp)/2;
((Circle)currentGraphicObject).getPath().addCircle((tempX1 + tempX2)/2,(tempY1 + tempY2)/2, radius, Path.Direction.CW);
(int)color[1],(int)color[2]);
}
if(a.ShapeObject_to_be_created == a.ShapeOval){
float tempX = ((Oval)currentGraphicObject).getoneEndOfTheOval().getX();
float tempY = ((Oval)currentGraphicObject).getoneEndOfTheOval().getY();
float tempX1 = event.getX();
float tempY1 = event.getY();
if(tempX<=tempX1 && tempY>=tempY1){
((Oval)currentGraphicObject).getRectangle().set(tempX,tempY1,tempX1,tempY);
}
if(tempX<=tempX1 && tempY<=tempY1){
((Oval)currentGraphicObject).getRectangle().set(tempX,tempY,tempX1,tempY1);
}
if(tempX>=tempX1 && tempY>=tempY1){
((Oval)currentGraphicObject).getRectangle().set(tempX1,tempY1,tempX,tempY);
}
if(tempX>=tempX1 && tempY<=tempY1){
((Oval)currentGraphicObject).getRectangle().set(tempX1,tempY,tempX,tempY1);
}
//RectF r = ((Oval)GraphicObject).getRectangle();
((Oval)currentGraphicObject).getPath().addOval(((Oval)currentGraphicObject).getRectangle(), Path.Direction.CW);
//((Oval)GraphicObject).getPath().addOval(r, Path.Direction.CW);
}
}
if(a.shapemenuclicked == false && a.erasemenuclicked == true){
//if(GraphicObject instanceof Erase){
if(a.ShapeObject_to_be_created == a.ShapeErase){
((Erase)currentGraphicObject).getPath().lineTo(event.getX(), event.getY());
((Erase)currentGraphicObject).getGraphicsPath().add(((Erase)currentGraphicObject).getPath());
}
}
if(a.colormenuclicked == false && a.shapemenuclicked == true){
currentGraphicObject.setrgb(100,100,100);
}
if(a.colormenuclicked == true && a.shapemenuclicked == true){
currentGraphicObject.setrgb((int)a.color[0],(int)a.color[1],(int)a.color[2]);
}
if(a.erasemenuclicked == true && a.colormenuclicked == false){
currentGraphicObject.setrgb(0,0,0);
//mPaint.setStrokeWidth(6);
}
if(a.brushwidthmenuclicked == true){// || erasemenuclicked == true){
currentGraphicObject.setStrokeWidth(a.BrushWidth);
}
a.graphicobjects.add(currentGraphicObject);
a.number_of_graphicObjects++;
}
/*if(colormenuclicked == false && shapemenuclicked == true){
currentGraphicObject.setrgb(100,100,100);
}
if(colormenuclicked == true && shapemenuclicked == true){
currentGraphicObject.setrgb((int)color[0],(int)color[1],(int)color[2]);
}
if(erasemenuclicked == true && colormenuclicked == false){
currentGraphicObject.setrgb(0,0,0);
//mPaint.setStrokeWidth(6);
}
if(brushwidthmenuclicked == true){// || erasemenuclicked == true){
currentGraphicObject.setStrokeWidth(BrushWidth);
}
graphicobjects.add(currentGraphicObject);
number_of_graphicObjects++;*/
}
return true;
}
#Override
public void onDraw(Canvas canvas) {
for(int i = 0; i<a.number_of_graphicObjects; i++){
Shape currentGraphicObject = a.graphicobjects.get(i);
a.mPaint.setColor(Color.rgb(currentGraphicObject.getrgb()[0], currentGraphicObject.getrgb()[1], currentGraphicObject.getrgb()[2]));
a.mPaint.setStrokeWidth(currentGraphicObject.getStrokeWidth());
if(currentGraphicObject instanceof FreeHand){
for (Path path : ((FreeHand)currentGraphicObject).getGraphicsPath()) {
canvas.drawPath(path,a.mPaint);
a.bitmapCanvas.drawPath(path,a.mPaint);
}
}
else if(currentGraphicObject instanceof Erase){
for (Path path : ((Erase)currentGraphicObject).getGraphicsPath()) {
canvas.drawPath(path, a.mPaint);
a.bitmapCanvas.drawPath(path, a.mPaint);
}
}
else{
canvas.drawPath(currentGraphicObject.getPath(),a.mPaint);
a.bitmapCanvas.drawPath(currentGraphicObject.getPath(),a.mPaint);
}
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
public void surfaceCreated(SurfaceHolder holder) {
_thread.setRunning(true);
_thread.start();
}
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
_thread.setRunning(false);
while (retry) {
try {
_thread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
class TutorialThread extends Thread {
private SurfaceHolder _surfaceHolder;
private Panel _panel;
private boolean _run = false;
public TutorialThread(SurfaceHolder surfaceHolder, Panel panel) {
_surfaceHolder = surfaceHolder;
_panel = panel;
}
public void setRunning(boolean run) {
_run = run;
}
public SurfaceHolder getSurfaceHolder() {
return _surfaceHolder;
}
#Override
public void run() {
Canvas c;
while (_run) {
c = null;
try {
c = _surfaceHolder.lockCanvas(null);
synchronized (_surfaceHolder) {
}
} finally {
if (c != null) {
_surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}

From what I see, your variable a is null and I can't see where he was initialized. So initialize it and the NullPointerException has gone.
One more thing. Your code is very extensive and declaring variables 'a' or 'b' and package names like 'aa.bb.cc' doesn't looks like a nice code. Programming is for humans to understand not machines ;)

Related

Image captured from camera shrink in size when displayed in ImageView using URL [duplicate]

This question already has answers here:
Capture Image from Camera and Display in Activity
(19 answers)
Closed 5 years ago.
I am new to android pls help me with it. Much appreciated. The problem is that, i get the image from camera, after it is being captured it will be display in the Imageview by getting captured image URL. however, when the image is display in the Imageview, the image is not of its actual size, it shrinks significantly. Could anyone help me with it, please.
The following is the code for cameraActivity:
public class CameraActivity extends AppCompatActivity {
Integer REQUEST_CAMERA =1, GALLERY_KITKAT_INTENT_CALLED=0;
public ImageView capturedPhoto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
SelectImage();
capturedPhoto = (ImageView) findViewById(R.id.cameraPhoto);
}
private void SelectImage()
{
final CharSequence[] items ={"Camera","Gallery","Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(CameraActivity.this);
builder.setTitle("Add Image");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (items[i].equals("Camera")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
//dispatchTakePictureIntent();
} else if (items[i].equals("Gallery")) {
Intent intent2 = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent2.addCategory(Intent.CATEGORY_OPENABLE);
intent2.setType("image/*");
startActivityForResult(intent2, GALLERY_KITKAT_INTENT_CALLED);
} else if (items[i].equals("Cancel")) {
dialogInterface.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode,int resultCode, Intent data)
{
super.onActivityResult(requestCode,resultCode,data);
if(resultCode == Activity.RESULT_OK && requestCode == REQUEST_CAMERA)
{
Bitmap image =(Bitmap) data.getExtras().get("data");
capturedPhoto.setImageBitmap(image);
//call to get uri from bitmap
Uri tempUri = getImageUri(getApplicationContext(),image);
//call to get actual path
//Toast.makeText(CameraActivity.this,"Here"+getRealPathFromURI(tempUri),Toast.LENGTH_SHORT).show();
GlobalVariables.filepath=getRealPathFromURI(tempUri);
setContentView(new SomeView(CameraActivity.this));
}
if (requestCode == GALLERY_KITKAT_INTENT_CALLED && resultCode == RESULT_OK && null != data )
{
if (requestCode == GALLERY_KITKAT_INTENT_CALLED) {
String filepath2 = "";
Uri originalUri = null;
originalUri = data.getData();
final int takeFlags = data.getFlags()
& (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Check for the freshest data.
getContentResolver().takePersistableUriPermission(originalUri,
takeFlags);
filepath2 = getPath(originalUri);
if (filepath2.toString() != null) {
// LoadPicture(filepath);
GlobalVariables.filepath = filepath2;
// cropImageView.setVisibility(View.VISIBLE);
setContentView(new SomeView(CameraActivity.this));
}
}
}
}
#SuppressLint("NewApi")
private String getPath(Uri uri) {
if (uri == null) {
return null;
}
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor;
if (Build.VERSION.SDK_INT > 19) {
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection,
sel, new String[]{id}, null);
} else {
cursor = getContentResolver().query(uri, projection, null, null,
null);
}
String path = null;
try {
int column_index = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
} catch (NullPointerException e) {
}
return path;
}
public Uri getImageUri(Context inContext, Bitmap image )
{
//ByteArrayOutputStream bytes = new ByteArrayOutputStream();
//thumbnail.compress(Bitmap.CompressFormat.JPEG,100,bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(),image,"title",null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri)
{
Cursor cursor = getContentResolver().query(uri,null,null,null,null);
cursor.moveToFirst();
int idx=cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
The following is the xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.mbdp.w.areametric.CameraActivity">
<ImageView
android:id="#+id/cameraPhoto"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
This is the code for SomeView class:
public class SomeView extends View implements View.OnTouchListener{
private Paint paint;
public static List<Point> points;
int DIST = 2;
boolean flgPathDraw = true;
String filepath = GlobalVariables.filepath;
Point mfirstpoint = null;
boolean bfirstpoint = false;
Point mlastpoint = null;
Bitmap bitmap = scaleToActualAspectRatio(rotateBitmap(filepath,
BitmapFactory.decodeFile(filepath)));
Context mContext;
public SomeView(Context c) {
super(c);
Toast.makeText(getContext(), "Crop the coin on image", Toast.LENGTH_LONG)
.show();
mContext = c;
setFocusable(true);
setFocusableInTouchMode(true);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setPathEffect(new DashPathEffect(new float[]{10, 20}, 0));
paint.setStrokeWidth(5);
paint.setColor(Color.WHITE);
this.setOnTouchListener(this);
points = new ArrayList<Point>();
bfirstpoint = false;
}
public SomeView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setFocusable(true);
setFocusableInTouchMode(true);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(2);
paint.setColor(Color.WHITE);
this.setOnTouchListener(this);
points = new ArrayList<Point>();
bfirstpoint = false;
}
public void onDraw(Canvas canvas) {
canvas.drawBitmap(bitmap, 0, 0, null);
Path path = new Path();
boolean first = true;
for (int i = 0; i < points.size(); i += 2) {
Point point = points.get(i);
if (first) {
first = false;
path.moveTo(point.x, point.y);
} else if (i < points.size() - 1) {
Point next = points.get(i + 1);
path.quadTo(point.x, point.y, next.x, next.y);
} else {
mlastpoint = points.get(i);
path.lineTo(point.x, point.y);
}
}
canvas.drawPath(path, paint);
}
public boolean onTouch(View view, MotionEvent event) {
Point point = new Point();
point.x = (int) event.getX();
point.y = (int) event.getY();
if (flgPathDraw) {
if (bfirstpoint) {
if (comparepoint(mfirstpoint, point)) {
// points.add(point);
points.add(mfirstpoint);
flgPathDraw = false;
showcropdialog();
} else {
points.add(point);
}
} else {
points.add(point);
}
if (!(bfirstpoint)) {
mfirstpoint = point;
bfirstpoint = true;
}
}
invalidate();
Log.e("Hi ==>", "Size: " + point.x + " " + point.y);
if (event.getAction() == MotionEvent.ACTION_UP) {
Log.d("Action up", "called");
mlastpoint = point;
if (flgPathDraw) {
if (points.size() > 12) {
if (!comparepoint(mfirstpoint, mlastpoint)) {
flgPathDraw = false;
points.add(mfirstpoint);
showcropdialog();
}
}
}
}
return true;
}
private boolean comparepoint(Point first, Point current) {
int left_range_x = (int) (current.x - 3);
int left_range_y = (int) (current.y - 3);
int right_range_x = (int) (current.x + 3);
int right_range_y = (int) (current.y + 3);
if ((left_range_x < first.x && first.x < right_range_x)
&& (left_range_y < first.y && first.y < right_range_y)) {
if (points.size() < 10) {
return false;
} else {
return true;
}
} else {
return false;
}
}
public void resetView() {
points.clear();
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
flgPathDraw = true;
invalidate();
}
public Bitmap scaleToActualAspectRatio(Bitmap bitmap) {
if (bitmap != null) {
boolean flag = true;
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
int deviceWidth = metrics.widthPixels;
int deviceHeight = metrics.heightPixels;
Matrix matrix = new Matrix();
matrix.postRotate(90);
int bitmapHeight = bitmap.getHeight(); // 563
int bitmapWidth = bitmap.getWidth(); // 900
// aSCPECT rATIO IS Always WIDTH x HEIGHT rEMEMMBER 1024 x 768
if (bitmapWidth > deviceWidth) {
flag = false;
// scale According to WIDTH
int scaledWidth = deviceWidth;
int scaledHeight = (scaledWidth * bitmapHeight) / bitmapWidth;
try {
if (scaledHeight > deviceHeight)
scaledHeight = deviceHeight;
bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth,
scaledHeight, true);
} catch (Exception e) {
e.printStackTrace();
}
}
if (flag) {
if (bitmapHeight > deviceHeight) {
// scale According to HEIGHT
int scaledHeight = deviceHeight;
int scaledWidth = (scaledHeight * bitmapWidth)
/ bitmapHeight;
try {
if (scaledWidth > deviceWidth)
scaledWidth = deviceWidth;
bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth,
scaledHeight, true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return bitmap;
}
private void showcropdialog() {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent;
switch (which) {
case DialogInterface.BUTTON_NEUTRAL:
resetView();
break;
case DialogInterface.BUTTON_POSITIVE:
// Yes button clicked
// bfirstpoint = false;
intent = new Intent(mContext, CropActivity.class);
intent.putExtra("crop", true);
mContext.startActivity(intent);
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
intent = new Intent(mContext, CropActivity.class);
intent.putExtra("crop", false);
mContext.startActivity(intent);
bfirstpoint = false;
// resetView();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage("Please select Crop or Inverse crop")
.setNeutralButton("Re-Crop", dialogClickListener)
.setPositiveButton("Crop", dialogClickListener)
.setNegativeButton("Inverse Crop", dialogClickListener).show()
.setCancelable(false);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Ask the user if they want to quit
// restart app
Intent i = getContext().getPackageManager()
.getLaunchIntentForPackage(getContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActionMode(i);
SomeView.this.getContext().startActivity(i);
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
public static Bitmap rotateBitmap(String src, Bitmap bitmap) {
try {
int orientation = getExifOrientation(src);
if (orientation == 1) {
return bitmap;
}
Matrix matrix = new Matrix();
switch (orientation) {
case 2:
matrix.setScale(-1, 1);
break;
case 3:
matrix.setRotate(180);
break;
case 4:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case 5:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case 6:
matrix.setRotate(90);
break;
case 7:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case 8:
matrix.setRotate(-90);
break;
default:
return bitmap;
}
try {
Bitmap oriented = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return oriented;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return bitmap;
}
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
private static int getExifOrientation(String src) throws IOException {
int orientation = 1;
try {
if (Build.VERSION.SDK_INT >= 5) {
Class<?> exifClass = Class
.forName("android.media.ExifInterface");
Constructor<?> exifConstructor = exifClass
.getConstructor(new Class[]{String.class});
Object exifInstance = exifConstructor
.newInstance(new Object[]{src});
Method getAttributeInt = exifClass.getMethod("getAttributeInt",
new Class[]{String.class, int.class});
Field tagOrientationField = exifClass
.getField("TAG_ORIENTATION");
String tagOrientation = (String) tagOrientationField.get(null);
orientation = (Integer) getAttributeInt.invoke(exifInstance,
new Object[]{tagOrientation, 1});
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return orientation;
}
}
Links to image of what happened:
Actual image on camera
Displayed image in ImageView gets shrink
That small image from camera indicates thumbnail since you use reading bitmap from extra..
This example will help you get full image:  
How to capture an image and store it with the native Android Camera

Want to apply pinch and zoom to GLSurfaceView(3d Object)

I am using rajawali library for loading .obj file.
My .obj rendering perfectly fine but not able to apply pinch and zoom functionality to it.
Have solved using ScaleGestureDetector.
Following is the sample code:
public class MainActivity extends RajawaliExampleActivity implements OnTouchListener, OnObjectPick {// ,
// BackfromTemple
// {
private RajawaliLoadModelRenderer mRenderer;
private float mPreviousX;
// private float mPreviousY;
private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
private ScaleGestureDetector mScaleDetector;
private boolean isRotationStarted;
private boolean firsttime = false;
private Camera cam;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRenderer = new RajawaliLoadModelRenderer(this);
mRenderer.setSurfaceView(mSurfaceView);
super.setRenderer(mRenderer);
mSurfaceView.setOnTouchListener(this);
initLoader();
mScaleDetector = new ScaleGestureDetector(getBaseContext(), mRenderer);
firsttime = false;
cam = mRenderer.getCamera();
mSurfaceView.setPreserveEGLContextOnPause(true);
}
void showProgressDialog(final Context c, final String msg) {
runOnUiThread(new Runnable() {
#Override
public void run() {
pd = new ProgressDialog(c);
pd.setMessage(msg);
pd.setCancelable(false);
pd.setIndeterminate(true);
if (!pd.isShowing()) {
pd.show();
}
}
});
}
protected void hideProgressDialog() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (pd != null && pd.isShowing()) {
pd.dismiss();
}
}
});
}
#Override
protected void onRestart() {
super.onRestart();
firsttime = true;
isRotationStarted = false;
mRenderer.mPickedObject = null;
runOnUiThread(new Runnable() {
#Override
public void run() {
if (SuperActivity.pd != null && SuperActivity.pd.isShowing()) {
SuperActivity.pd.dismiss();
}
}
});
}
#Override
public boolean onTouchEvent(MotionEvent e) {
mScaleDetector.onTouchEvent(e);
float x = e.getX();
float y = e.getY();
if (e.getAction() == MotionEvent.ACTION_MOVE) {
float dx = x - mPreviousX;
// float dy = y - mPreviousY;
if (Math.abs(dx) > 2.5) {
isRotationStarted = true;
mRenderer.mObjectGroup.getRotation().y -= dx * TOUCH_SCALE_FACTOR;
}
// else if (Math.abs(dy) > 2.5) {
// isRotationStarted = true;
// mRenderer.mObjectGroup.getRotation().x -= dy *
// TOUCH_SCALE_FACTOR;
// }
}
mPreviousX = x;
return false;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
mScaleDetector.onTouchEvent(event);
float x = event.getX();
// float y = event.getY();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mRenderer.getObjectAt(event.getX(), event.getY());
// if (mRenderer.isObjectPicked) {
// showProgressDialog();
// }
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
// if (mRenderer.isObjectPicked) {
float dx = x - mPreviousX;
// float dy = y - mPreviousY;
if (Math.abs(dx) > 2.5 && mRenderer.mObjectGroup != null) {
isRotationStarted = true;
mRenderer.mObjectGroup.getRotation().y -= dx * TOUCH_SCALE_FACTOR;
}
// else if (Math.abs(dy) > 2.5 && mRenderer.mObjectGroup != null) {
// isRotationStarted = true;
// mRenderer.mObjectGroup.getRotation().x -= dy *
// TOUCH_SCALE_FACTOR;
// }
// }
} else if (event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_UP) {
isRotationStarted = false;
mRenderer.mPickedObject = null;
// runOnUiThread(new Runnable() {
// #Override
// public void run() {
// if (!mRenderer.isObjectPicked) {
// hideProgressDialog();
// isRotationStarted = false;
// mRenderer.isObjectPicked = false;
// mRenderer.mPickedObject = null;
// }
// }
// });
}
mPreviousX = x;
// mPreviousY = y;
return true;
}
#Override
public void objSelected(BaseObject3D object) {
final Intent i = new Intent(this, newactivity.class);
String objName = object.getName();
isRotationStarted = false;
mRenderer.mPickedObject = null;
startActivity(i);
}}
Easy way to achieve it by using ArcballCamera
ArcballCamera arcball = new ArcballCamera(mContext, ((Activity)mContext).findViewById(R.id.linear_layout));
arcball.setTarget(object3D); //your 3D Object
arcball.setPosition(0,0,4); //optional
//arcball.setScreenMappingRatio(-1); // Not yet merged at master branch as of now
getCurrentScene().replaceAndSwitchCamera(getCurrentCamera(), arcball);

ontouch method is null pointer exception my application touch in start button

class is RadarSceen then method ontouch method is crash is null pointer exception and this method use start radar and stop radar.then localRotateAnimation.setDuration(3000L) crash is null pointer exception
public class RadarScreen extends Activity implements View.OnTouchListener {
private static final String APP_TAG = "com.example.ghostsam";
private CountDownTimer countdownHideGhost = null;
private CountDownTimer countdownShowGhost = null;
private DisplayMetrics getDisplay = new DisplayMetrics();
private int getDisplayHeight;
private float getDisplayScale;
private int getDisplayWidth;
private Boolean hideGhosts = Boolean.valueOf(false);
private ImageView ivLogo = null;
private ImageView ivRadar = null;
private ImageView ivRadarGhosts = null;
private ImageView ivSignalButton = null;
private Typeface layoutFontFace;
private Boolean radarRun = Boolean.valueOf(false);
// private RotateAnimation rotateAnimation ;
private RotateAnimation localRotateAnimation;
private boolean settingsGeneralVibrate = true;
private Boolean showGhosts = Boolean.valueOf(false);
private int showGhostsZufallszahl = 0;
private Vibrator vib = null;
public Bitmap drawButton(String paramString1, String paramString2) {
Bitmap localBitmap = Bitmap
.createBitmap(this.getDisplayWidth - (int) (70.0F * this.getDisplayScale),
(int) (52.0F * this.getDisplayScale), Bitmap.Config.ARGB_8888);
Canvas localCanvas = new Canvas(localBitmap);
Paint localPaint = new Paint();
localPaint.setTypeface(this.layoutFontFace);
localPaint.setTextAlign(Paint.Align.CENTER);
localPaint.setAntiAlias(true);
localPaint.setColor(Color.parseColor(paramString2));
localCanvas.drawRoundRect(
new RectF(0.0F, 0.0F, localBitmap.getWidth(), localBitmap.getHeight()), 12.0F,
12.0F, localPaint);
localPaint.setColor(Color.parseColor("#000000"));
localCanvas.drawRoundRect(new RectF(2.0F, 2.0F, -2 + localBitmap.getWidth(),
-2 + localBitmap.getHeight()), 12.0F, 12.0F, localPaint);
localPaint.setColor(Color.parseColor(paramString2));
localPaint.setAlpha(200);
localPaint.setTextSize(32.0F * this.getDisplayScale);
localPaint.setTextScaleX(1.75F);
localPaint.setFakeBoldText(true);
localCanvas.drawText(paramString1, localBitmap.getWidth() / 2,
36.0F * this.getDisplayScale, localPaint);
return localBitmap;
}
public Bitmap drawRadar(Boolean paramBoolean) {
Bitmap localBitmap = Bitmap
.createBitmap(-50 + this.getDisplayWidth, -50 + this.getDisplayWidth,
Bitmap.Config.ARGB_8888);
Canvas localCanvas = new Canvas(localBitmap);
Paint localPaint = new Paint();
int i = (int) ((localBitmap.getWidth() - 10.0F * this.getDisplayScale) / 2.0F
+ 5.0F * this.getDisplayScale);
int j = (int) (i - 5.0F * this.getDisplayScale);
localPaint.setAntiAlias(true);
localPaint.setColor(Color.parseColor("#FFFFFF"));
localPaint.setStyle(Paint.Style.STROKE);
localPaint.setStrokeWidth(3.0F * this.getDisplayScale);
localPaint.setAlpha(75);
for (int k = 0; ; k++) {
if (k > 4) {
localPaint.setAlpha(100);
localPaint.setStyle(Paint.Style.FILL);
localPaint.setShader(new SweepGradient(i, i, 0, -16711936));
if (paramBoolean.booleanValue()) {
RectF localRectF = new RectF();
localRectF.set(i - j, i - j, i + j, i + j);
localCanvas.drawArc(localRectF, 0.0F, 360.0F, true, localPaint);
}
localPaint.setShader(null);
localPaint.setAlpha(255);
localPaint.setColor(Color.parseColor("#810003"));
localPaint.setStyle(Paint.Style.FILL);
localPaint.setStrokeWidth(0.0F);
localCanvas.drawCircle(i, i, 10.0F * this.getDisplayScale, localPaint);
return localBitmap;
}
localCanvas.drawCircle(i, i, j - k * 40 * this.getDisplayScale, localPaint);
}
}
public Bitmap drawRadarGhosts(Boolean paramBoolean) {
Bitmap localBitmap = Bitmap
.createBitmap(-50 + this.getDisplayWidth, -50 + this.getDisplayWidth,
Bitmap.Config.ARGB_8888);
Canvas localCanvas = new Canvas(localBitmap);
Paint localPaint = new Paint();
if (paramBoolean.booleanValue()) {
int i = (int) ((localBitmap.getWidth() - 10.0F * this.getDisplayScale) / 2.0F
+ 5.0F * this.getDisplayScale);
int j = (int) (i - 5.0F * this.getDisplayScale);
localPaint.setAntiAlias(true);
localPaint.setAlpha(255);
Random localRandom = new Random();
localPaint.setAlpha(150);
int k = localRandom.nextInt(180);
int m = localRandom.nextInt(j);
int n = i + (int) (Math.cos(3.141592653589793D * k / 180.0D) * m);
int i1 = i + (int) (Math.sin(3.141592653589793D * k / 180.0D) * m);
localPaint.setColor(-16711936);
localPaint.setShader(
new RadialGradient(n, i1, 22.0F * this.getDisplayScale, -16711936, 0,
TileMode.CLAMP));
localCanvas.drawCircle(n, i1, 15.0F * this.getDisplayScale, localPaint);
if (localRandom.nextInt(50) < 5) {
int i6 = localRandom.nextInt(180);
int i7 = localRandom.nextInt(j);
int i8 = i + (int) (Math.cos(3.141592653589793D * i6 / 180.0D) * i7);
int i9 = i + (int) (Math.sin(3.141592653589793D * i6 / 180.0D) * i7);
localPaint.setShader(
new RadialGradient(i8, i9, 22.0F * this.getDisplayScale, -16711936, 0,
TileMode.CLAMP));
localCanvas.drawCircle(i8, i9, 15.0F * this.getDisplayScale, localPaint);
}
if (localRandom.nextInt(75) < 5) {
int i2 = localRandom.nextInt(180);
int i3 = localRandom.nextInt(j);
int i4 = i + (int) (Math.cos(3.141592653589793D * i2 / 180.0D) * i3);
int i5 = i + (int) (Math.sin(3.141592653589793D * i2 / 180.0D) * i3);
localPaint.setShader(
new RadialGradient(i4, i5, 22.0F * this.getDisplayScale, -16711936, 0,
TileMode.CLAMP));
localCanvas.drawCircle(i4, i5, 15.0F * this.getDisplayScale, localPaint);
}
}
return localBitmap;
}
public void onCreate(Bundle paramBundle) {
Log.i("com.example.ghostsam", "onStart RadarScreen");
requestWindowFeature(1);
getWindow().setFlags(1024, 1024);
super.onCreate(paramBundle);
setContentView(R.layout.radarscreen);
SharedPreferences localSharedPreferences = getSharedPreferences("app_prefs", 0);
int i = localSharedPreferences.getInt("appStartCounter", 0);
int j = localSharedPreferences.getInt("appStartFirst", 0);
int k = i + 1;
SharedPreferences.Editor localEditor = localSharedPreferences.edit();
localEditor.putInt("appStartCounter", k);
if (j <= 0) {
localEditor.putInt("appStartFirst", (int) (System.currentTimeMillis() / 1000L));
}
localEditor.commit();
if ((k == 5) || (k == 10) || (k == 25)) {
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setIcon(17301543);
Resources localResources1 = getResources();
Object[] arrayOfObject1 = new Object[1];
arrayOfObject1[0] = "name";
localBuilder.setTitle(localResources1.getString(R.string.app_name, arrayOfObject1));
Resources localResources2 = getResources();
Object[] arrayOfObject2 = new Object[1];
arrayOfObject2[0] = "name";
localBuilder.setMessage(localResources2
.getString(R.string.dialog_ratemarket_question, arrayOfObject2));
Resources localResources3 = getResources();
Object[] arrayOfObject3 = new Object[1];
arrayOfObject3[0] = "name";
localBuilder.setPositiveButton(
localResources3.getString(R.string.dialog_button_yes, arrayOfObject3),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface paramDialogInterface,
int paramInt) {
Resources localResources = RadarScreen.this.getResources();
Object[] arrayOfObject = new Object[1];
arrayOfObject[0] = "name";
Intent localIntent = new Intent("android.intent.action.VIEW",
Uri.parse(localResources.getString(R.string.app_marketlink,
arrayOfObject)));
RadarScreen.this.startActivity(localIntent);
paramDialogInterface.dismiss();
}
});
Resources localResources4 = getResources();
Object[] arrayOfObject4 = new Object[1];
arrayOfObject4[0] = "name";
localBuilder.setNegativeButton(
localResources4.getString(R.string.dialog_button_no, arrayOfObject4),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface paramDialogInterface,
int paramInt) {
paramDialogInterface.dismiss();
}
});
localBuilder.create().show();
}
}
public boolean onCreateOptionsMenu(Menu paramMenu) {
getMenuInflater().inflate(R.menu.radarscreen, paramMenu);
return true;
}
public void onError(Exception paramException) {
}
public void onIllegalHttpStatusCode(int paramInt, String paramString) {
}
public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent) {
if (paramInt == 4) {
quitApp();
}
for (int i = 1; ; i = 0) {
return true;
}
}
#SuppressLint("NewApi")
public boolean onOptionsItemSelected(MenuItem paramMenuItem) {
switch (paramMenuItem.getItemId()) {
default:
break;
case R.id.radarscreen_menu_moreapps:
Resources localResources2 = getResources();
Object[] arrayOfObject2 = new Object[1];
arrayOfObject2[0] = "name";
startActivity(new Intent("android.intent.action.VIEW", Uri.parse(localResources2
.getString(R.string.app_marketdeveloperlink, arrayOfObject2))));
break;
case R.id.radarscreen_menu_rateapp:
Resources localResources1 = getResources();
Object[] arrayOfObject1 = new Object[1];
arrayOfObject1[0] = "name";
startActivity(new Intent("android.intent.action.VIEW", Uri.parse(
localResources1.getString(R.string.app_marketlink, arrayOfObject1))));
break;
case R.id.radarscreen_menu_about:
startActivity(new Intent(this, About.class));
break;
case R.id.radarscreen_menu_settings:
startActivity(new Intent(this, Settings.class));
break;
case R.id.radarscreen_menu_quit:
quitApp();
}
return true;
}
public void onResume() {
super.onResume();
Log.i("com.example.ghostsam", "onResume RadarScreen");
getWindowManager().getDefaultDisplay().getMetrics(this.getDisplay);
this.getDisplayWidth = this.getDisplay.widthPixels;
this.getDisplayHeight = this.getDisplay.heightPixels;
this.getDisplayScale = (this.getDisplayWidth / 480.0F);
this.layoutFontFace = Typeface.createFromAsset(getAssets(), "Roboto-Regular.ttf");
this.settingsGeneralVibrate = PreferenceManager
.getDefaultSharedPreferences(getBaseContext())
.getBoolean("settings_general_vibrate", true);
this.vib = ((Vibrator) getSystemService("vibrator"));
this.ivLogo = ((ImageView) findViewById(R.id.ivLogo));
this.ivLogo.setImageBitmap(Bitmap.createScaledBitmap(
BitmapFactory.decodeResource(getResources(), R.drawable.logo),
(int) (460.0F * this.getDisplayScale), (int) (68.0F * this.getDisplayScale),
true));
this.ivSignalButton = ((ImageView) findViewById(R.id.ivSignalButton));
this.ivSignalButton.setImageBitmap(drawButton("start radar", "#005F21"));
this.ivSignalButton.setOnTouchListener(this);
this.ivRadar = ((ImageView) findViewById(R.id.ivRadar));
this.ivRadar.setImageBitmap(drawRadar(Boolean.valueOf(false)));
this.ivRadarGhosts = ((ImageView) findViewById(R.id.ivRadarGhosts));
if (this.ivRadarGhosts != null) {
this.ivRadarGhosts.setImageBitmap(drawRadarGhosts(Boolean.valueOf(false)));
}
this.countdownShowGhost = new CountDownTimer(15000L, 1000L) {
public void onFinish() {
RadarScreen.this.showGhosts = Boolean.valueOf(false);
RadarScreen.this.hideGhosts = Boolean.valueOf(false);
if (RadarScreen.this.countdownHideGhost != null) {
RadarScreen.this.countdownHideGhost.start();
}
}
public void onTick(long paramLong) {
Random localRandom = new Random();
if (!RadarScreen.this.showGhosts.booleanValue()) {
RadarScreen.this.showGhosts = Boolean.valueOf(true);
RadarScreen.this.showGhostsZufallszahl = (1000 + localRandom
.nextInt(10000));
if (localRandom.nextInt(50) >= 10) {
AlphaAnimation localAlphaAnimation2 = new AlphaAnimation(0.0F, 0.975F);
localAlphaAnimation2.setDuration(1000L);
localAlphaAnimation2.setFillAfter(true);
if (RadarScreen.this.ivRadarGhosts != null) {
RadarScreen.this.ivRadarGhosts.startAnimation(localAlphaAnimation2);
RadarScreen.this.ivRadarGhosts.setImageBitmap(
RadarScreen.this.drawRadarGhosts(Boolean.valueOf(true)));
if (RadarScreen.this.settingsGeneralVibrate) {
RadarScreen.this.vib.vibrate(20L);
}
}
}
}
if ((RadarScreen.this.showGhostsZufallszahl > paramLong) && (!RadarScreen.this
.hideGhosts.booleanValue())) {
RadarScreen.this.hideGhosts = Boolean.valueOf(true);
AlphaAnimation localAlphaAnimation1 = new AlphaAnimation(0.975F, 0.0F);
localAlphaAnimation1.setDuration(1000L);
localAlphaAnimation1.setFillAfter(true);
if (RadarScreen.this.ivRadarGhosts == null) {
return;
}
RadarScreen.this.ivRadarGhosts.startAnimation(localAlphaAnimation1);
}
}
};
this.countdownHideGhost = new CountDownTimer(12500L, 2250L) {
public void onFinish() {
RadarScreen.this.showGhosts = Boolean.valueOf(false);
RadarScreen.this.hideGhosts = Boolean.valueOf(false);
if (RadarScreen.this.countdownShowGhost != null) {
RadarScreen.this.countdownShowGhost.start();
}
}
public void onTick(long paramLong) {
}
};
}
public void onStop() {
super.onStop();
Log.i("com.example.ghostsam", "onStop RadarScreen");
BitmapDrawable localBitmapDrawable1 = (BitmapDrawable) this.ivLogo.getDrawable();
this.ivLogo.setImageBitmap(null);
this.ivLogo.setImageDrawable(null);
this.ivLogo = null;
Bitmap localBitmap1 = localBitmapDrawable1.getBitmap();
if ((localBitmap1 != null) && (!localBitmap1.isRecycled()))
{
localBitmap1.recycle();
}
BitmapDrawable localBitmapDrawable2 = (BitmapDrawable) this.ivRadar.getDrawable();
this.ivRadar.setImageBitmap(null);
this.ivRadar.setImageDrawable(null);
this.ivRadar = null;
Bitmap localBitmap2 = localBitmapDrawable2.getBitmap();
if ((localBitmap2 != null) && (!localBitmap2.isRecycled()))
{
localBitmap2.recycle();
}
BitmapDrawable localBitmapDrawable3 = (BitmapDrawable) this.ivRadarGhosts.getDrawable();
this.ivRadarGhosts.setImageBitmap(null);
this.ivRadarGhosts.setImageDrawable(null);
this.ivRadarGhosts = null;
Bitmap localBitmap3 = localBitmapDrawable3.getBitmap();
if ((localBitmap3 != null) && (!localBitmap3.isRecycled()))
{
localBitmap3.recycle();
}
BitmapDrawable localBitmapDrawable4 = (BitmapDrawable) this.ivSignalButton
.getDrawable();
this.ivSignalButton.setImageBitmap(null);
this.ivSignalButton.setImageDrawable(null);
this.ivSignalButton = null;
Bitmap localBitmap4 = localBitmapDrawable4.getBitmap();
if ((localBitmap4 != null) && (!localBitmap4.isRecycled()))
{
localBitmap4.recycle();
}
this.countdownHideGhost.cancel();
this.countdownHideGhost = null;
this.countdownShowGhost.cancel();
this.countdownShowGhost = null;
this.radarRun = Boolean.valueOf(false);
this.showGhosts = Boolean.valueOf(false);
this.hideGhosts = Boolean.valueOf(false);
}
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
switch (paramMotionEvent.getAction()) {
default:
if (paramView != this.ivSignalButton) {
break;
}
case 0:
if (this.radarRun.booleanValue()) {
if (this.radarRun.booleanValue()) {
if (this.ivSignalButton == null) {
break;
}
this.ivSignalButton.setImageBitmap(drawButton("stop radar", "#1BA449"));
}
}
case 1:
if (this.ivSignalButton == null) {
break;
}
this.ivSignalButton.setImageBitmap(drawButton("start radar", "#1BA449"));
}
// while (paramView != this.ivSignalButton);
if (this.radarRun.booleanValue()) {
if (this.ivSignalButton != null) {
this.ivSignalButton.setImageBitmap(drawButton("stop radar", "#005F21"));
}
if ((paramMotionEvent.getX() <= 0.0F) || (paramMotionEvent.getX() >= paramView
.getWidth()) ||
(paramMotionEvent.getY() <= 0.0F) || (paramMotionEvent.getY() >= paramView
.getHeight())) {
this.ivSignalButton.setImageBitmap(drawButton("stop radar", "#005F21"));
}
if (this.ivSignalButton != null) {
this.ivSignalButton.setImageBitmap(drawButton("start radar", "#005F21"));
}
RotateAnimation localRotateAnimation = new RotateAnimation(0.0F, 360.0F, 1, 0.5F, 1,
0.5F);
localRotateAnimation.setInterpolator(new LinearInterpolator());
localRotateAnimation.setFillAfter(true);
localRotateAnimation.setRepeatMode(1);
if (!this.radarRun.booleanValue()) {
if (this.ivSignalButton != null) {
this.ivSignalButton.setImageBitmap(drawButton("stop radar", "#005F21"));
}
}
this.radarRun = Boolean.valueOf(true);
this.radarRun = Boolean.valueOf(false);
if (this.ivRadar != null) {
this.ivRadar.setImageBitmap(drawRadar(Boolean.valueOf(false)));
}
localRotateAnimation.setDuration(10L);
localRotateAnimation.setRepeatCount(0);
if (this.ivRadarGhosts != null) {
this.ivRadarGhosts.setImageBitmap(drawRadarGhosts(Boolean.valueOf(false)));
}
if (this.countdownHideGhost != null) {
this.countdownHideGhost.cancel();
}
if (this.countdownHideGhost != null) {
this.countdownShowGhost.cancel();
}
}
if (this.ivSignalButton == null) {
this.ivSignalButton.setImageBitmap(drawButton("start radar", "#005F21"));
}
if (this.ivRadar != null) {
this.ivRadar.setImageBitmap(drawRadar(Boolean.valueOf(true)));
}
localRotateAnimation.setDuration(3000L);
localRotateAnimation.setRepeatCount(-1);
if (this.countdownHideGhost == null) {
this.countdownHideGhost.start();
}
this.ivRadar.startAnimation(localRotateAnimation);
return true;
}
}
You have to problems here:
You defined a filed RotateAnimation localRotateAnimation but never assigned a value to it. That's why you get a NullPointerException.
You are using a local variable with the same name and assign it a value: RotateAnimation localRotateAnimation = new RotateAnimation(0.0F, 360.0F, 1, 0.5F, 1, 0.5F);. Most likly, you wanted to use the filed. So change that to just localRotateAnimation = new RotateAnimation(/*params*/);
I'm not sure if fixing 2. fixes 1. because I did not understand your logic. Maybe 2. gets called every time before you reach the code which throws the NPE now.
Maybe you need to assign a value somewhere else to.
Maybe this code block is what you want:
// moved up to run it even if condition is false
// and use field
localRotateAnimation = new RotateAnimation(0.0F, 360.0F, 1, 0.5F, 1, 0.5F);
if (this.radarRun.booleanValue()) {
if (this.ivSignalButton != null) {
this.ivSignalButton.setImageBitmap(drawButton("stop radar", "#005F21"));
}
if ((paramMotionEvent.getX() <= 0.0F) || (paramMotionEvent.getX() >= paramView
.getWidth()) ||
(paramMotionEvent.getY() <= 0.0F) || (paramMotionEvent.getY() >= paramView
.getHeight())) {
this.ivSignalButton.setImageBitmap(drawButton("stop radar", "#005F21"));
}
if (this.ivSignalButton != null) {
this.ivSignalButton.setImageBitmap(drawButton("start radar", "#005F21"));
}
localRotateAnimation.setInterpolator(new LinearInterpolator());
localRotateAnimation.setFillAfter(true);
localRotateAnimation.setRepeatMode(1);
if (!this.radarRun.booleanValue()) {
if (this.ivSignalButton != null) {
this.ivSignalButton.setImageBitmap(drawButton("stop radar", "#005F21"));
}
}
this.radarRun = Boolean.valueOf(true);
this.radarRun = Boolean.valueOf(false);
if (this.ivRadar != null) {
this.ivRadar.setImageBitmap(drawRadar(Boolean.valueOf(false)));
}
localRotateAnimation.setDuration(10L);
localRotateAnimation.setRepeatCount(0);
if (this.ivRadarGhosts != null) {
this.ivRadarGhosts.setImageBitmap(drawRadarGhosts(Boolean.valueOf(false)));
}
if (this.countdownHideGhost != null) {
this.countdownHideGhost.cancel();
}
if (this.countdownHideGhost != null) {
this.countdownShowGhost.cancel();
}
}
if (this.ivSignalButton == null) {
this.ivSignalButton.setImageBitmap(drawButton("start radar", "#005F21"));
}
if (this.ivRadar != null) {
this.ivRadar.setImageBitmap(drawRadar(Boolean.valueOf(true)));
}
localRotateAnimation.setDuration(3000L);
localRotateAnimation.setRepeatCount(-1);
if (this.countdownHideGhost == null) {
this.countdownHideGhost.start();
}
this.ivRadar.startAnimation(localRotateAnimation);

why jd-gui lost some info when decompile a .class file?

I have decompiled a class by jd-gui below, but I am unable to understand how the "linearLayout" is being initialized and why linearLayout.startAnimation(animationset) should be invoked, the LockScreen member "linearLayout" is not referred to any instance.
Can anybody tell me how this work? Is it possible for jd-gui lose something while decompilin a .class file ?
the decompiled file below:
// Referenced classes of package com.android.internal.policy.impl:
// KeyguardScreen, KeyguardStatusViewManager, DrawWaterWave, KeyguardUpdateMonitor,
// KeyguardScreenCallback
class LockScreen extends RelativeLayout
implements KeyguardScreen
{
class MultiWaveViewMethods
implements com.android.internal.widget.multiwaveview.MultiWaveView.OnTriggerListener, UnlockWidgetCommonMethods
{
private boolean mCameraDisabled;
private final MultiWaveView mMultiWaveView;
final LockScreen this$0;
public View getView()
{
return mMultiWaveView;
}
public void onGrabbed(View view, int i)
{
}
public void onGrabbedStateChange(View view, int i)
{
if (i != 0)
mCallback.pokeWakelock();
}
public void onReleased(View view, int i)
{
}
public void onTrigger(View view, int i)
{
if (i != 0 && i != 1) goto _L2; else goto _L1
_L1:
mCallback.goToUnlockScreen();
_L4:
return;
_L2:
if (i == 2 || i == 3)
if (!mCameraDisabled)
{
Intent intent = new Intent("android.intent.action.CAMERA_BUTTON", null);
mContext.sendOrderedBroadcast(intent, null);
mCallback.goToUnlockScreen();
} else
{
toggleRingMode();
mUnlockWidgetMethods.updateResources();
mCallback.pokeWakelock();
}
if (true) goto _L4; else goto _L3
_L3:
}
public void ping()
{
mMultiWaveView.ping();
}
public void reset(boolean flag)
{
mMultiWaveView.reset(flag);
}
public void updateResources()
{
int i;
if (mCameraDisabled)
{
if (mSilentMode)
i = 0x107000b;
else
i = 0x107000e;
} else
{
i = 0x1070010;
}
mMultiWaveView.setTargetResources(i);
}
MultiWaveViewMethods(MultiWaveView multiwaveview)
{
boolean flag = true;
this$0 = LockScreen.this;
super();
mMultiWaveView = multiwaveview;
if (mLockPatternUtils.getDevicePolicyManager().getCameraDisabled(null))
{
Log.v("LockScreen", "Camera disabled by Device Policy");
mCameraDisabled = flag;
} else
{
if (mMultiWaveView.getTargetResourceId() == 0x1070010)
flag = false;
mCameraDisabled = flag;
}
}
}
class SlidingTabMethods
implements com.android.internal.widget.SlidingTab.OnTriggerListener, UnlockWidgetCommonMethods
{
private final SlidingTab mSlidingTab;
final LockScreen this$0;
public View getView()
{
return mSlidingTab;
}
public void onGrabbedStateChange(View view, int i)
{
if (i == 2)
{
mSilentMode = isSilentMode();
SlidingTab slidingtab = mSlidingTab;
int j;
if (mSilentMode)
j = 0x104030b;
else
j = 0x104030c;
slidingtab.setRightHintText(j);
}
if (i != 0)
mCallback.pokeWakelock();
}
public void onTrigger(View view, int i)
{
if (i != 1) goto _L2; else goto _L1
_L1:
mCallback.goToUnlockScreen();
_L4:
return;
_L2:
if (i == 2)
{
toggleRingMode();
mCallback.pokeWakelock();
}
if (true) goto _L4; else goto _L3
_L3:
}
public void ping()
{
}
public void reset(boolean flag)
{
mSlidingTab.reset(flag);
}
public void updateResources()
{
int i = 1;
SlidingTab slidingtab;
int j;
int k;
int l;
int i1;
if (!mSilentMode || mAudioManager.getRingerMode() != i)
i = 0;
slidingtab = mSlidingTab;
if (mSilentMode)
{
if (i != 0)
j = 0x10802cc;
else
j = 0x10802c9;
} else
{
j = 0x10802ca;
}
if (mSilentMode)
k = 0x1080398;
else
k = 0x1080395;
if (mSilentMode)
l = 0x1080381;
else
l = 0x1080380;
if (mSilentMode)
i1 = 0x1080394;
else
i1 = 0x1080393;
slidingtab.setRightTabResources(j, k, l, i1);
}
SlidingTabMethods(SlidingTab slidingtab)
{
this$0 = LockScreen.this;
super();
mSlidingTab = slidingtab;
}
}
private static interface UnlockWidgetCommonMethods
{
public abstract View getView();
public abstract void ping();
public abstract void reset(boolean flag);
public abstract void updateResources();
}
class WaveViewMethods
implements com.android.internal.widget.WaveView.OnTriggerListener, UnlockWidgetCommonMethods
{
private final WaveView mWaveView;
final LockScreen this$0;
public View getView()
{
return mWaveView;
}
public void onGrabbedStateChange(View view, int i)
{
if (i == 10)
mCallback.pokeWakelock(30000);
}
public void onTrigger(View view, int i)
{
Log.i("LockScreen", (new StringBuilder()).append("onTrigger, whichHandle=").append(i).toString());
if (i == 10)
{
Log.i("LockScreen", "onTrigger, requestUnlockScreen");
requestUnlockScreen();
}
}
public void ping()
{
}
public void reset(boolean flag)
{
mWaveView.reset();
}
public void updateResources()
{
}
WaveViewMethods(WaveView waveview)
{
this$0 = LockScreen.this;
super();
mWaveView = waveview;
}
}
private static final boolean DBG = true;
private static final String ENABLE_MENU_KEY_FILE = "/data/local/enable_menu_key";
static final String LOCKSCREEN_WALLPAPER = "lockScreenWallpaper";
static final File LOCKSCREEN_WALLPAPER_DIR;
static final File LOCKSCREEN_WALLPAPER_FILE;
private static final int MASTER_STREAM_TYPE = 3;
private static final int ON_RESUME_PING_DELAY = 500;
private static final int STAY_ON_WHILE_GRABBED_TIMEOUT = 30000;
private static final String TAG = "LockScreen";
private static final int WAIT_FOR_ANIMATION_TIMEOUT;
Bitmap BitmapLock;
Bitmap BitmapLockin;
Bitmap BitmapLockout;
final float MAX_LOCK_VOLUME = 0.2F;
final float MIN_LOCK_VOLUME = 0.05F;
int circleinwidth;
int circlewidth;
private ImageView imageCircle;
private LinearLayout linearLayout;
private LinearLayout linearLayout2;
private int locationBrower[];
private int locationCall[];
private int locationCamera[];
private boolean mAnimate;
private AudioManager mAudioManager;
private ImageView mBrower;
private boolean mBrowerPress;
private ImageView mCall;
private boolean mCallPress;
private KeyguardScreenCallback mCallback;
private ImageView mCamera;
private boolean mCameraPress;
private RelativeLayout mChildView;
private Context mContext;
private int mCreationOrientation;
private boolean mDMLock;
private boolean mEnableMenuKeyInLockScreen;
private float mFirstMotionX;
private float mFirstMotionY;
private HDMINative mHDMI;
private int mKeyboardHidden;
private float mLastMotionX;
private float mLastMotionY;
private LockPatternUtils mLockPatternUtils;
private int mLockSoundId;
private int mLockSoundStreamId;
private SoundPool mLockSounds;
private TextView mLockString;
private int mMasterStreamMaxVolume;
private float mMotionDeltaX;
private float mMotionDeltaY;
private int mMoveFirst;
private boolean mMoveFirst2;
private final Runnable mOnResumePing = new Runnable() {
final LockScreen this$0;
public void run()
{
if (mDMLock)
mUnlockWidgetMethods.ping();
}
{
this$0 = LockScreen.this;
super();
}
};
Paint mPaintin;
Paint mPaintout;
private boolean mScreenOn;
private boolean mSilentMode;
private KeyguardStatusViewManager mStatusViewManager;
private boolean mTouching;
private boolean mUnlock;
private int mUnlockSoundId;
private View mUnlockWidget;
private UnlockWidgetCommonMethods mUnlockWidgetMethods;
private KeyguardUpdateMonitor mUpdateMonitor;
private final WallpaperManager mWallpaperManager;
private float mYVelocity;
DrawWaterWave m_DrawWaterWave;
LockScreen(Context context, Configuration configuration, LockPatternUtils lockpatternutils, KeyguardUpdateMonitor keyguardupdatemonitor, KeyguardScreenCallback keyguardscreencallback)
{
super(context);
mHDMI = new HDMINative();
BitmapLockin = null;
BitmapLockout = null;
BitmapLock = null;
circleinwidth = 75;
circlewidth = 180;
mMoveFirst = 0;
mMoveFirst2 = false;
mPaintin = null;
mPaintout = null;
mTouching = false;
mAnimate = false;
mUnlock = false;
mScreenOn = false;
mDMLock = false;
mContext = null;
mCallPress = false;
mBrowerPress = false;
mCameraPress = false;
locationCall = new int[2];
locationBrower = new int[2];
locationCamera = new int[2];
mContext = context;
mLockPatternUtils = lockpatternutils;
mUpdateMonitor = keyguardupdatemonitor;
mCallback = keyguardscreencallback;
mEnableMenuKeyInLockScreen = shouldEnableMenuKey();
mWallpaperManager = WallpaperManager.getInstance(context);
mCreationOrientation = configuration.orientation;
mKeyboardHidden = configuration.hardKeyboardHidden;
LayoutInflater layoutinflater = LayoutInflater.from(context);
Log.v("LockScreen", (new StringBuilder()).append("Creation orientation = ").append(mCreationOrientation).toString());
Log.i("LockScreen", "we will initialize the LockScreen single portrait layout");
layoutinflater.inflate(0x109005a, this, true);
mChildView = (RelativeLayout)findViewById(0x10202b4);
setBackDrawable();
mStatusViewManager = new KeyguardStatusViewManager(this, mUpdateMonitor, mLockPatternUtils, mCallback, false);
setFocusable(true);
setFocusableInTouchMode(true);
setDescendantFocusability(0x60000);
mAudioManager = (AudioManager)mContext.getSystemService("audio");
mSilentMode = isSilentMode();
m_DrawWaterWave = new DrawWaterWave(context);
if (mDMLock)
{
mUnlockWidget = findViewById(0x102029b);
android.content.ContentResolver contentresolver;
String s;
StringBuilder stringbuilder;
if (mUnlockWidget instanceof SlidingTab)
{
SlidingTab slidingtab = (SlidingTab)mUnlockWidget;
slidingtab.setHoldAfterTrigger(true, false);
slidingtab.setLeftHintText(0x104030a);
slidingtab.setLeftTabResources(0x10802cb, 0x1080396, 0x1080377, 0x108038a);
SlidingTabMethods slidingtabmethods = new SlidingTabMethods(slidingtab);
slidingtab.setOnTriggerListener(slidingtabmethods);
mUnlockWidgetMethods = slidingtabmethods;
} else
if (mUnlockWidget instanceof WaveView)
{
WaveView waveview = (WaveView)mUnlockWidget;
WaveViewMethods waveviewmethods = new WaveViewMethods(waveview);
waveview.setOnTriggerListener(waveviewmethods);
mUnlockWidgetMethods = waveviewmethods;
} else
if (mUnlockWidget instanceof MultiWaveView)
{
MultiWaveView multiwaveview = (MultiWaveView)mUnlockWidget;
MultiWaveViewMethods multiwaveviewmethods = new MultiWaveViewMethods(multiwaveview);
multiwaveview.setOnTriggerListener(multiwaveviewmethods);
mUnlockWidgetMethods = multiwaveviewmethods;
} else
{
throw new IllegalStateException((new StringBuilder()).append("Unrecognized unlock widget: ").append(mUnlockWidget).toString());
}
mUnlockWidgetMethods.updateResources();
}
BitmapLockin = ((BitmapDrawable)(BitmapDrawable)getResources().getDrawable(0x1080617)).getBitmap();
BitmapLockout = ((BitmapDrawable)(BitmapDrawable)getResources().getDrawable(0x1080619)).getBitmap();
BitmapLock = ((BitmapDrawable)(BitmapDrawable)getResources().getDrawable(0x1080618)).getBitmap();
imageCircle = (ImageView)findViewById(0x10202c7);
mCall = (ImageView)findViewById(0x10202c0);
mBrower = (ImageView)findViewById(0x10202c1);
mCamera = (ImageView)findViewById(0x10202c2);
mLockString = (TextView)findViewById(0x10202bd);
mPaintin = new Paint();
mPaintout = new Paint();
contentresolver = mContext.getContentResolver();
mLockSounds = new SoundPool(1, 1, 0);
s = android.provider.Settings.System.getString(contentresolver, "lock_sound");
if (s != null)
mLockSoundId = mLockSounds.load(s, 1);
if (s == null || mLockSoundId == 0)
Log.d("LockScreen", (new StringBuilder()).append("failed to load sound from ").append(s).toString());
if ("/system/media/audio/ui/Effect_Tick.ogg" != null)
mUnlockSoundId = mLockSounds.load("/system/media/audio/ui/Effect_Tick.ogg", 1);
if ("/system/media/audio/ui/Effect_Tick.ogg" == null || mUnlockSoundId == 0)
Log.d("LockScreen", (new StringBuilder()).append("failed to load sound from ").append("/system/media/audio/ui/Effect_Tick.ogg").toString());
if (mUpdateMonitor.DM_IsLocked() && mDMLock)
{
Log.i("LockScreen", "we should hide unlock widget");
mUnlockWidget.setVisibility(4);
}
if (mDMLock)
{
stringbuilder = (new StringBuilder()).append("*** LockScreen accel is ");
String s1;
if (mUnlockWidget.isHardwareAccelerated())
s1 = "on";
else
s1 = "off";
Log.v("LockScreen", stringbuilder.append(s1).toString());
}
}
private boolean isScreenOn()
{
PowerManager powermanager = (PowerManager)mContext.getSystemService("power");
boolean flag = false;
if (powermanager != null)
{
flag = powermanager.isScreenOn();
Log.d("LockScreen", (new StringBuilder()).append("screenOn:").append(flag).toString());
}
return flag;
}
private boolean isSilentMode()
{
boolean flag;
if (mAudioManager.getRingerMode() != 2)
flag = true;
else
flag = false;
return flag;
}
private void playSounds(boolean flag)
{
if (android.provider.Settings.System.getInt(mContext.getContentResolver(), "lockscreen_sounds_enabled", 1) != 1) goto _L2; else goto _L1
_L1:
int i;
if (flag)
i = mLockSoundId;
else
i = mUnlockSoundId;
mLockSounds.stop(mLockSoundStreamId);
if (mAudioManager != null) goto _L4; else goto _L3
_L3:
mAudioManager = (AudioManager)mContext.getSystemService("audio");
if (mAudioManager != null) goto _L5; else goto _L2
_L2:
return;
_L5:
mMasterStreamMaxVolume = mAudioManager.getStreamMaxVolume(3);
_L4:
int j = mAudioManager.getStreamVolume(3);
if (j != 0)
{
float f = 0.05F + 0.15F * ((float)j / (float)mMasterStreamMaxVolume);
Log.d("LockScreen", (new StringBuilder()).append("playSounds").append(i).toString());
mLockSoundStreamId = mLockSounds.play(i, f, f, 1, 0, 1.0F);
}
if (true) goto _L2; else goto _L6
_L6:
}
private void requestUnlockScreen()
{
postDelayed(new Runnable() {
final LockScreen this$0;
public void run()
{
mCallback.goToUnlockScreen();
}
{
this$0 = LockScreen.this;
super();
}
}, 0L);
}
private void setBackDrawable()
{
}
private boolean shouldEnableMenuKey()
{
boolean flag = getResources().getBoolean(0x111001a);
boolean flag1 = ActivityManager.isRunningInTestHarness();
boolean flag2 = (new File("/data/local/enable_menu_key")).exists();
boolean flag3;
if (!flag || flag1 || flag2)
flag3 = true;
else
flag3 = false;
return flag3;
}
private void toggleRingMode()
{
int i = 1;
boolean flag;
if (!mSilentMode)
flag = i;
else
flag = false;
mSilentMode = flag;
if (mSilentMode)
{
int j;
AudioManager audiomanager;
if (android.provider.Settings.System.getInt(mContext.getContentResolver(), "vibrate_in_silent", i) == i)
j = i;
else
j = 0;
audiomanager = mAudioManager;
if (j == 0)
i = 0;
audiomanager.setRingerMode(i);
} else
{
mAudioManager.setRingerMode(2);
}
}
public void cleanUp()
{
mUpdateMonitor.removeCallback(this);
mLockPatternUtils = null;
mUpdateMonitor = null;
mCallback = null;
}
protected void dispatchDraw(Canvas canvas)
{
if ((mTouching || mMoveFirst != 0) && !mDMLock)
{
super.dispatchDraw(canvas);
canvas.save();
canvas.translate(0.0F, 0.0F);
if (mMotionDeltaX * mMotionDeltaX + mMotionDeltaY * mMotionDeltaY > (float)(circleinwidth * circleinwidth))
{
float f = mMotionDeltaX * mMotionDeltaX + mMotionDeltaY * mMotionDeltaY;
float f1 = (0 + (0 + circlewidth)) * (0 + (0 + circlewidth));
float f2 = (255F * f) / f1;
if (f2 >= 255F)
f2 = 255F;
mPaintin.setAlpha((int)(255F - f2));
} else
{
mPaintin.setAlpha(255);
}
canvas.drawBitmap(BitmapLockin, mFirstMotionX - (float)circlewidth, mFirstMotionY - (float)circlewidth, mPaintin);
canvas.drawBitmap(BitmapLock, mFirstMotionX - 25F, mFirstMotionY - 25F, null);
canvas.restore();
invalidate();
if (mMoveFirst == 1)
mMoveFirst = 2;
if (isScreenOn())
mCallback.pokeWakelock();
else
Log.i("LockScreen", "dispatch, screenoff");
} else
{
setBackDrawable();
super.dispatchDraw(canvas);
}
}
public boolean needsInput()
{
return false;
}
protected void onAttachedToWindow()
{
super.onAttachedToWindow();
updateConfiguration();
}
public void onClick2(View view)
{
if (view.getId() != 0x10202c0) goto _L2; else goto _L1
_L1:
mCallPress = true;
mBrowerPress = false;
mCameraPress = false;
mCall.setVisibility(0);
mBrower.setVisibility(4);
mCamera.setVisibility(4);
_L4:
return;
_L2:
if (view.getId() == 0x10202c1)
{
mCallPress = false;
mBrowerPress = true;
mCameraPress = false;
mCall.setVisibility(4);
mBrower.setVisibility(0);
mCamera.setVisibility(4);
} else
if (view.getId() == 0x10202c2)
{
mCallPress = false;
mBrowerPress = false;
mCameraPress = true;
mCall.setVisibility(4);
mBrower.setVisibility(4);
mCamera.setVisibility(0);
}
if (true) goto _L4; else goto _L3
_L3:
}
protected void onConfigurationChanged(Configuration configuration)
{
super.onConfigurationChanged(configuration);
updateConfiguration();
}
public boolean onKeyDown(int i, KeyEvent keyevent)
{
if (i == 82 && mEnableMenuKeyInLockScreen)
mCallback.goToUnlockScreen();
return false;
}
public void onPause()
{
mScreenOn = false;
mTouching = false;
mStatusViewManager.onPause();
setBackDrawable();
if (mDMLock)
mUnlockWidgetMethods.reset(false);
mHDMI.hdmiPortraitEnable(false);
}
public void onPhoneStateChanged(String s)
{
}
public void onResume()
{
mAnimate = false;
mTouching = false;
mMotionDeltaY = 0.0F;
mStatusViewManager.onResume();
postDelayed(mOnResumePing, 500L);
mHDMI.hdmiPortraitEnable(true);
mScreenOn = isScreenOn();
setBackDrawable();
}
public void onRingerModeChanged(int i)
{
boolean flag;
if (2 != i)
flag = true;
else
flag = false;
if (flag != mSilentMode)
{
mSilentMode = flag;
if (mDMLock)
mUnlockWidgetMethods.updateResources();
}
}
public boolean onTouchEvent(MotionEvent motionevent)
{
if (mScreenOn && !mDMLock) goto _L2; else goto _L1
_L1:
boolean flag;
Log.w("LockScreen", " ** Lock Screen is off or animation is running **");
flag = false;
_L8:
return flag;
_L2:
int i;
int j;
int k;
int l;
int i1;
int j1;
int k1;
int l1;
int i2;
i = motionevent.getAction();
j = (int)motionevent.getX();
mUnlock = false;
k = (int)motionevent.getY();
l = mCall.getWidth();
i1 = mCall.getHeight();
j1 = mBrower.getWidth();
k1 = mBrower.getHeight();
l1 = mCamera.getWidth();
i2 = mCamera.getHeight();
mCall.getLocationInWindow(locationCall);
mBrower.getLocationInWindow(locationBrower);
mCamera.getLocationInWindow(locationCamera);
i & 0xff;
JVM INSTR tableswitch 0 2: default 172
// 0 193
// 1 834
// 2 662;
goto _L3 _L4 _L5 _L6
_L5:
break MISSING_BLOCK_LABEL_834;
_L3:
break; /* Loop/switch isn't completed */
_L4:
break; /* Loop/switch isn't completed */
_L9:
if (mUnlock)
mCallback.goToUnlockScreen();
flag = true;
if (true) goto _L8; else goto _L7
_L7:
if (!mAnimate)
{
if (k > locationCall[1] && k < i1 + locationCall[1] && j > locationCall[0] && j < l + locationCall[0])
{
mCallPress = true;
mBrowerPress = false;
mCameraPress = false;
mCall.setVisibility(0);
mBrower.setVisibility(4);
mCamera.setVisibility(4);
mLockString.setText(0x10404db);
} else
if (k > locationBrower[1] && k < k1 + locationBrower[1] && j > locationBrower[0] && j < j1 + locationBrower[0])
{
mCallPress = false;
mBrowerPress = true;
mCameraPress = false;
mCall.setVisibility(4);
mBrower.setVisibility(0);
mCamera.setVisibility(4);
mLockString.setText(0x10404db);
} else
if (k > locationCamera[1] && k < i2 + locationCamera[1] && j > locationCamera[0] && j < l1 + locationCamera[0])
{
mCallPress = false;
mBrowerPress = false;
mCameraPress = true;
mCall.setVisibility(4);
mBrower.setVisibility(4);
mCamera.setVisibility(0);
mLockString.setText(0x10404db);
} else
{
onWallpaperTap(motionevent);
}
playSounds(true);
mFirstMotionX = j;
mFirstMotionY = k;
mMoveFirst2 = true;
m_DrawWaterWave.DropStone(j, k, 10, 50);
if (mMoveFirst == 10)
{
mMoveFirst = 1;
AnimationSet animationset = new AnimationSet(false);
b8 b8_1 = new b8(mFirstMotionX - (float)circlewidth, mFirstMotionY - (float)circlewidth, linearLayout, linearLayout2);
b8_1.initialize(circlewidth, circlewidth, 0, 0);
animationset.addAnimation(b8_1);
linearLayout.startAnimation(animationset);
android.view.animation.Animation.AnimationListener animationlistener = new android.view.animation.Animation.AnimationListener() {
final LockScreen this$0;
public void onAnimationEnd(Animation animation)
{
if (mTouching)
linearLayout2.setVisibility(0);
linearLayout.clearAnimation();
linearLayout.setVisibility(4);
}
public void onAnimationRepeat(Animation animation)
{
}
public void onAnimationStart(Animation animation)
{
}
{
this$0 = LockScreen.this;
super();
}
};
b8_1.setAnimationListener(animationlistener);
}
}
goto _L9
_L6:
if (!mAnimate)
{
mTouching = true;
mMotionDeltaY = (float)k - mFirstMotionY;
mMotionDeltaX = (float)j - mFirstMotionX;
if ((mMotionDeltaX % 3F == 0.0F || mMotionDeltaY % 3F == 0.0F) && mFirstMotionY < 750F)
onWallpaperTap(motionevent);
if (mMoveFirst2 && (mMotionDeltaX >= 20F || mMotionDeltaY >= 20F || mMotionDeltaX <= -20F || mMotionDeltaY <= -20F) && mFirstMotionY < 750F)
mMoveFirst2 = false;
if (mMotionDeltaY <= 0.0F);
m_DrawWaterWave.DropStone(j, k, 10, 50);
}
goto _L9
if (!mAnimate)
{
onWallpaperTap(motionevent);
float f = mMotionDeltaX;
float f1 = mMotionDeltaY;
mTouching = false;
mMotionDeltaY = 0.0F;
mMotionDeltaX = 0.0F;
mMoveFirst = 0;
if ((mCallPress || mBrowerPress || mCameraPress) && k < 700 && mFirstMotionY > 750F)
{
Intent intent = new Intent();
if (mCallPress)
{
intent.setClassName("com.android.contacts", "com.android.contacts.DialtactsActivity");
intent.setAction("android.intent.action.DIAL");
} else
if (mBrowerPress)
intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
else
if (mCameraPress)
intent.setClassName("com.android.camera", "com.android.camera.Camera");
intent.setFlags(0x10000000);
mCallback.goToUnlockScreen();
mContext.startActivity(intent);
mUnlock = false;
} else
if (f * f + f1 * f1 > (float)(circlewidth * circlewidth))
{
mUnlock = true;
} else
{
mCall.setVisibility(0);
mBrower.setVisibility(0);
mCamera.setVisibility(0);
mLockString.setText(0x10404a0);
mUnlock = false;
}
imageCircle.setVisibility(8);
}
goto _L9
}
protected void onWallpaperTap(MotionEvent motionevent)
{
motionevent.findPointerIndex(motionevent.getPointerId(0));
Log.d("SlideButton", (new StringBuilder()).append("eee ").append(motionevent).toString());
mWallpaperManager.sendWallpaperTouch(getWindowToken(), motionevent);
}
protected void onWallpaperTapSecondary(MotionEvent motionevent)
{
int i = motionevent.findPointerIndex(motionevent.getPointerId(0));
mWallpaperManager.sendWallpaperCommand(getWindowToken(), "android.wallpaper.secondaryTap", 0 + (int)motionevent.getX(i), 0 + (int)motionevent.getY(i), 0, null);
}
void updateConfiguration()
{
int i;
Configuration configuration;
i = 1;
configuration = getResources().getConfiguration();
if (configuration.orientation == mCreationOrientation) goto _L2; else goto _L1
_L1:
mCallback.recreateMe(configuration);
_L4:
return;
_L2:
if (configuration.hardKeyboardHidden != mKeyboardHidden)
{
mKeyboardHidden = configuration.hardKeyboardHidden;
if (mKeyboardHidden != i)
i = 0;
if (mUpdateMonitor.isKeyguardBypassEnabled() && i != 0)
mCallback.goToUnlockScreen();
}
if (true) goto _L4; else goto _L3
_L3:
}
static
{
LOCKSCREEN_WALLPAPER_DIR = new File("/data/data/com.android.settings/mtk");
LOCKSCREEN_WALLPAPER_FILE = new File(LOCKSCREEN_WALLPAPER_DIR, "lockScreenWallpaper");
}
/*
static boolean access$002(LockScreen lockscreen, boolean flag)
{
lockscreen.mSilentMode = flag;
return flag;
}
*/
enter code here
}
A good rule of thumb is that these decompilers only generate something that resembles java code. There are often syntax/compilation problems, and there's no guarantee that the semantics match that of the original class.
If you want a lossless representation, it's better to use a disassembler to view the bytecode. For dex files, you can use baksmali, dexdump or dedexer.

SurfaceView Returns black Screen in droidreader

I had tried alot & even search alot but i didn't found
the solution about the black screen
which i get by fetching the cache view on the surface view..
if is there any other way to capture the screen then let me know about this..
if i use another control & fetching the drawable cache of that control it also return null..
this is the code which i used to fetch the screen Image....
try {
// Button btn = new Button(mActivity.getApplicationContext());
view.buildDrawingCache();
view.setDrawingCacheEnabled(true);
Bitmap b = view.getDrawingCache();
b.compress(CompressFormat.JPEG, 100, new FileOutputStream(
"/mnt/sdcard/documents/" + new Date().getTime() + ".JPEG"));
} catch (Exception e) {
e.printStackTrace();
}
i had used this on the touch_up action of the surface view.....
EDIT:
public class DroidReaderActivity extends Activity {
private static final boolean LOG = false;
private static final int REQUEST_CODE_PICK_FILE = 1;
private static final int REQUEST_CODE_OPTION_DIALOG = 2;
private static final int DIALOG_GET_PASSWORD = 1;
private static final int DIALOG_ABOUT = 2;
private static final int DIALOG_GOTO_PAGE = 3;
private static final int DIALOG_WELCOME = 4;
private static final int DIALOG_ENTER_ZOOM = 5;
private static final String PREFERENCE_EULA_ACCEPTED = "eula.accepted";
private static final String PREFERENCES_EULA = "eula";
protected DroidReaderView mReaderView = null;
protected DroidReaderDocument mDocument = null;
protected Menu m_ZoomMenu;
FrameLayout fl;
private String mFilename;
private String mTemporaryFilename;
private String mPassword;
private int mPageNo;
private SQLiteDatabase db;
static DatabaseConnectionAPI db_api;
private boolean mDocumentIsOpen = false;
private boolean mLoadedDocument = false;
private boolean mWelcomeShown = false;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_PICK_FILE:
if (resultCode == RESULT_OK && data != null) {
// Theoretically there could be a case where OnCreate() is called
// again with the intent that was originally used to open the app,
// which would revert to a previous document. Use setIntent
// to update the intent that will be supplied back to OnCreate().
setIntent(data);
mTemporaryFilename = data.getDataString();
if (mTemporaryFilename != null) {
if (mTemporaryFilename.startsWith("file://")) {
mTemporaryFilename = mTemporaryFilename.substring(7);
}
mPassword = "";
openDocumentWithDecodeAndLookup();
}
}
break;
case REQUEST_CODE_OPTION_DIALOG:
readPreferences();
tryLoadLastFile();
break;
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("ONCREATE");
db_api = new DatabaseConnectionAPI(this);
try {
db_api.createDataBase();
db_api.openDataBase();
} catch (IOException e) {
e.printStackTrace();
}
// first, show the welcome if it hasn't been shown already:
final SharedPreferences preferences = getSharedPreferences(PREFERENCES_EULA, Context.MODE_PRIVATE);
if (!preferences.getBoolean(PREFERENCE_EULA_ACCEPTED, false)) {
mWelcomeShown = true;
preferences.edit().putBoolean(PREFERENCE_EULA_ACCEPTED, true).commit();
showDialog(DIALOG_WELCOME);
}
if (mDocument == null)
mDocument = new DroidReaderDocument();
// Initialize the PdfRender engine
PdfRender.setFontProvider(new DroidReaderFontProvider(this));
// then build our layout. it's so simple that we don't use
// XML for now.
fl = new FrameLayout(this);
mReaderView = new DroidReaderView(this, null, mDocument);
// add the viewing area and the navigation
fl.addView(mReaderView);
setContentView(fl);
readPreferences();
if (savedInstanceState != null) {
mFilename = savedInstanceState.getString("filename");
if ((new File(mFilename)).exists()) {
mPassword = savedInstanceState.getString("password");
mDocument.mZoom = savedInstanceState.getFloat("zoom");
mDocument.mRotation = savedInstanceState.getInt("rotation");
mPageNo = savedInstanceState.getInt("page");
mDocument.mMarginOffsetX = savedInstanceState.getInt("marginOffsetX");
mDocument.mMarginOffsetY = savedInstanceState.getInt("marginOffsetY");
mDocument.mContentFitMode = savedInstanceState.getInt("contentFitMode");
openDocument();
mLoadedDocument = true;
}
savedInstanceState.clear();
}
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask() {
#Override
public void run() {
try {
Bitmap saveBitmap = Bitmap.createBitmap(fl.getWidth(), fl.getHeight(), Bitmap.Config.ARGB_8888);
saveBitmap.compress(CompressFormat.JPEG, 100,
new FileOutputStream("/mnt/sdcard/documents/" + new Date().getTime() + ".JPEG"));
} catch (Exception e) {
e.printStackTrace();
}
}
}, 4000);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if ((mDocument != null) && mDocument.isPageLoaded()) {
outState.putFloat("zoom", mDocument.mZoom);
outState.putInt("rotation", mDocument.mRotation);
outState.putInt("page", mDocument.mPage.no);
outState.putInt("offsetX", mDocument.mOffsetX);
outState.putInt("offsetY", mDocument.mOffsetY);
outState.putInt("marginOffsetX", mDocument.mMarginOffsetX);
outState.putInt("marginOffsetY", mDocument.mMarginOffsetY);
outState.putInt("contentFitMode", mDocument.mContentFitMode);
outState.putString("password", mPassword);
outState.putString("filename", mFilename);
mDocument.closeDocument();
}
}
public void onTap(float X, float Y) {
float left, right, top, bottom;
float width = mDocument.mDisplaySizeX;
float height = mDocument.mDisplaySizeY;
boolean prev = false;
boolean next = false;
if (mDocumentIsOpen) {
left = width * (float) 0.25;
right = width * (float) 0.75;
top = height * (float) 0.25;
bottom = height * (float) 0.75;
if ((X < left) && (Y < top))
prev = true;
if ((X < left) && (Y > bottom))
next = true;
if ((X > right) && (Y < top))
prev = true;
if ((X > right) && (Y > bottom))
next = true;
if ((X > left) && (X < right) && (Y > bottom)) {
Log.d("DroidReaderMetrics", String.format("Zoom = %5.2f%%", mDocument.mZoom * 100.0));
Log.d("DroidReaderMetrics", String.format("Page size = (%2.0f,%2.0f)", mDocument.mPage.mMediabox[2]
- mDocument.mPage.mMediabox[0], mDocument.mPage.mMediabox[3] - mDocument.mPage.mMediabox[1]));
Log.d("DroidReaderMetrics", String.format(
"Display size = (%d,%d)", mDocument.mDisplaySizeX, mDocument.mDisplaySizeY));
Log.d("DroidReaderMetrics", String.format("DPI = (%d, %d)", mDocument.mDpiX, mDocument.mDpiY));
Log.d("DroidReaderMetrics", String.format("Content size = (%2.0f,%2.0f)",
mDocument.mPage.mContentbox[2] - mDocument.mPage.mContentbox[0],
mDocument.mPage.mContentbox[3] - mDocument.mPage.mContentbox[1]));
Log.d("DroidReaderMetrics", String.format("Content offset = (%2.0f,%2.0f)",
mDocument.mPage.mContentbox[0], mDocument.mPage.mContentbox[1]));
Log.d("DroidReaderMetrics", String.format(
"Document offset = (%d,%d)", mDocument.mOffsetX, mDocument.mOffsetY));
}
if (next) {
if (mDocument.havePage(1, true))
openPage(1, true);
} else if (prev) {
if (mDocument.havePage(-1, true))
openPage(-1, true);
}
}
}
protected void openDocument() {
// Store the view details for the previous document and close it.
if (mDocumentIsOpen) {
mDocument.closeDocument();
mDocumentIsOpen = false;
}
try {
this.setTitle(mFilename);
mDocument.open(mFilename, mPassword, mPageNo);
openPage(0, true);
mDocumentIsOpen = true;
} catch (PasswordNeededException e) {
showDialog(DIALOG_GET_PASSWORD);
} catch (WrongPasswordException e) {
Toast.makeText(this, R.string.error_wrong_password, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, R.string.error_opening_document, Toast.LENGTH_LONG).show();
}
}
protected void openDocumentWithDecodeAndLookup() {
try {
mTemporaryFilename = URLDecoder.decode(mTemporaryFilename, "utf-8");
// Do some sanity checks on the supplied filename.
File f = new File(mTemporaryFilename);
if ((f.exists()) && (f.isFile()) && (f.canRead())) {
mFilename = mTemporaryFilename;
openDocumentWithLookup();
} else {
Toast.makeText(this, R.string.error_file_open_failed, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, R.string.error_opening_document, Toast.LENGTH_LONG).show();
}
}
protected void openDocumentWithLookup() {
readOrWriteDB(false);
openDocument();
}
protected void openPage(int no, boolean isRelative) {
try {
if (!(no == 0 && isRelative))
mDocument.openPage(no, isRelative);
this.setTitle(new File(mFilename).getName()
+ String.format(" (%d/%d)", mDocument.mPage.no, mDocument.mDocument.pagecount));
mPageNo = mDocument.mPage.no;
} catch (PageLoadException e) {
}
}
private void readPreferences() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
if (prefs.getString("zoom_type", "0").equals("0")) {
float zoom = Float.parseFloat(prefs.getString("zoom_percent", "50"));
if ((1 <= zoom) && (1000 >= zoom)) {
mDocument.setZoom(zoom / 100, false);
}
} else {
mDocument.setZoom(Float.parseFloat(prefs.getString("zoom_type", "0")), false);
}
if (prefs.getBoolean("dpi_auto", true)) {
// read the display's DPI
mDocument.setDpi((int) metrics.xdpi, (int) metrics.ydpi);
} else {
int dpi = Integer.parseInt(prefs.getString("dpi_manual", "160"));
if ((dpi < 1) || (dpi > 4096))
dpi = 160; // sanity check fallback
mDocument.setDpi(dpi, dpi);
}
if (prefs.getBoolean("tilesize_by_factor", true)) {
// set the tile size for rendering by factor
Float factor = Float.parseFloat(prefs.getString("tilesize_factor", "1.5"));
mDocument.setTileMax((int) (metrics.widthPixels * factor), (int) (metrics.heightPixels * factor));
} else {
int tilesize_x = Integer.parseInt(prefs.getString("tilesize_x", "640"));
int tilesize_y = Integer.parseInt(prefs.getString("tilesize_x", "480"));
if (metrics.widthPixels < metrics.heightPixels) {
mDocument.setTileMax(tilesize_x, tilesize_y);
} else {
mDocument.setTileMax(tilesize_y, tilesize_x);
}
}
boolean invert = prefs.getBoolean("invert_display", false);
mDocument.setDisplayInvert(invert);
mReaderView.setDisplayInvert(invert);
if (prefs.getBoolean("full_screen", false)) {
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
mDocument.mHorizontalScrollLock = prefs.getBoolean("horizontal_scroll_lock", false);
}
protected void setZoom(float newZoom) {
newZoom = newZoom / (float) 100.0;
if (newZoom > 16.0)
newZoom = (float) 16.0;
if (newZoom < 0.0625)
newZoom = (float) 0.0625;
mDocument.setZoom(newZoom, false);
}
protected void tryLoadLastFile() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mFilename = prefs.getString("last_open_file", "");
if (mFilename != null) {
if ((mFilename.length() > 0) && ((new File(mFilename)).exists())) {
// Don't URL-decode the filename, as that's presumably already been done.
mPassword = "";
openDocumentWithLookup();
mLoadedDocument = true;
}
}
}
}
DroidReaderView:
public class DroidReaderView extends SurfaceView implements OnGestureListener,
SurfaceHolder.Callback, DroidReaderDocument.RenderListener {
public static Path mPath = new Path();
private static StringBuffer sbx = new StringBuffer();
private static StringBuffer sby = new StringBuffer();
public static Paint mPaint = new Paint();
public static Paint nullpaint = new Paint();
private String sx, sy, sbx_str, sby_str;
public static Canvas mCanvas = new Canvas();
private int pid = 1;
/**
* Debug helper
*/
protected final static String TAG = "DroidReaderView";
protected final static boolean LOG = false;
/**
* our view thread which does the drawing
*/
public DroidReaderViewThread mThread;
/**
* our gesture detector
*/
protected final GestureDetector mGestureDetector;
/**
* our context
*/
protected final DroidReaderActivity mActivity;
/**
* our SurfaceHolder
*/
protected final SurfaceHolder mSurfaceHolder;
public static DroidReaderDocument mDocument;
protected boolean mDisplayInvert;
/**
* constructs a new View
*
* #param context
* Context for the View
* #param attrs
* attributes (may be null)
*/
public DroidReaderView(final DroidReaderActivity activity, AttributeSet attrs, DroidReaderDocument document) {
super(activity, attrs);
mActivity = activity;
mSurfaceHolder = getHolder();
mDocument = document;
mDocument.mRenderListener = this;
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
// tell the SurfaceHolder to inform this thread on
// changes to the surface
mSurfaceHolder.addCallback(this);
mGestureDetector = new GestureDetector(this);
}
/* event listeners: */
#Override
protected void onDraw(Canvas canvas) {
mThread.c = canvas;
mThread.c = mSurfaceHolder.lockCanvas();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
mThread.c.drawPath(mPath, mPaint);
mSurfaceHolder.unlockCanvasAndPost(mThread.c);
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (LOG)
Log.d(TAG, "onFling(): notifying ViewThread");
mThread.mScroller.fling(0, 0, -(int) velocityX, -(int) velocityY, -4096, 4096, -4096, 4096);
mThread.triggerRepaint();
return true;
}
/* keyboard events: */
#Override
public boolean onKeyDown(int keyCode, KeyEvent msg) {
if (LOG)
Log.d(TAG, "onKeyDown(), keycode " + keyCode);
return false;
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent msg) {
if (LOG)
Log.d(TAG, "onKeyUp(), keycode " + keyCode);
return false;
}
/* interface for the GestureListener: */
#Override
public void onLongPress(MotionEvent e) {
if (LOG)
Log.d(TAG, "onLongPress(): ignoring!");
}
#Override
public void onNewRenderedPixmap() {
if (LOG)
Log.d(TAG, "new rendered pixmap was signalled");
mThread.triggerRepaint();
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (LOG)
Log.d(TAG, "onScroll(), distance vector: " + distanceX + "," + distanceY);
mDocument.offset((int) distanceX, (int) distanceY, true);
mThread.triggerRepaint();
return true;
}
#Override
public void onShowPress(MotionEvent e) {
if (LOG)
Log.d(TAG, "onShowPress(): ignoring!");
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// Pass the tap, and the window dimensions, to the activity to process.
mActivity.onTap(e.getX(), e.getY());
return true;
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touch_start(float x, float y) {
mPath.moveTo(x, y);
mX = x;
sx = Float.toString(mX);
sbx.append(sx);
sbx.append(",");
mY = y;
sy = Float.toString(mY);
sby.append(sy);
sby.append(",");
sbx_str = sbx.toString();
sby_str = sby.toString();
}
private void draw_move(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;
sx = Float.toString(mX);
sbx.append(sx);
sbx.append(",");
mY = y;
sy = Float.toString(mY);
sby.append(sy);
sby.append(",");
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
sx = Float.toString(mX);
sbx.append(sx);
sbx.append(",");
sy = Float.toString(mY);
sby.append(sy);
sby.append(",");
mPath.reset();
sbx_str = sbx.toString().trim();
sby_str = sby.toString().trim();
insert(TAGS.presentation_id, mDocument.mPage.no, sbx_str, sby_str);
sbx = new StringBuffer();
sby = new StringBuffer();
System.out.println(sbx_str.trim());
System.out.println(sby_str.trim());
}
#Override
public boolean onTouchEvent(final MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
draw_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
try {
// Button btn = new Button(mActivity.getApplicationContext());
// buildDrawingCache();
// setDrawingCacheEnabled(true);
// Bitmap b = getDrawingCache();
// b.compress(CompressFormat.JPEG, 100, new FileOutputStream(
// "/mnt/sdcard/documents/" + new Date().getTime() + ".JPEG"));
} catch (Exception e) {
e.printStackTrace();
}
break;
}
invalidate();
if (LOG) {
Log.d(TAG, "onTouchEvent(): notifying mGestureDetector");
invalidate();
}
if (mGestureDetector.onTouchEvent(event)) {
invalidate();
return true;
}
return true;
}
#Override
public boolean onTrackballEvent(MotionEvent event) {
if (LOG)
Log.d(TAG, "onTouchEvent(): notifying ViewThread");
mDocument
.offset((int) event.getX() * 20, (int) event.getY() * 20, true);
mThread.triggerRepaint();
return true;
}
/* surface events: */
public void setDisplayInvert(boolean invert) {
if (mThread != null)
mThread.setPainters(invert);
mDisplayInvert = invert;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if (LOG)
Log.d(TAG, "surfaceChanged(): size " + width + "x" + height);
mDocument.startRendering(width, height);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (LOG)
Log.d(TAG, "surfaceCreated(): starting ViewThread");
mThread = new DroidReaderViewThread(holder, mActivity, mDocument);
mThread.setPainters(mDisplayInvert);
mThread.start();
}
/* render events */
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (LOG)
Log.d(TAG, "surfaceDestroyed(): dying");
mDocument.stopRendering();
boolean retry = true;
mThread.mRun = false;
mThread.interrupt();
while (retry) {
try {
mThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
#Override
public boolean onDown(MotionEvent e) {
return false;
}
DroidReaderViewThread :
Thread that cares for blitting Pixmaps onto the Canvas and handles scrolling
class DroidReaderViewThread extends Thread {
public Canvas c = new Canvas();
private Cursor mCursor;
private Path mPath1 = new Path();
private StringBuffer sbx_read, sby_read;
public static Paint mPaint2 = new Paint();
public static Paint mPaint3 = new Paint();
Path old_path = new Path();
/**
* Debug helper
*/
protected final static String TAG = "DroidReaderViewThread";
protected final static boolean LOG = false;
/**
* the SurfaceHolder for our Surface
*/
protected final SurfaceHolder mSurfaceHolder;
/**
* Paint for not (yet) rendered parts of the page
*/
protected final Paint mEmptyPaint;
/**
* Paint for filling the display when there is no PdfPage (yet)
*/
protected final Paint mNoPagePaint;
/**
* Paint for the status text
*/
protected final Paint mStatusPaint;
/**
* Flag that our thread should be running
*/
protected boolean mRun = true;
/**
* our scroller
*/
protected final Scroller mScroller;
protected final DroidReaderDocument mDocument;
/**
* Background render thread, using the SurfaceView programming scheme
*
* #param holder
* our SurfaceHolder
* #param context
* the Context for our drawing
*/
public DroidReaderViewThread(SurfaceHolder holder, Context context, DroidReaderDocument document) {
// store a reference to our SurfaceHolder
mSurfaceHolder = holder;
mDocument = document;
// initialize Paints for non-Pixmap areas
mEmptyPaint = new Paint();
mNoPagePaint = new Paint();
mStatusPaint = new Paint();
setPainters(false);
// the scroller, i.e. the object that calculates/interpolates
// positions for scrolling/jumping/flinging
mScroller = new Scroller(context);
}
/**
* ll this does the actual drawing to the Canvas for our surface
*/
private void doDraw() {
if (LOG)
Log.d(TAG, "drawing...");
c = null;
try {
c = mSurfaceHolder.lockCanvas(null);
if (!mDocument.isPageLoaded()) {
// no page/document loaded
if (LOG)
Log.d(TAG, "no page loaded.");
c.drawRect(0, 0, c.getWidth(), c.getHeight(), mNoPagePaint);
} else if (mDocument.havePixmap()) {
// we have both page and Pixmap, so draw:
// background:
if (LOG)
Log.d(TAG, "page loaded, rendering pixmap");
c.drawRect(0, 0, c.getWidth(), c.getHeight(), mEmptyPaint);
Log.d("CALL", "CALL");
c.drawBitmap(mDocument.mView.mBuf, 0,
mDocument.mView.mViewBox.width(), -mDocument.mOffsetX + mDocument.mView.mViewBox.left,
-mDocument.mOffsetY + mDocument.mView.mViewBox.top,
mDocument.mView.mViewBox.width(), mDocument.mView.mViewBox.height(), false, null);
try {
Log.d("Reading", "Reading");
mCursor = DroidReaderActivity.db_api
.ExecuteQueryGetCursor("SELECT * FROM path WHERE page_no=" + mDocument.mPage.no
+ " AND presentation_id=" + TAGS.presentation_id + ";");
if (!mCursor.equals(null)) {
mCursor.moveToFirst();
float x1 = 0, y1 = 0;
int pid = 0;
do {
sbx_read = new StringBuffer();
sbx_read.append(mCursor.getString(mCursor.getColumnIndex("x_path")));
sby_read = new StringBuffer();
sby_read.append(mCursor.getString(mCursor.getColumnIndex("y_path")));
String[] sbx_read_array = sbx_read.toString().trim().split(",");
String[] sby_read_array = sby_read.toString().trim().split(",");
for (int i = 0; i < sbx_read_array.length; i++) {
x1 = Float.parseFloat(sbx_read_array[i].toString());
y1 = Float.parseFloat(sby_read_array[i].toString());
if (pid != mCursor.getInt(mCursor.getColumnIndex("path_id"))) {
pid = mCursor.getInt(mCursor.getColumnIndex("path_id"));
Log.d("New Path Id.",
String.valueOf(mCursor.getInt(mCursor.getColumnIndex("path_id"))));
mPath1.reset();
mPath1.moveTo(x1, y1);
} else {
Log.d("Path id repeating.",
String.valueOf(mCursor.getInt(mCursor.getColumnIndex("path_id"))));
}
mPath1.lineTo(x1, y1);
c.drawPath(mPath1, DroidReaderView.mPaint);
}
} while (mCursor.moveToNext());
mCursor.close();
Log.d("Read mode Complete", "Read mode Complete");
}
} catch (Exception e) {
// Log.d("read Cursor", e.getMessage().toString());
}
} else {
// page loaded, but no Pixmap yet
if (LOG)
Log.d(TAG, "page loaded, but no active Pixmap.");
c.drawRect(0, 0, c.getWidth(), c.getHeight(), mEmptyPaint);
mPaint3.setAntiAlias(true);
mPaint3.setDither(true);
mPaint3.setColor(Color.TRANSPARENT);
mPaint3.setStyle(Paint.Style.STROKE);
mPaint3.setStrokeJoin(Paint.Join.ROUND);
mPaint3.setStrokeCap(Paint.Cap.ROUND);
mPaint3.setStrokeWidth(12);
mPaint3.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
c.drawPath(old_path, mPaint3);
}
} finally {
if (c != null) {
mPaint2.setAntiAlias(true);
mPaint2.setDither(true);
mPaint2.setColor(Color.GREEN);
mPaint2.setStyle(Paint.Style.STROKE);
mPaint2.setStrokeJoin(Paint.Join.ROUND);
mPaint2.setStrokeCap(Paint.Cap.ROUND);
mPaint2.setStrokeWidth(12);
c.drawPath(DroidReaderView.mPath, mPaint2);
// DroidReaderView.mPath.reset();
// old_path = DroidReaderView.mPath;
}
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
/**
* Main Thread loop
*/
#SuppressWarnings("static-access")
#Override
public void run() {
while (mRun) {
boolean doSleep = true;
if (!mScroller.isFinished()) {
if (mScroller.computeScrollOffset()) {
if (LOG)
Log.d(TAG, "new scroll offset");
doSleep = false;
int oldX = mDocument.mOffsetX;
int oldY = mDocument.mOffsetY;
mDocument.offset(mScroller.getCurrX(), mScroller.getCurrY(), true);
if ((oldX == mDocument.mOffsetX) && (oldY == mDocument.mOffsetY))
mScroller.abortAnimation();
} else {
mScroller.abortAnimation();
}
}
doDraw();
// if we're allowed, we will go to sleep now
if (doSleep) {
try {
// nothing to do, wait for someone waking us up:
if (LOG)
Log.d(TAG, "ViewThread going to sleep");
// between
// the check for pending interrupts and the sleep() which
// could lead to a not-handled repaint request:
if (!this.interrupted())
Thread.sleep(3600000);
} catch (InterruptedException e) {
if (LOG)
Log.d(TAG, "ViewThread woken up");
}
}
}
// mRun is now false, so we shut down.
if (LOG)
Log.d(TAG, "shutting down");
}
public void setPainters(boolean invert) {
// initialize Paints for non-Pixmap areas
mEmptyPaint.setStyle(Paint.Style.FILL);
mNoPagePaint.setStyle(Paint.Style.FILL);
mStatusPaint.setStyle(Paint.Style.FILL);
if (invert)
mEmptyPaint.setColor(0xff000000); // black
else
mEmptyPaint.setColor(0xffc0c0c0); // light gray
if (invert)
mNoPagePaint.setColor(0xff000000); // black
else
mNoPagePaint.setColor(0xff303030); // dark gray
if (invert)
mStatusPaint.setColor(0xff000000); // black
else
mStatusPaint.setColor(0xff808080); // medium gray
}
public void triggerRepaint() {
if (LOG)
Log.d(TAG, "repaint triggered");
interrupt();
}
}
I am using this, and its works fine in my case,
Here imageFrame is FrameLayout, root view of my View which I want to save as bitmap..
Bitmap saveBitmap = Bitmap.createBitmap(imageFrame.getWidth(), imageFrame.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(saveBitmap);
imageFrame.draw(c);
Try replacing imageFrame with your view.
EDIT:
Date date = new Date();
File filename = new File(file.getAbsoluteFile(), "" + date.getTime() + ".jpg");
try
{
fOut = new FileOutputStream(filename);
saveBitmap.compress(Bitmap.CompressFormat.JPEG, 50, fOut);
try
{
fOut.flush();
fOut.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
EDIT 2:
private void doDraw() {
int w = WIDTH_PX, h = HEIGHT_PX;
BitmapConfig conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
c = new Canvas(bmp);

Categories

Resources