App Crashes When Saving Shared Preference for a CustomView [duplicate]

Home / Uncategorized / App Crashes When Saving Shared Preference for a CustomView [duplicate]

Question:
This question is an exact duplicate of:App Crashes When Trying to save position of custom view as SharedPreference

Trying to implement a movable custom view like a crop view to specify the area of detection in a motion detection application. The bitmaps for the motion detection should be created according to the height and width of the custom view as the user sets it. The view is inflating properly, but the app crashes as soon as custom view is moved. Whether it has something to do with the way the state of box is saved as preference when it is moved? What are the changes should be made in the code?

Logcat
08-15 10:34:00.166 5884-6969/com.md.areadectest I/MotionDetectionActivity: Saving.. previous=android.graphics.Bitmap@e8b4fcb original=android.graphics.Bitmap@5a303a8 bitmap=android.graphics.Bitmap@d75eec1
08-15 10:34:00.279 5884-5884/com.md.areadectest D/ViewRootImpl@47122fb[MotionDetectionActivity]: ViewPostImeInputStage processPointer 1
08-15 10:34:00.284 5884-5884/com.md.areadectest E/InputEventReceiver: Exception dispatching input event.
08-15 10:34:00.284 5884-5884/com.md.areadectest E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
08-15 10:34:00.291 5884-5884/com.md.areadectest E/MessageQueue-JNI: java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.String android.content.Context.getPackageName()’ on a null object reference
at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:499)
at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:488)
at com.md.areadectest.SharedPrefsUtils.setStringPreference(SharedPrefsUtils.java:43)
at com.md.areadectest.AreaDetectorView.onTouchEvent(AreaDetectorView.java:357)
at android.view.View.dispatchTouchEvent(View.java:10731)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2859)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2535)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2865)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2550)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2865)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2550)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2865)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2550)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2865)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2550)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2865)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2550)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2865)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2550)
at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:509)
at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1863)
at android.app.Activity.dispatchTouchEvent(Activity.java:3226)
at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:471)
at android.view.View.dispatchPointerEvent(View.java:10960)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:5075)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4927)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4458)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4511)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4477)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4610)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4485)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4667)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4458)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4511)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4477)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4485)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4458)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6960)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6899)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6860)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:7070)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:323)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
08-15 10:34:00.292 5884-5884/com.md.areadectest D/AndroidRuntime: Shutting down VM
08-15 10:34:00.294 5884-5884/com.md.areadectest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.md.areadectest, PID: 5884
java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.String android.content.Context.getPackageName()’ on a null object reference
at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:499)
at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:488)
at com.md.areadectest.SharedPrefsUtils.setStringPreference(SharedPrefsUtils.java:43)
at com.md.areadectest.AreaDetectorView.onTouchEvent(AreaDetectorView.java:357)
at android.view.View.dispatchTouchEvent(View.java:10731)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2859)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2535)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2865)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2550)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2865)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2550)

