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

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);

Related

How to fill the color gradually on drawn view canvas Android

I am having a WaveFormView on which I want to change the color of it while playing Audio file and as the Audio is paused it should be stopped coloring at that certain point and when resumed it should continue forward with coloring. I am not getting how to do it in my code..
This is the screen shot of my generated waveform. Now when I will click on Play button it should change the color of waveform gradually with red color (from start to end slowly).
Here is my code to draw waveform view.
WaveFormView.class
public class WaveformView extends View {
public interface WaveformListener {
public void waveformFling(float x);
public void waveformDraw();
}
;
// Colors
private Paint mGridPaint;
private Paint mSelectedLinePaint;
private Paint mUnselectedLinePaint;
private Paint mUnselectedBkgndLinePaint;
private Paint mBorderLinePaint;
private Paint mPlaybackLinePaint;
private Paint mTimecodePaint;
private SoundFile mSoundFile;
private int[] mLenByZoomLevel;
private double[][] mValuesByZoomLevel;
private double[] mZoomFactorByZoomLevel;
private int[] mHeightsAtThisZoomLevel;
private int mZoomLevel;
private int mNumZoomLevels;
private int mSampleRate;
private int mSamplesPerFrame;
private int mOffset;
private int mSelectionStart;
private int mSelectionEnd;
private int mPlaybackPos;
private float mDensity;
private float mInitialScaleSpan;
private WaveformListener mListener;
private GestureDetector mGestureDetector;
private ScaleGestureDetector mScaleGestureDetector;
private boolean mInitialized;
Color color;
public WaveformView(Context context, AttributeSet attrs) {
super(context, attrs);
// We don't want keys, the markers get these
setFocusable(false);
mGridPaint = new Paint();
mGridPaint.setAntiAlias(false);
mGridPaint.setColor(
getResources().getColor(R.color.grid_line));
mSelectedLinePaint = new Paint();
mSelectedLinePaint.setAntiAlias(false);
mSelectedLinePaint.setColor(
getResources().getColor(R.color.waveform_selected));
mUnselectedLinePaint = new Paint();
mUnselectedLinePaint.setAntiAlias(false);
mUnselectedLinePaint.setColor(
getResources().getColor(R.color.waveform_unselected));
mUnselectedBkgndLinePaint = new Paint();
mUnselectedBkgndLinePaint.setAntiAlias(false);
mUnselectedBkgndLinePaint.setColor(
getResources().getColor(
R.color.selection_border));
mBorderLinePaint = new Paint();
mBorderLinePaint.setAntiAlias(true);
mBorderLinePaint.setStrokeWidth(1.5f);
mBorderLinePaint.setPathEffect(
new DashPathEffect(new float[]{3.0f, 2.0f}, 0.0f));
mBorderLinePaint.setColor(
getResources().getColor(R.color.selection_border));
mPlaybackLinePaint = new Paint();
mPlaybackLinePaint.setAntiAlias(false);
mPlaybackLinePaint.setColor(
getResources().getColor(R.color.playback_indicator));
mTimecodePaint = new Paint();
mTimecodePaint.setTextSize(12);
mTimecodePaint.setAntiAlias(true);
mTimecodePaint.setColor(
getResources().getColor(R.color.timecode));
mTimecodePaint.setShadowLayer(
2, 1, 1,
getResources().getColor(R.color.timecode_shadow));
mGestureDetector = new GestureDetector(
context,
new GestureDetector.SimpleOnGestureListener() {
public boolean onFling(
MotionEvent e1, MotionEvent e2, float vx, float vy) {
mListener.waveformFling(vx);
return true;
}
});
mSoundFile = null;
mLenByZoomLevel = null;
mValuesByZoomLevel = null;
mHeightsAtThisZoomLevel = null;
mOffset = 0;
mPlaybackPos = -1;
mSelectionStart = 0;
mSelectionEnd = 0;
mDensity = 1.0f;
mInitialized = false;
}
public boolean hasSoundFile() {
return mSoundFile != null;
}
public void setSoundFile(SoundFile soundFile) {
mSoundFile = soundFile;
mSampleRate = mSoundFile.getSampleRate();
mSamplesPerFrame = mSoundFile.getSamplesPerFrame();
computeDoublesForAllZoomLevels();
mHeightsAtThisZoomLevel = null;
}
/**
* Called once when a new sound file is added
*/
private void computeDoublesForAllZoomLevels() {
int numFrames = mSoundFile.getNumFrames();
int[] frameGains = mSoundFile.getFrameGains();
double[] smoothedGains = new double[numFrames];
if (numFrames == 1) {
smoothedGains[0] = frameGains[0];
} else if (numFrames == 2) {
smoothedGains[0] = frameGains[0];
smoothedGains[1] = frameGains[1];
} else if (numFrames > 2) {
smoothedGains[0] = (double)(
(frameGains[0] / 2.0) +
(frameGains[1] / 2.0));
for (int i = 1; i < numFrames - 1; i++) {
smoothedGains[i] = (double)(
(frameGains[i - 1] / 3.0) +
(frameGains[i ] / 3.0) +
(frameGains[i + 1] / 3.0));
}
smoothedGains[numFrames - 1] = (double)(
(frameGains[numFrames - 2] / 2.0) +
(frameGains[numFrames - 1] / 2.0));
}
// Make sure the range is no more than 0 - 255
double maxGain = 1.0;
for (int i = 0; i < numFrames; i++) {
if (smoothedGains[i] > maxGain) {
maxGain = smoothedGains[i];
}
}
double scaleFactor = 1.0;
if (maxGain > 255.0) {
scaleFactor = 255 / maxGain;
}
// Build histogram of 256 bins and figure out the new scaled max
maxGain = 0;
int gainHist[] = new int[256];
for (int i = 0; i < numFrames; i++) {
int smoothedGain = (int)(smoothedGains[i] * scaleFactor);
if (smoothedGain < 0)
smoothedGain = 0;
if (smoothedGain > 255)
smoothedGain = 255;
if (smoothedGain > maxGain)
maxGain = smoothedGain;
gainHist[smoothedGain]++;
}
// Re-calibrate the min to be 5%
double minGain = 0;
int sum = 0;
while (minGain < 255 && sum < numFrames / 20) {
sum += gainHist[(int)minGain];
minGain++;
}
// Re-calibrate the max to be 99%
sum = 0;
while (maxGain > 2 && sum < numFrames / 100) {
sum += gainHist[(int)maxGain];
maxGain--;
}
// Compute the heights
double[] heights = new double[numFrames];
double range = maxGain - minGain;
for (int i = 0; i < numFrames; i++) {
double value = (smoothedGains[i] * scaleFactor - minGain) / range;
if (value < 0.0)
value = 0.0;
if (value > 1.0)
value = 1.0;
heights[i] = value * value;
}
mNumZoomLevels = 5;
mLenByZoomLevel = new int[5];
mZoomFactorByZoomLevel = new double[5];
mValuesByZoomLevel = new double[5][];
// Level 0 is doubled, with interpolated values
mLenByZoomLevel[0] = numFrames * 2;
mZoomFactorByZoomLevel[0] = 2.0;
mValuesByZoomLevel[0] = new double[mLenByZoomLevel[0]];
if (numFrames > 0) {
mValuesByZoomLevel[0][0] = 0.5 * heights[0];
mValuesByZoomLevel[0][1] = heights[0];
}
for (int i = 1; i < numFrames; i++) {
mValuesByZoomLevel[0][2 * i] = 0.5 * (heights[i - 1] + heights[i]);
mValuesByZoomLevel[0][2 * i + 1] = heights[i];
}
// Level 1 is normal
mLenByZoomLevel[1] = numFrames;
mValuesByZoomLevel[1] = new double[mLenByZoomLevel[1]];
mZoomFactorByZoomLevel[1] = 1.0;
for (int i = 0; i < mLenByZoomLevel[1]; i++) {
mValuesByZoomLevel[1][i] = heights[i];
}
// 3 more levels are each halved
for (int j = 2; j < 5; j++) {
mLenByZoomLevel[j] = mLenByZoomLevel[j - 1] / 2;
mValuesByZoomLevel[j] = new double[mLenByZoomLevel[j]];
mZoomFactorByZoomLevel[j] = mZoomFactorByZoomLevel[j - 1] / 2.0;
for (int i = 0; i < mLenByZoomLevel[j]; i++) {
mValuesByZoomLevel[j][i] =
0.5 * (mValuesByZoomLevel[j - 1][2 * i] +
mValuesByZoomLevel[j - 1][2 * i + 1]);
}
}
if (numFrames > 5000) {
mZoomLevel = 3;
} else if (numFrames > 1000) {
mZoomLevel = 2;
} else if (numFrames > 300) {
mZoomLevel = 1;
} else {
mZoomLevel = 0;
}
mInitialized = true;
}
public boolean canZoomIn() {
return (mZoomLevel > 0);
}
public void zoomIn() {
if (canZoomIn()) {
mZoomLevel--;
mSelectionStart *= 2;
mSelectionEnd *= 2;
mHeightsAtThisZoomLevel = null;
int offsetCenter = mOffset + getMeasuredWidth() / 2;
offsetCenter *= 2;
mOffset = offsetCenter - getMeasuredWidth() / 2;
if (mOffset < 0)
mOffset = 0;
invalidate();
}
}
public boolean canZoomOut() {
return (mZoomLevel < mNumZoomLevels - 1);
}
public void zoomOut() {
if (canZoomOut()) {
mZoomLevel++;
mSelectionStart /= 2;
mSelectionEnd /= 2;
int offsetCenter = mOffset + getMeasuredWidth() / 2;
offsetCenter /= 2;
mOffset = offsetCenter - getMeasuredWidth() / 2;
if (mOffset < 0)
mOffset = 0;
mHeightsAtThisZoomLevel = null;
invalidate();
}
}
public double pixelsToSeconds(int pixels) {
double z = mZoomFactorByZoomLevel[mZoomLevel];
return (pixels * (double)mSamplesPerFrame / (mSampleRate * z));
}
public void setListener(WaveformListener listener) {
mListener = listener;
}
public void recomputeHeights(float density) {
mHeightsAtThisZoomLevel = null;
mDensity = density;
mTimecodePaint.setTextSize((int)(12 * density));
invalidate();
}
protected void drawWaveformLine(Canvas canvas,
int x, int y0, int y1,
Paint paint) {
canvas.drawLine(x, y0, x, y1, paint);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mSoundFile == null)
return;
if (mHeightsAtThisZoomLevel == null)
computeIntsForThisZoomLevel();
DisplayMetrics displaymetrics = getContext().getResources().getDisplayMetrics();
int height = displaymetrics.heightPixels;
int widths = displaymetrics.widthPixels;
// Draw waveform
int measuredWidth = getMeasuredWidth();
int measuredHeight = getMeasuredHeight();
int start = mOffset;
int width = mHeightsAtThisZoomLevel.length - start;
int ctr = measuredHeight / 2;
Log.e("wid",String.valueOf(width));
Log.e("widCal",String.valueOf(mHeightsAtThisZoomLevel.length));
Log.e("widstart",String.valueOf(start));
if (width > measuredWidth)
width = measuredWidth;
Log.e("measured",String.valueOf(measuredWidth));
// Draw grid
double onePixelInSecs = pixelsToSeconds(1);
boolean onlyEveryFiveSecs = (onePixelInSecs > 1.0 / 50.0);
double fractionalSecs = mOffset * onePixelInSecs;
int integerSecs = (int) fractionalSecs;
int i = 0;
while (i < width) {
i++;
fractionalSecs += onePixelInSecs;
int integerSecsNew = (int) fractionalSecs;
if (integerSecsNew != integerSecs) {
integerSecs = integerSecsNew;
if (!onlyEveryFiveSecs || 0 == (integerSecs % 5)) {
canvas.drawLine(i, 0, i, measuredHeight, mGridPaint);
}
}
}
// Draw waveform
for ( i = 0; i < width; i++) {
Paint paint;
if (i + start >= mSelectionStart &&
i + start < mSelectionEnd) {
paint = mSelectedLinePaint;
// paint.setColor(color);
} else {
drawWaveformLine(canvas, ((widths/width)*i), 0, measuredHeight,
mUnselectedBkgndLinePaint);
paint = mUnselectedLinePaint;
}
drawWaveformLine(
canvas, ((widths/width)*i),
ctr - mHeightsAtThisZoomLevel[start + i],
ctr + 1 + mHeightsAtThisZoomLevel[start + i],
paint);
if (i + start == mPlaybackPos) {
canvas.drawLine(i, 0, i, measuredHeight, mPlaybackLinePaint);
}
}
if (mListener != null) {
mListener.waveformDraw();
}
}
private void computeIntsForThisZoomLevel() {
int halfHeight = (getMeasuredHeight() / 2) - 1;
mHeightsAtThisZoomLevel = new int[mLenByZoomLevel[mZoomLevel]];
for (int i = 0; i < mLenByZoomLevel[mZoomLevel]; i++) {
mHeightsAtThisZoomLevel[i] =
(int)(mValuesByZoomLevel[mZoomLevel][i] * halfHeight);
}
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity implements WaveformView.WaveformListener {
WaveformView mWaveformView;
SoundFile mSoundFile;
private float mDensity;
private File mFile;
private String mFilename;
private long mLoadingLastUpdateTime;
boolean mLoadingKeepGoing;
boolean mFinishActivity;
private ProgressDialog mProgressDialog;
String mTitle,mArtist;
private Thread mLoadSoundFileThread;
private Thread mRecordAudioThread;
private Thread mSaveSoundFileThread;
private boolean mIsPlaying;
private SamplePlayer mPlayer;
private String mInfoContent;
private int mWidth;
private int mMaxPos;
private int mStartPos;
private int mEndPos;
private boolean mStartVisible;
private boolean mEndVisible;
private int mLastDisplayedStartPos;
private int mLastDisplayedEndPos;
private int mOffset;
private int mOffsetGoal;
private int mFlingVelocity;
private int mPlayStartMsec;
private int mPlayEndMsec;
private Handler mHandler;
Button pla;
MediaPlayer mediaPlayer;
boolean ismIsPlaying;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pla = (Button)findViewById(R.id.play);
mWaveformView = (WaveformView)findViewById(R.id.waveform);
mWaveformView.setListener(this);
mHandler = new Handler();
Uri uri = Uri.parse("/sdcard/audio_file.mp3");
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
loadGui();
loadFromFile();
}
/**
* Called from both onCreate and onConfigurationChanged
* (if the user switched layouts)
*/
private void loadGui() {
// Inflate our UI from its XML layout description.
setContentView(R.layout.activity_main);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mDensity = metrics.density;
mWaveformView = (WaveformView)findViewById(R.id.waveform);
mWaveformView.setListener(this);
if (mSoundFile != null && !mWaveformView.hasSoundFile()) {
mWaveformView.setSoundFile(mSoundFile);
mWaveformView.recomputeHeights(mDensity);
}
}
private void loadFromFile() {
mFilename = "/sdcard/audio_file.mp3";
mFile = new File(mFilename);
SongMetadataReader metadataReader = new SongMetadataReader(
this, mFilename);
mTitle = metadataReader.mTitle;
mArtist = metadataReader.mArtist;
String titleLabel = mTitle;
if (mArtist != null && mArtist.length() > 0) {
titleLabel += " - " + mArtist;
}
setTitle(titleLabel);
mLoadingLastUpdateTime = getCurrentTime();
mLoadingKeepGoing = true;
mFinishActivity = false;
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setTitle("Loading...");
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
mLoadingKeepGoing = false;
mFinishActivity = true;
}
});
mProgressDialog.show();
final SoundFile.ProgressListener listener =
new SoundFile.ProgressListener() {
public boolean reportProgress(double fractionComplete) {
long now = getCurrentTime();
if (now - mLoadingLastUpdateTime > 100) {
mProgressDialog.setProgress(
(int) (mProgressDialog.getMax() * fractionComplete));
mLoadingLastUpdateTime = now;
}
return mLoadingKeepGoing;
}
};
// Load the sound file in a background thread
mLoadSoundFileThread = new Thread() {
public void run() {
try {
mSoundFile = SoundFile.create(mFile.getAbsolutePath(), listener);
if (mSoundFile == null) {
mProgressDialog.dismiss();
String name = mFile.getName().toLowerCase();
String[] components = name.split("\\.");
String err;
if (components.length < 2) {
err = getResources().getString(
R.string.no_extension_error);
} else {
err = getResources().getString(
R.string.bad_extension_error) + " " +
components[components.length - 1];
}
final String finalErr = err;
Runnable runnable = new Runnable() {
public void run() {
showFinalAlert(new Exception(), finalErr);
}
};
mHandler.post(runnable);
return;
}
mPlayer = new SamplePlayer(mSoundFile);
} catch (final Exception e) {
mProgressDialog.dismiss();
e.printStackTrace();
mInfoContent = e.toString();
runOnUiThread(new Runnable() {
public void run() {
}
});
Runnable runnable = new Runnable() {
public void run() {
showFinalAlert(e, getResources().getText(R.string.read_error));
}
};
mHandler.post(runnable);
return;
}
mProgressDialog.dismiss();
if (mLoadingKeepGoing) {
Runnable runnable = new Runnable() {
public void run() {
finishOpeningSoundFile();
}
};
mHandler.post(runnable);
} else if (mFinishActivity){
MainActivity.this.finish();
}
}
};
mLoadSoundFileThread.start();
}
private void finishOpeningSoundFile() {
mWaveformView.setSoundFile(mSoundFile);
mWaveformView.recomputeHeights(mDensity);
Log.e("sound file",mFilename);
Log.e("sound", String.valueOf(mSoundFile));
}
/**
* Show a "final" alert dialog that will exit the activity
* after the user clicks on the OK button. If an exception
* is passed, it's assumed to be an error condition, and the
* dialog is presented as an error, and the stack trace is
* logged. If there's no exception, it's a success message.
*/
private void showFinalAlert(Exception e, CharSequence message) {
CharSequence title;
if (e != null) {
Log.e("Ringdroid", "Error: " + message);
Log.e("Ringdroid", getStackTrace(e));
title = getResources().getText(R.string.alert_title_failure);
setResult(RESULT_CANCELED, new Intent());
} else {
Log.v("Ringdroid", "Success: " + message);
title = getResources().getText(R.string.alert_title_success);
}
new AlertDialog.Builder(MainActivity.this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(
R.string.alert_ok_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
finish();
}
})
.setCancelable(false)
.show();
}
private void showFinalAlert(Exception e, int messageResourceId) {
showFinalAlert(e, getResources().getText(messageResourceId));
}
#Override
public void waveformTouchStart(float x) {
}
#Override
public void waveformTouchMove(float x) {
}
#Override
public void waveformTouchEnd() {
}
#Override
public void waveformFling(float x) {
}
#Override
public void waveformDraw() {
mWidth = mWaveformView.getMeasuredWidth();
if (mOffsetGoal != mOffset) {
// updateDisplay();
}
else if (mIsPlaying) {
// updateDisplay();
} else if (mFlingVelocity != 0) {
// updateDisplay();
}
}
private long getCurrentTime() {
return System.nanoTime() / 1000000;
}
private String getStackTrace(Exception e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
return writer.toString();
}
public void buttonClick(View view) {
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
mediaPlayer.start();
ismIsPlaying = true;
}
}
In your onDraw(Canvas canvas) add the following lines
if (i + start <= mPlaybackPos) {
Paint mPaint = new Paint(paint);
mPaint.setColor(Color.RED);
drawWaveformLine(
canvas, ((widths/width)*i),
ctr - mHeightsAtThisZoomLevel[start + i],
ctr + 1 + mHeightsAtThisZoomLevel[start + i],
mPaint);
}
add them above the line:
if (i + start == mPlaybackPos) {
And if this works, consider to allocate the Paint-object outside the onDraw() method.

Android Selectable TextViewer SetHighlightedText

I am Using SelectableTextview in my e-book app where i want to highlight any text from the book. The text is being highlighted by SelectableTextViewer class, and i am saving the selected text in database. Now i want when the user open the e-book next time the same text should be highlighted as it is. But there is no method of setting selected text. How can i solve this problem. Please help me
SelectableTextviewer.java
public class SelectableTextViewer extends RelativeLayout {
private ImageView imgStartSelect;
public static int mStartSelect = -1;
private ImageView imgEndSelect;
public static int mEndSelect = -1;
private int mImgWidth = 40;
private int mImgHeight = 50;
private TextView textView;
private View mCurrentControlFocused;
public static interface ISelectableTextViewerListener {
public void updateSelection(SelectableTextViewer selectableTextViewer);
public void endSelectingText(SelectableTextViewer selectableTextViewer,
String selectedText);
public void stopSelectingText(
SelectableTextViewer selectableTextViewer, String selectedText);
}
private ISelectableTextViewerListener selectableTextViewerListener;
public static BackgroundColorSpan spanBackgroundColored;
public void setSelectableTextViewerListener(
ISelectableTextViewerListener selectableTextViewerListener) {
this.selectableTextViewerListener = selectableTextViewerListener;
}
public SelectableTextViewer(Context context) {
super(context);
if (!isInEditMode()) {
this.initControls();
}
}
public SelectableTextViewer(Context context, AttributeSet attrs) {
super(context, attrs);
if (!isInEditMode()) {
this.initControls();
}
}
public SelectableTextViewer(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
if (!isInEditMode()) {
this.initControls();
}
}
private void initControls() {
this.spanBackgroundColored = new BackgroundColorSpan(Color.YELLOW);
this.textView = new TextView(getContext());
this.addView(textView);
this.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
showSelectionControls();
int[] location = { 0, 0 };
getLocationOnScreen(location);
System.out.println("getLocationOnScreen:" + location[0] + "\t"
+ location[1]);
return false;
}
});
this.createImgControllersForSelection();
}
protected void disallowIntercept(Boolean disallowIntercept) {
this.getParent().requestDisallowInterceptTouchEvent(disallowIntercept);
}
protected void createImgControllersForSelection() {
this.imgStartSelect = new ImageView(getContext());
this.imgEndSelect = new ImageView(getContext());
this.imgStartSelect.setImageResource(R.drawable.cursor);
this.imgEndSelect.setImageResource(R.drawable.cursor);
this.addView(imgStartSelect, mImgWidth, mImgHeight);
this.addView(imgEndSelect, mImgWidth, mImgHeight);
OnClickListener onClickForChangeFocus = new OnClickListener() {
#Override
public void onClick(View v) {
mCurrentControlFocused = v;
}
};
this.imgEndSelect.setOnClickListener(onClickForChangeFocus);
this.imgStartSelect.setOnClickListener(onClickForChangeFocus);
OnTouchListener onTouchSelectionControl = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
disallowIntercept(true);
mCurrentControlFocused = v;
int eid = event.getAction();
switch (eid) {
case MotionEvent.ACTION_MOVE:
int[] location = { 0, 0 };
getLocationOnScreen(location);
LayoutParams mParams = (LayoutParams) v
.getLayoutParams();
int x = (int) event.getRawX();
int y = (int) event.getRawY();
// + insideScrollView.getScrollY();
mParams.leftMargin = x - mImgWidth / 2 - location[0];
if (x <= 0) {
mParams.leftMargin = mImgWidth;
} else if (x > (getMeasuredWidth() - mImgWidth)) {
mParams.leftMargin = getMeasuredWidth() - mImgWidth;
}
// TODO Must calculate all padding control
mParams.topMargin = (int) (y - (location[1] + mImgHeight * 1.5f));
if (mParams.topMargin <= 1) {
mParams.topMargin = 1;
}
v.setLayoutParams(mParams);
updateSelectionByMovementImgControls(mParams.leftMargin,
mParams.topMargin);
break;
case MotionEvent.ACTION_UP:
if (selectableTextViewerListener != null) {
selectableTextViewerListener.endSelectingText(
SelectableTextViewer.this, getSelectedText());
}
break;
default:
disallowIntercept(false);
break;
}
return true;
}
};
this.imgEndSelect.setOnTouchListener(onTouchSelectionControl);
this.imgStartSelect.setOnTouchListener(onTouchSelectionControl);
this.imgEndSelect.setVisibility(View.GONE);
this.imgStartSelect.setVisibility(View.GONE);
}
public void updateSelectionByMovementImgControls(int x, int y) {
if (mCurrentControlFocused.equals(imgStartSelect)) {
this.mStartSelect = getOffsetByCoordinates(x + mImgWidth / 2, y);
} else if (mCurrentControlFocused.equals(imgEndSelect)) {
this.mEndSelect = getOffsetByCoordinates(x + mImgWidth / 2, y);
}
updateSelectionSpan();
}
protected Layout updateSelectionSpan() {
Layout retLayout = this.textView.getLayout();
if (this.mStartSelect > -1 && this.mEndSelect > -1) {
if (this.mStartSelect > this.mEndSelect) {
int temp = mEndSelect;
this.mEndSelect = mStartSelect;
this.mStartSelect = temp;
showSelectionControls();
}
SpannedString spannable = (SpannedString) this.textView.getText();
SpannableStringBuilder ssb = new SpannableStringBuilder(spannable);
ssb.removeSpan(this.spanBackgroundColored);
ssb.setSpan(this.spanBackgroundColored, this.mStartSelect,
this.mEndSelect, Spannable.SPAN_USER);
this.textView.setText(ssb);
this.textView.requestLayout();
if (this.selectableTextViewerListener != null) {
this.selectableTextViewerListener.updateSelection(this);
}
}
return retLayout;
}
protected void showSelectionControls() {
if (this.mStartSelect > -1 && this.mEndSelect > -1) {
Layout layout = updateSelectionSpan();
Rect parentTextViewRect = new Rect();
LayoutParams startLP = (LayoutParams) this.imgStartSelect
.getLayoutParams();
float xStart = layout.getPrimaryHorizontal(this.mStartSelect)
- mImgWidth / 2;
float yStart = layout.getLineBounds(
layout.getLineForOffset(this.mStartSelect),
parentTextViewRect);
startLP.setMargins((int) xStart, (int) yStart, -1, -1);
this.imgStartSelect.setLayoutParams(startLP);
this.imgStartSelect.setVisibility(View.VISIBLE);
LayoutParams endLP = (LayoutParams) this.imgEndSelect
.getLayoutParams();
float xEnd = layout.getPrimaryHorizontal(this.mEndSelect)
- mImgWidth / 2;
float yEnd = layout.getLineBounds(
layout.getLineForOffset(this.mEndSelect),
parentTextViewRect);
endLP.setMargins((int) xEnd, (int) yEnd, -1, -1);
this.imgEndSelect.setLayoutParams(endLP);
this.imgEndSelect.setVisibility(View.VISIBLE);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (this.imgStartSelect != null) {
if (this.imgStartSelect.getVisibility() == View.GONE) {
this.onTouchDownCalcSelections(event);
disallowIntercept(false);
} else {
this.stopSelecting();
}
}
} else {
this.disallowIntercept(false);
}
return super.onTouchEvent(event);
}
private void hideSelectionControls() {
this.imgStartSelect.setVisibility(View.GONE);
this.imgEndSelect.setVisibility(View.GONE);
}
private int getOffsetByCoordinates(int x, int y) {
int retOffset = -1;
Layout layout = this.textView.getLayout();
if (layout != null) {
int line = layout.getLineForVertical(y);
retOffset = layout.getOffsetForHorizontal(line, x);
}
return retOffset;
}
private void onTouchDownCalcSelections(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
this.mStartSelect = getOffsetByCoordinates(x, y);
if (this.mStartSelect > -1) {
// Calculate text end
String tempStr = this.textView.getText().toString();
tempStr = tempStr.substring(this.mStartSelect);
Pattern pt = Pattern.compile("\\s");
Matcher mt = pt.matcher(tempStr);
if (mt.find()) {
String match = mt.group(0);
tempStr = tempStr.substring(0, tempStr.indexOf(match));
}
this.mEndSelect = this.mStartSelect + tempStr.length();
}
}
public void setText(SpannableStringBuilder builder) {
this.textView.setText(builder);
}
public ImageView getImgEndSelect() {
return imgEndSelect;
}
public ImageView getImgStartSelect() {
return imgStartSelect;
}
/**
* For this all doing
*
* #return
*/
public String getSelectedText() {
String retSelectedString = null;
if (this.mStartSelect > -1 && this.mEndSelect > -1) {
retSelectedString = this.textView.getText()
.subSequence(this.mStartSelect, this.mEndSelect).toString();
}
return retSelectedString;
}
/**
* Hides cursors and clears
*
* #return
*/
public void stopSelecting() {
this.hideSelectionControls();
SpannedString spannable = (SpannedString) this.textView.getText();
SpannableStringBuilder ssb = new SpannableStringBuilder(spannable);
ssb.removeSpan(this.spanBackgroundColored);
this.setText(ssb);
if (selectableTextViewerListener != null) {
selectableTextViewerListener.stopSelectingText(
SelectableTextViewer.this, getSelectedText());
}
}
}
you have to this method as re-use, customize this method as per your use. this is just a concept.
// text comes from textview.gettext or database text and invalidate the view.
protected Layout updateSelectionSpan(Strint text) {
Layout retLayout = this.textView.getLayout();
if (this.mStartSelect > -1 && this.mEndSelect > -1) {
if (this.mStartSelect > this.mEndSelect) {
int temp = mEndSelect;
this.mEndSelect = mStartSelect;
this.mStartSelect = temp;
showSelectionControls();
}
SpannedString spannable = (SpannedString) text;
SpannableStringBuilder ssb = new SpannableStringBuilder(spannable);
ssb.removeSpan(this.spanBackgroundColored);
ssb.setSpan(this.spanBackgroundColored, this.mStartSelect,
this.mEndSelect, Spannable.SPAN_USER);
this.textView.setText(ssb);
this.textView.requestLayout();
if (this.selectableTextViewerListener != null) {
this.selectableTextViewerListener.updateSelection(this);
}
}
return retLayout;
}

Folding animation in Both Horizontal / Vertical direction for multiple Images using ImageView

I want make fold animation in both horizontal & vertical and i followed the below link for (DevBytes) for making folding animation.However this works for only for single image. How to make it to work for multiple Image Folding one by one (By swiping and autoplay)
Folding Layout class:
public class FoldingLayout extends ViewGroup {
public static enum Orientation {
VERTICAL,
HORIZONTAL
}
private final String FOLDING_VIEW_EXCEPTION_MESSAGE = "Folding Layout can only 1 child at " +
"most";
private final float SHADING_ALPHA = 0.8f;
private final float SHADING_FACTOR = 0.5f;
private final int DEPTH_CONSTANT = 1500;
private final int NUM_OF_POLY_POINTS = 8;
private Rect[] mFoldRectArray;
private Matrix [] mMatrix;
private Orientation mOrientation = Orientation.HORIZONTAL;
private float mAnchorFactor = 0;
private float mFoldFactor = 0;
private int mNumberOfFolds = 2;
private boolean mIsHorizontal = true;
private int mOriginalWidth = 0;
private int mOriginalHeight = 0;
private float mFoldMaxWidth = 0;
private float mFoldMaxHeight = 0;
private float mFoldDrawWidth = 0;
private float mFoldDrawHeight = 0;
private boolean mIsFoldPrepared = false;
private boolean mShouldDraw = true;
private Paint mSolidShadow;
private Paint mGradientShadow;
private LinearGradient mShadowLinearGradient;
private Matrix mShadowGradientMatrix;
private float [] mSrc;
private float [] mDst;
private OnFoldListener mFoldListener;
private float mPreviousFoldFactor = 0;
private Bitmap mFullBitmap;
private Rect mDstRect;
public FoldingLayout(Context context) {
super(context);
}
public FoldingLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FoldingLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected boolean addViewInLayout(View child, int index, LayoutParams params,
boolean preventRequestLayout) {
throwCustomException(getChildCount());
boolean returnValue = super.addViewInLayout(child, index, params, preventRequestLayout);
return returnValue;
}
#Override
public void addView(View child, int index, LayoutParams params) {
throwCustomException(getChildCount());
super.addView(child, index, params);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
View child = getChildAt(0);
measureChild(child,widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
View child = getChildAt(0);
child.layout(0, 0, child.getMeasuredWidth(), child.getMeasuredHeight());
updateFold();
}
private class NumberOfFoldingLayoutChildrenException extends RuntimeException {
public NumberOfFoldingLayoutChildrenException(String message) {
super(message);
}
}
private void throwCustomException (int numOfChildViews) {
if (numOfChildViews == 1) {
throw new NumberOfFoldingLayoutChildrenException(FOLDING_VIEW_EXCEPTION_MESSAGE);
}
}
public void setFoldListener(OnFoldListener foldListener) {
mFoldListener = foldListener;
}
public void setFoldFactor(float foldFactor) {
if (foldFactor != mFoldFactor) {
mFoldFactor = foldFactor;
calculateMatrices();
invalidate();
}
}
public void setOrientation(Orientation orientation) {
if (orientation != mOrientation) {
mOrientation = orientation;
updateFold();
}
}
public void setAnchorFactor(float anchorFactor) {
if (anchorFactor != mAnchorFactor) {
mAnchorFactor = anchorFactor;
updateFold();
}
}
public void setNumberOfFolds(int numberOfFolds) {
if (numberOfFolds != mNumberOfFolds) {
mNumberOfFolds = numberOfFolds;
updateFold();
}
}
public float getAnchorFactor() {
return mAnchorFactor;
}
public Orientation getOrientation() {
return mOrientation;
}
public float getFoldFactor() {
return mFoldFactor;
}
public int getNumberOfFolds() {
return mNumberOfFolds;
}
private void updateFold() {
prepareFold(mOrientation, mAnchorFactor, mNumberOfFolds);
calculateMatrices();
invalidate();
}
private void prepareFold(Orientation orientation, float anchorFactor, int numberOfFolds) {
mSrc = new float[NUM_OF_POLY_POINTS];
mDst = new float[NUM_OF_POLY_POINTS];
mDstRect = new Rect();
mFoldFactor = 0;
mPreviousFoldFactor = 0;
mIsFoldPrepared = false;
mSolidShadow = new Paint();
mGradientShadow = new Paint();
mOrientation = orientation;
mIsHorizontal = (orientation == Orientation.HORIZONTAL);
if (mIsHorizontal) {
mShadowLinearGradient = new LinearGradient(0, 0, SHADING_FACTOR, 0, Color.BLACK,
Color.TRANSPARENT, TileMode.CLAMP);
} else {
mShadowLinearGradient = new LinearGradient(0, 0, 0, SHADING_FACTOR, Color.BLACK,
Color.TRANSPARENT, TileMode.CLAMP);
}
mGradientShadow.setStyle(Style.FILL);
mGradientShadow.setShader(mShadowLinearGradient);
mShadowGradientMatrix = new Matrix();
mAnchorFactor = anchorFactor;
mNumberOfFolds = numberOfFolds;
mOriginalWidth = getMeasuredWidth();
mOriginalHeight = getMeasuredHeight();
mFoldRectArray = new Rect[mNumberOfFolds];
mMatrix = new Matrix [mNumberOfFolds];
for (int x = 0; x < mNumberOfFolds; x++) {
mMatrix[x] = new Matrix();
}
int h = mOriginalHeight;
int w = mOriginalWidth;
if (FoldingLayoutActivity.IS_JBMR2) {
mFullBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(mFullBitmap);
getChildAt(0).draw(canvas);
}
int delta = Math.round(mIsHorizontal ? ((float) w) / ((float) mNumberOfFolds) :
((float) h) /((float) mNumberOfFolds));
for (int x = 0; x < mNumberOfFolds; x++) {
if (mIsHorizontal) {
int deltap = (x + 1) * delta > w ? w - x * delta : delta;
mFoldRectArray[x] = new Rect(x * delta, 0, x * delta + deltap, h);
} else {
int deltap = (x + 1) * delta > h ? h - x * delta : delta;
mFoldRectArray[x] = new Rect(0, x * delta, w, x * delta + deltap);
}
}
if (mIsHorizontal) {
mFoldMaxHeight = h;
mFoldMaxWidth = delta;
} else {
mFoldMaxHeight = delta;
mFoldMaxWidth = w;
}
mIsFoldPrepared = true;
}
private void calculateMatrices() {
mShouldDraw = true;
if (!mIsFoldPrepared) {
return;
}
if (mFoldFactor == 1) {
mShouldDraw = false;
return;
}
if (mFoldFactor == 0 && mPreviousFoldFactor > 0) {
mFoldListener.onEndFold();
}
if (mPreviousFoldFactor == 0 && mFoldFactor > 0) {
mFoldListener.onStartFold();
}
mPreviousFoldFactor = mFoldFactor;
for (int x = 0; x < mNumberOfFolds; x++) {
mMatrix[x].reset();
}
float cTranslationFactor = 1 - mFoldFactor;
float translatedDistance = mIsHorizontal ? mOriginalWidth * cTranslationFactor :
mOriginalHeight * cTranslationFactor;
float translatedDistancePerFold = Math.round(translatedDistance / mNumberOfFolds);
mFoldDrawWidth = mFoldMaxWidth < translatedDistancePerFold ?
translatedDistancePerFold : mFoldMaxWidth;
mFoldDrawHeight = mFoldMaxHeight < translatedDistancePerFold ?
translatedDistancePerFold : mFoldMaxHeight;
float translatedDistanceFoldSquared = translatedDistancePerFold * translatedDistancePerFold;
float depth = mIsHorizontal ?
(float)Math.sqrt((double)(mFoldDrawWidth * mFoldDrawWidth -
translatedDistanceFoldSquared)) :
(float)Math.sqrt((double)(mFoldDrawHeight * mFoldDrawHeight -
translatedDistanceFoldSquared));
float scaleFactor = DEPTH_CONSTANT / (DEPTH_CONSTANT + depth);
float scaledWidth, scaledHeight, bottomScaledPoint, topScaledPoint, rightScaledPoint,
leftScaledPoint;
if (mIsHorizontal) {
scaledWidth = mFoldDrawWidth * cTranslationFactor;
scaledHeight = mFoldDrawHeight * scaleFactor;
} else {
scaledWidth = mFoldDrawWidth * scaleFactor;
scaledHeight = mFoldDrawHeight * cTranslationFactor;
}
topScaledPoint = (mFoldDrawHeight - scaledHeight) / 2.0f;
bottomScaledPoint = topScaledPoint + scaledHeight;
leftScaledPoint = (mFoldDrawWidth - scaledWidth) / 2.0f;
rightScaledPoint = leftScaledPoint + scaledWidth;
float anchorPoint = mIsHorizontal ? mAnchorFactor * mOriginalWidth :
mAnchorFactor * mOriginalHeight;
/* The fold along which the anchor point is located. */
float midFold = mIsHorizontal ? (anchorPoint / mFoldDrawWidth) : anchorPoint /
mFoldDrawHeight;
mSrc[0] = 0;
mSrc[1] = 0;
mSrc[2] = 0;
mSrc[3] = mFoldDrawHeight;
mSrc[4] = mFoldDrawWidth;
mSrc[5] = 0;
mSrc[6] = mFoldDrawWidth;
mSrc[7] = mFoldDrawHeight;
for (int x = 0; x < mNumberOfFolds; x++) {
boolean isEven = (x % 2 == 0);
if (mIsHorizontal) {
mDst[0] = (anchorPoint > x * mFoldDrawWidth) ? anchorPoint + (x - midFold) *
scaledWidth : anchorPoint - (midFold - x) * scaledWidth;
mDst[1] = isEven ? 0 : topScaledPoint;
mDst[2] = mDst[0];
mDst[3] = isEven ? mFoldDrawHeight: bottomScaledPoint;
mDst[4] = (anchorPoint > (x + 1) * mFoldDrawWidth) ? anchorPoint + (x + 1 - midFold)
* scaledWidth : anchorPoint - (midFold - x - 1) * scaledWidth;
mDst[5] = isEven ? topScaledPoint : 0;
mDst[6] = mDst[4];
mDst[7] = isEven ? bottomScaledPoint : mFoldDrawHeight;
} else {
mDst[0] = isEven ? 0 : leftScaledPoint;
mDst[1] = (anchorPoint > x * mFoldDrawHeight) ? anchorPoint + (x - midFold) *
scaledHeight : anchorPoint - (midFold - x) * scaledHeight;
mDst[2] = isEven ? leftScaledPoint: 0;
mDst[3] = (anchorPoint > (x + 1) * mFoldDrawHeight) ? anchorPoint + (x + 1 -
midFold) * scaledHeight : anchorPoint - (midFold - x - 1) * scaledHeight;
mDst[4] = isEven ? mFoldDrawWidth : rightScaledPoint;
mDst[5] = mDst[1];
mDst[6] = isEven ? rightScaledPoint : mFoldDrawWidth;
mDst[7] = mDst[3];
}
for (int y = 0; y < 8; y ++) {
mDst[y] = Math.round(mDst[y]);
}
int alpha = (int) (mFoldFactor * 255 * SHADING_ALPHA);
mSolidShadow.setColor(Color.argb(alpha, 0, 0, 0));
if (mIsHorizontal) {
mShadowGradientMatrix.setScale(mFoldDrawWidth, 1);
mShadowLinearGradient.setLocalMatrix(mShadowGradientMatrix);
} else {
mShadowGradientMatrix.setScale(1, mFoldDrawHeight);
mShadowLinearGradient.setLocalMatrix(mShadowGradientMatrix);
}
mGradientShadow.setShader(mShadowLinearGradient);
mGradientShadow.setAlpha(alpha);
}
#Override
protected void dispatchDraw(Canvas canvas) {
if (!mIsFoldPrepared || mFoldFactor == 0) {
super.dispatchDraw(canvas);
return;
}
if (!mShouldDraw) {
return;
}
for (int x = 0; x < mNumberOfFolds; x++) {
src = mFoldRectArray[x];
canvas.concat(mMatrix[x]);
if (FoldingLayoutActivity.IS_JBMR2) {
mDstRect.set(0, 0, src.width(), src.height());
canvas.drawBitmap(mFullBitmap, src, mDstRect, null);
} else {
canvas.clipRect(0, 0, src.right - src.left, src.bottom - src.top);
if (mIsHorizontal) {
canvas.translate(-src.left, 0);
} else {
canvas.translate(0, -src.top);
}
super.dispatchDraw(canvas);
if (mIsHorizontal) {
canvas.translate(src.left, 0);
} else {
canvas.translate(0, src.top);
}
}
if (x % 2 == 0) {
canvas.drawRect(0, 0, mFoldDrawWidth, mFoldDrawHeight, mSolidShadow);
} else {
canvas.drawRect(0, 0, mFoldDrawWidth, mFoldDrawHeight, mGradientShadow);
}
canvas.restore();
}
}
}
// onFoldListener
public interface OnFoldListener {
public void onStartFold();
public void onEndFold();
}
// FoldingLayoutActivity
public class FoldingLayoutActivity extends Activity {
private final int ANTIALIAS_PADDING = 1;
private final int FOLD_ANIMATION_DURATION = 1000;
static final boolean IS_JBMR2 = Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN_MR2;
private FoldingLayout mFoldLayout;
private SeekBar mAnchorSeekBar;
private Orientation mOrientation = Orientation.HORIZONTAL;
private int mTranslation = 0;
private int mNumberOfFolds = 2;
private int mParentPositionY = -1;
private int mTouchSlop = -1;
private float mAnchorFactor = 0;
private boolean mDidLoadSpinner = true;
private boolean mDidNotStartScroll = true;
private boolean mIsCameraFeed = false;
private boolean mIsSepiaOn = true;
private GestureDetector mScrollGestureDetector;
private ItemSelectedListener mItemSelectedListener;
private Camera mCamera;
private TextureView mTextureView;
private ImageView mImageView;
private Paint mSepiaPaint;
private Paint mDefaultPaint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fold);
mImageView = (ImageView)findViewById(R.id.image_view);
mImageView.setPadding(ANTIALIAS_PADDING, ANTIALIAS_PADDING, ANTIALIAS_PADDING,
ANTIALIAS_PADDING);
mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
mImageView.setImageDrawable(getResources().getDrawable(R.drawable.image));
mTextureView = new TextureView(this);
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
mAnchorSeekBar = (SeekBar)findViewById(R.id.anchor_seek_bar);
mFoldLayout = (FoldingLayout)findViewById(R.id.fold_view);
mFoldLayout.setBackgroundColor(Color.BLACK);
mFoldLayout.setFoldListener(mOnFoldListener);
mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop();
mAnchorSeekBar.setOnSeekBarChangeListener(mSeekBarChangeListener);
mScrollGestureDetector = new GestureDetector(this, new ScrollGestureDetector());
mItemSelectedListener = new ItemSelectedListener();
mDefaultPaint = new Paint();
mSepiaPaint = new Paint();
ColorMatrix m1 = new ColorMatrix();
ColorMatrix m2 = new ColorMatrix();
m1.setSaturation(0);
m2.setScale(1f, .95f, .82f, 1.0f);
m1.setConcat(m2, m1);
mSepiaPaint.setColorFilter(new ColorMatrixColorFilter(m1));
}
private OnFoldListener mOnFoldListener =
new OnFoldListener() {
#Override
public void onStartFold() {
if (mIsSepiaOn) {
setSepiaLayer(mFoldLayout.getChildAt(0), true);
}
}
#Override
public void onEndFold() {
setSepiaLayer(mFoldLayout.getChildAt(0), false);
}
};
private void setSepiaLayer (View view, boolean isSepiaLayerOn) {
if (!IS_JBMR2) {
if (isSepiaLayerOn) {
view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
view.setLayerPaint(mSepiaPaint);
} else {
view.setLayerPaint(mDefaultPaint);
}
}
}
private TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView
.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i2) {
mCamera = Camera.open();
if (mCamera == null && Camera.getNumberOfCameras() > 1) {
mCamera = mCamera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
}
if (mCamera == null) {
return;
}
try {
mCamera.setPreviewTexture(surfaceTexture);
mCamera.setDisplayOrientation(90);
mCamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i2) {
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
}
return true;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
}
};
private SeekBar.OnSeekBarChangeListener mSeekBarChangeListener = new SeekBar
.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mTranslation = 0;
mAnchorFactor = ((float)mAnchorSeekBar.getProgress())/100.0f;
mFoldLayout.setAnchorFactor(mAnchorFactor);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (IS_JBMR2) {
getMenuInflater().inflate(R.menu.fold_with_bug, menu);
} else {
getMenuInflater().inflate(R.menu.fold, menu);
}
Spinner s = (Spinner) menu.findItem(R.id.num_of_folds).getActionView();
s.setOnItemSelectedListener(mItemSelectedListener);
return true;
}
#Override
public void onWindowFocusChanged (boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
int[] loc = new int[2];
mFoldLayout.getLocationOnScreen(loc);
mParentPositionY = loc[1];
}
#Override
public boolean onTouchEvent(MotionEvent me) {
return mScrollGestureDetector.onTouchEvent(me);
}
#Override
public boolean onOptionsItemSelected (MenuItem item) {
switch(item.getItemId()) {
case R.id.animate_fold:
animateFold();
break;
case R.id.toggle_orientation:
mOrientation = (mOrientation == Orientation.HORIZONTAL) ? Orientation.VERTICAL :
Orientation.HORIZONTAL;
item.setTitle((mOrientation == Orientation.HORIZONTAL) ? R.string.vertical :
R.string.horizontal);
mTranslation = 0;
mFoldLayout.setOrientation(mOrientation);
break;
case R.id.camera_feed:
mIsCameraFeed = !mIsCameraFeed;
item.setTitle(mIsCameraFeed ? R.string.static_image : R.string.camera_feed);
item.setChecked(mIsCameraFeed);
if (mIsCameraFeed) {
mFoldLayout.removeView(mImageView);
mFoldLayout.addView(mTextureView, new ViewGroup.LayoutParams(
mFoldLayout.getWidth(), mFoldLayout.getHeight()));
} else {
mFoldLayout.removeView(mTextureView);
mFoldLayout.addView(mImageView, new ViewGroup.LayoutParams(
mFoldLayout.getWidth(), mFoldLayout.getHeight()));
}
mTranslation = 0;
break;
case R.id.sepia:
mIsSepiaOn = !mIsSepiaOn;
item.setChecked(!mIsSepiaOn);
if (mIsSepiaOn && mFoldLayout.getFoldFactor() != 0) {
setSepiaLayer(mFoldLayout.getChildAt(0), true);
} else {
setSepiaLayer(mFoldLayout.getChildAt(0), false);
}
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
public void animateFold ()
{
float foldFactor = mFoldLayout.getFoldFactor();
ObjectAnimator animator = ObjectAnimator.ofFloat(mFoldLayout, "foldFactor", foldFactor, 1);
animator.setRepeatMode(ValueAnimator.REVERSE);
animator.setRepeatCount(1);
animator.setDuration(FOLD_ANIMATION_DURATION);
animator.setInterpolator(new AccelerateInterpolator());
animator.start();
}
private class ItemSelectedListener implements OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
mNumberOfFolds = Integer.parseInt(parent.getItemAtPosition(pos).toString());
if (mDidLoadSpinner) {
mDidLoadSpinner = false;
} else {
mTranslation = 0;
mFoldLayout.setNumberOfFolds(mNumberOfFolds);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
private class ScrollGestureDetector extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onDown (MotionEvent e) {
mDidNotStartScroll = true;
return true;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
int touchSlop = 0;
float factor;
if (mOrientation == Orientation.VERTICAL) {
factor = Math.abs((float)(mTranslation) / (float)(mFoldLayout.getHeight()));
if (e2.getY() - mParentPositionY <= mFoldLayout.getHeight()
&& e2.getY() - mParentPositionY >= 0) {
if ((e2.getY() - mParentPositionY) > mFoldLayout.getHeight() * mAnchorFactor) {
mTranslation -= (int)distanceY;
touchSlop = distanceY < 0 ? -mTouchSlop : mTouchSlop;
} else {
mTranslation += (int)distanceY;
touchSlop = distanceY < 0 ? mTouchSlop : -mTouchSlop;
}
mTranslation = mDidNotStartScroll ? mTranslation + touchSlop : mTranslation;
if (mTranslation < -mFoldLayout.getHeight()) {
mTranslation = -mFoldLayout.getHeight();
}
}
} else {
factor = Math.abs(((float)mTranslation) / ((float) mFoldLayout.getWidth()));
if (e2.getRawX() > mFoldLayout.getWidth() * mAnchorFactor) {
mTranslation -= (int)distanceX;
touchSlop = distanceX < 0 ? -mTouchSlop : mTouchSlop;
} else {
mTranslation += (int)distanceX;
touchSlop = distanceX < 0 ? mTouchSlop : -mTouchSlop;
}
mTranslation = mDidNotStartScroll ? mTranslation + touchSlop : mTranslation;
if (mTranslation < -mFoldLayout.getWidth()) {
mTranslation = -mFoldLayout.getWidth();
}
}
mDidNotStartScroll = false;
if (mTranslation > 0) {
mTranslation = 0;
}
mFoldLayout.setFoldFactor(factor);
return true;
}
}
}
//activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.android.foldinglayout.FoldingLayout
android:layout_weight="1"
android:id="#+id/fold_view"
android:layout_width="match_parent"
android:layout_height="0dp">
<ImageView
android:id="#+id/image_view"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:scaleType="fitXY"/>
</com.example.android.foldinglayout.FoldingLayout>
<SeekBar
android:id="#+id/anchor_seek_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"/>
</LinearLayout>

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.

aplication crash and take me this errors

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 ;)

Categories

Resources