AreaDetectorView.java
public class AreaDetectorView extends LinearLayout {

public static int Width;
public static int Height;

private static Paint BoxPaint = null;
private static Paint TextPaint = null;
private static Paint ArrowPaint = null;
private static Path mPath = null;
private static Rect mRect = null;
private static int lastX, lastY = 0;
private static boolean mBoxTouched = false;
private static boolean mArrowTouched = false;
private static Context mContext;
private static int ArrowWidth = 0;
private static Paint BoxPaint2 = null;

public AreaDetectorView(Context context) {
super(context);
mContext = context;
}
//attrs was not there
public AreaDetectorView(Context context, AttributeSet attrs) {
super(context,attrs);
mContext = context;
// TODO Auto-generated constructor stub
if (!this.getRootView().isInEditMode()) {
ArrowWidth =GetDisplayPixel(context, 30);
}

//InitDetectionArea();

InitMemberVariables();
setWillNotDraw(false);
}
public static int GetDisplayPixel(Context paramContext, int paramInt)
{
return (int)(paramInt * paramContext.getResources().getDisplayMetrics().density + 0.5F);
}

public static void InitMemberVariables() {
if (BoxPaint == null) {
BoxPaint = new Paint();
BoxPaint.setAntiAlias(true);
BoxPaint.setStrokeWidth(2.0f);
//BoxPaint.setStyle(Style.STROKE);
BoxPaint.setStyle(Style.FILL_AND_STROKE);
BoxPaint.setColor(ContextCompat.getColor(mContext, R.color.bwff_60));
}
if (ArrowPaint == null) {
ArrowPaint = new Paint();
ArrowPaint.setAntiAlias(true);
ArrowPaint.setColor(ContextCompat.getColor(mContext,R.color.redDD));
ArrowPaint.setStyle(Style.FILL_AND_STROKE);
}
if (TextPaint == null) {
TextPaint = new Paint();
TextPaint.setColor(ContextCompat.getColor(mContext,R.color.yellowL));
TextPaint.setTextSize(16);
//txtPaint.setTypeface(lcd);
TextPaint.setStyle(Style.FILL_AND_STROKE);
}
if (mPath == null) {
mPath = new Path();
} else {
mPath.reset();
}
if (mRect == null) {
mRect = new Rect();
}

if (BoxPaint2 == null) {
BoxPaint2 = new Paint();
BoxPaint2.setAntiAlias(true);
BoxPaint2.setStrokeWidth(2.0f);
//BoxPaint.setStyle(Style.STROKE);
BoxPaint2.setStyle(Style.STROKE);
BoxPaint2.setColor(ContextCompat.getColor(mContext,R.color.bwff_9e));
}

}

public static void InitDetectionArea() {
try {
int w = Preferences.DetectionArea.width();
int h = Preferences.DetectionArea.height();
int x = Preferences.DetectionArea.left;
int y = Preferences.DetectionArea.top;

// ver 2.6.0
if (Preferences.DetectionArea.left == 1
&& Preferences.DetectionArea.top == 1
&& Preferences.DetectionArea.right == 1
&& Preferences.DetectionArea.bottom == 1) {

w = Preferences.DisplayWidth / 4;
h = Preferences.DisplayHeight / 3;

// ver 2.5.9
w = Width / 4;
h = Height / 3;

Preferences.DetectorWidth = w; //UtilGeneralHelper.GetDisplayPixel(this, 100);
Preferences.DetectorHeight = h; //UtilGeneralHelper.GetDisplayPixel(this, 100);

x = (Preferences.DisplayWidth / 2) – (w / 2);
y = (Preferences.DisplayHeight / 2) – (h / 2);

// ver 2.5.9
x = (Width / 2) – (w / 2);
y = (Height / 2) – (h / 2);

}

//Preferences.DetectionArea = new Rect(x, x, x + Preferences.DetectorWidth, x + Preferences.DetectorHeight);
Preferences.DetectionArea = new Rect(x, y, x + w, y + h);

Preferences.gDetectionBitmapInt = new int[Preferences.DetectionArea.width() * Preferences.DetectionArea.height()];
Preferences.gDetectionBitmapIntPrev = new int[Preferences.DetectionArea.width() * Preferences.DetectionArea.height()];

} catch (Exception e) {
e.printStackTrace();
}
}

public static void SetDetectionArea(int x, int y, int w, int h) {
try {
Preferences.DetectionArea = new Rect(x, y, w, h);

} catch (Exception e) {
e.printStackTrace();
}
}

private void DrawAreaBox(Canvas canvas) {
try {
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
protected void dispatchDraw(Canvas canvas) {
try {
if (this.getRootView().isInEditMode()) {
super.dispatchDraw(canvas);
return;
}

//canvas.save(Canvas.MATRIX_SAVE_FLAG);
//Preferences.DetectionAreaOrient = UtilGeneralHelper.GetDetectRectByOrientation();

canvas.drawColor(0);
mPath.reset();

canvas.drawRect(Preferences.DetectionArea, BoxPaint);

mPath.moveTo(Preferences.DetectionArea.right – ArrowWidth, Preferences.DetectionArea.bottom);
mPath.lineTo(Preferences.DetectionArea.right, Preferences.DetectionArea.bottom – ArrowWidth);
mPath.lineTo(Preferences.DetectionArea.right, Preferences.DetectionArea.bottom);
mPath.lineTo(Preferences.DetectionArea.right – ArrowWidth, Preferences.DetectionArea.bottom);
mPath.close();
canvas.drawPath(mPath, ArrowPaint);

mPath.reset();
//canvas.drawRect(Preferences.DetectionAreaOrient, BoxPaint2);
//canvas.drawRect(Preferences.DetectionAreaOrientPort, BoxPaint2);

TextPaint.setTextSize(16);
//TextPaint.setLetterSpacing(2);

TextPaint.setColor(ContextCompat.getColor(mContext,R.color.bwff));

TextPaint.getTextBounds(getResources().getString(R.string.str_detectarea), 0, 1, mRect);
canvas.drawText(getResources().getString(R.string.str_detectarea),
Preferences.DetectionArea.left + 4,
Preferences.DetectionArea.top + 4 + mRect.height(),
TextPaint);
int recH = mRect.height();

TextPaint.setStrokeWidth(1.2f);
TextPaint.setTextSize(18);
TextPaint.setColor(ContextCompat.getColor(mContext,R.color.redD_9e));
TextPaint.getTextBounds(getResources().getString(R.string.str_dragandmove), 0, 1, mRect);
canvas.drawText(getResources().getString(R.string.str_dragandmove),
Preferences.DetectionArea.left + 4,
Preferences.DetectionArea.top + 20 + mRect.height()*2,
TextPaint);

TextPaint.getTextBounds(getResources().getString(R.string.str_scalearea), 0, 1, mRect);
canvas.drawText(getResources().getString(R.string.str_scalearea),
Preferences.DetectionArea.left + 4,
Preferences.DetectionArea.top + 36 + mRect.height()*3,
TextPaint);

super.dispatchDraw(canvas);
//canvas.restore();
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
protected void onDraw(Canvas canvas) {
try {
super.onDraw(canvas);
invalidate();
} catch (Exception e) {
e.printStackTrace();
} finally {

}
}

@Override
public boolean onTouchEvent(MotionEvent event) {
boolean retValue = true;
int X = (int)event.getX();
int Y = (int)event.getY();

//AppMain.txtLoc.setText(String.valueOf(X) + ", " + String.valueOf(Y));

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:mBoxTouched = TouchedInBoxArea(X, Y);

//AppMain.txtLoc.setText("BoxTouched: " + String.valueOf(mBoxTouched));

if (!mBoxTouched) break;

lastX = X;
lastY = Y;

BoxPaint.setStyle(Style.FILL_AND_STROKE);
BoxPaint.setColor(ContextCompat.getColor(mContext,R.color.redD_9e));

mArrowTouched = TouchedInArrow(X, Y);
//AppMain.txtLoc.setText("ArrowTouched: " + String.valueOf(mBoxTouched));

if (mArrowTouched) {
ArrowPaint.setColor(ContextCompat.getColor(mContext,R.color.bwff_9e));
}

break;

case MotionEvent.ACTION_MOVE:if (!mBoxTouched) break;

int moveX = X – lastX;
int moveY = Y – lastY;

//AppMain.txtLoc.setText("Move X, Y: " + String.valueOf(moveX) + "," + String.valueOf(moveY));
if (!mArrowTouched) {
if (Preferences.DetectionArea.left + moveX < 0) { break; } // if (Preferences.DetectionArea.right + moveX > Preferences.gDisplay.getWidth()) {
// break;
// }
// ver 2.5.9
if (Preferences.DetectionArea.right + moveX > Width) {
break;
}
if (Preferences.DetectionArea.top + moveY < 0) { break; } // if (Preferences.DetectionArea.bottom + moveY > Preferences.gDisplay.getHeight()) {
// break;
// }
// ver 2.5.9
if (Preferences.DetectionArea.bottom + moveY > Height) {
break;
}
}

if (mArrowTouched) {
if ((Preferences.DetectionArea.width() + moveX) < ArrowWidth * 2){ break; } if ((Preferences.DetectionArea.height() + moveY) < ArrowWidth * 2) { break; } Preferences.DetectionArea.right += moveX; Preferences.DetectionArea.bottom += moveY; //Log.i("DBG", "W,H: " + String.valueOf(Preferences.DetectionArea.width()) + "," + String.valueOf(Preferences.DetectionArea.height())); } else { Preferences.DetectionArea.left += moveX; Preferences.DetectionArea.right += moveX; Preferences.DetectionArea.top += moveY; Preferences.DetectionArea.bottom += moveY; } lastX = X; lastY = Y; //AppMain.txtLoc.setText(String.valueOf(Preferences.DetectionArea.left) + ", " + String.valueOf(Preferences.DetectionArea.top)); break; case MotionEvent.ACTION_UP:mBoxTouched = false; mArrowTouched = false; //BoxPaint.setStyle(Style.STROKE); BoxPaint.setStyle(Style.FILL_AND_STROKE); BoxPaint.setColor(ContextCompat.getColor(mContext,R.color.bwff_60)); ArrowPaint.setColor(ContextCompat.getColor(mContext,R.color.redDD)); //AppMain.txtLoc.setText(String.valueOf(Preferences.DetectionArea.left) + ", " + String.valueOf(Preferences.DetectionArea.top)); if (Preferences.DetectionArea.left < 0) { Preferences.DetectionArea.left = 0; } // if (Preferences.DetectionArea.right > Preferences.gDisplay.getWidth()) {
// Preferences.DetectionArea.right = Preferences.gDisplay.getWidth();
// }
// ver 2.5.9
if (Preferences.DetectionArea.right > Width) {
Preferences.DetectionArea.right = Width;
}
if (Preferences.DetectionArea.top < 0) { Preferences.DetectionArea.top = 0; } // if (Preferences.DetectionArea.bottom > Preferences.gDisplay.getHeight()) {
// Preferences.DetectionArea.bottom = Preferences.gDisplay.getHeight();
// }
if (Preferences.DetectionArea.bottom > Height) {
Preferences.DetectionArea.bottom = Height;
}

Preferences.gDetectionBitmapInt = new int[Preferences.DetectionArea.width() * Preferences.DetectionArea.height()];
Preferences.gDetectionBitmapIntPrev = new int[Preferences.DetectionArea.width() * Preferences.DetectionArea.height()];
//Preferences.gDetectionBitmapInt = null;
//Preferences.gDetectionBitmapIntPrev = null;

String area = String.valueOf(Preferences.DetectionArea.left)
+ "," + String.valueOf(Preferences.DetectionArea.top)
+ "," + String.valueOf(Preferences.DetectionArea.right)
+ "," + String.valueOf(Preferences.DetectionArea.bottom);

// UtilGeneralHelper.SavePreferenceSetting(Preferences.gContext, Preferences.PREF_DETECTION_AREA_KEY, area);
SharedPrefsUtils.setStringPreference(Prefe.gContext, Prefe.PREF_DETECTION_AREA_KEY, area);

break;
}

invalidate();
return retValue;
}

private boolean TouchedInBoxArea(int x, int y) {
boolean retValue = false;
try {

if (x > Preferences.DetectionArea.left && x < Preferences.DetectionArea.right) { if (y > Preferences.DetectionArea.top && y < Preferences.DetectionArea.bottom) { retValue = true; } } } catch (Exception e) { e.printStackTrace(); } return retValue; } private boolean TouchedInArrow(int x, int y) { boolean retValue = false; try { if (x > Preferences.DetectionArea.right – ArrowWidth && x < Preferences.DetectionArea.right) { if (y > Preferences.DetectionArea.bottom – ArrowWidth && y < Preferences.DetectionArea.bottom) { retValue = true; } } } catch (Exception e) { e.printStackTrace(); } return retValue; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); setMeasuredDimension(width, height); Width = width; Height = height; InitDetectionArea(); } @Override protected void onFinishInflate() { super.onFinishInflate(); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { // TODO Auto-generated method stub for (int i = 0; i < this.getChildCount()-1; i++){ (this.getChildAt(i)).layout(l, t, r, b); } if (changed) { // check width height if (r != Width || b != Height) { // size does not match } } } } Prefe.java public class Prefe extends Application{ .... public static Rect DetectionArea; public static int DetectorHeight = 0; public static int DetectorWidth = 0; public static final String PREF_DETECTION_AREA_KEY = "pref_detection_area_key"; static { .... DetectionArea = new Rect(1, 1, 1, 1); ... } } SharedPrefsUtils.java final public class SharedPrefsUtils { private SharedPrefsUtils() {} public static boolean setStringPreference(Context context, String key, String value) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); if (preferences != null && !TextUtils.isEmpty(key)) { SharedPreferences.Editor editor = preferences.edit(); editor.putString(key, value); return editor.commit(); } return false; }


Answer:
Change this line
SharedPrefsUtils.setStringPreference(Prefe.gContext, Prefe.PREF_DETECTION_AREA_KEY, area);

with this line:SharedPrefsUtils.setStringPreference(mContext, Prefe.PREF_DETECTION_AREA_KEY, area);
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *