Android Camera Application: Capture button not working? - java

I've been working on this Camera app for a little while now. Basically what I want to do is take a picture(and store it internally), then display that image in the next Activity. The preview works perfectly, but when I hit the Capture button on MainActivity the error "Unfortunately, myApplication has stopped" shows up and the app crashes. AndroidStudio is not giving me any Event Log information either...
Here's the main activity(is something wrong with SendInfo?):
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "File_name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create an instance of Camera
Camera mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
CameraPreview mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Camera mCamera = getCameraInstance();
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
}
//////////////////////
public void sendInfo(View view)
{
Intent intent = new Intent(this,show_image.class);
Uri fileUri = getOutputMediaFileUri(1);
intent.putExtra(EXTRA_MESSAGE, fileUri.toString());
startActivity(intent);
}
/////////////////
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d("Logtag:", "Error creating media file, check storage permissions: "
);
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("Logtag:", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Logtag:", "Error accessing file: " + e.getMessage());
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** A safe way to get an instance of the Camera object. */
public Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
Toast.makeText(getApplicationContext(), "Camera is not available (in use or does not exist)",
Toast.LENGTH_LONG).show();
}
return c; // returns null if camera is unavailable
}
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This locat ion works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("Logtag", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
And here is the second Activity that should be displaying the image...
public class show_image extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String stringURI = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Uri uri = Uri.parse(stringURI);
Bitmap bitmap = BitmapFactory.decodeFile(stringURI);
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(bitmap);
setContentView(imageView);
}
public static Bitmap decodeFile(File f, final int maxSize) {
Bitmap b = null;
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int scale = 1;
if (o.outHeight > maxSize || o.outWidth > maxSize) {
scale = (int) Math.pow(2, (int) Math.round(Math.log(maxSize / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
} catch (Exception e) {
Log.e("Logtag", "Error processing bitmap", e);
} finally {
//FileUtil.closeQuietly(fis);
}
return b;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Output from Log Cat:
02-25 00:53:11.907 13191-13191/edu.ramapo.camer I/System.out﹕ debugger has settled (1480)
02-25 00:53:12.177 13191-13191/edu.ramapo.camer I/dalvikvm﹕ Could not find method android.view.ViewGroup.onNestedScrollAccepted, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onNestedScrollAccepted
02-25 00:53:12.177 13191-13191/edu.ramapo.camer W/dalvikvm﹕ VFY: unable to resolve virtual method 11357: Landroid/view/ViewGroup;.onNestedScrollAccepted (Landroid/view/View;Landroid/view/View;I)V
02-25 00:53:12.177 13191-13191/edu.ramapo.camer D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
02-25 00:53:12.177 13191-13191/edu.ramapo.camer I/dalvikvm﹕ Could not find method android.view.ViewGroup.onStopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onStopNestedScroll
02-25 00:53:12.177 13191-13191/edu.ramapo.camer W/dalvikvm﹕ VFY: unable to resolve virtual method 11363: Landroid/view/ViewGroup;.onStopNestedScroll (Landroid/view/View;)V
02-25 00:53:12.177 13191-13191/edu.ramapo.camer D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
02-25 00:53:12.177 13191-13191/edu.ramapo.camer I/dalvikvm﹕ Could not find method android.support.v7.internal.widget.ActionBarOverlayLayout.stopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.setHideOnContentScrollEnabled
02-25 00:53:12.177 13191-13191/edu.ramapo.camer W/dalvikvm﹕ VFY: unable to resolve virtual method 9047: Landroid/support/v7/internal/widget/ActionBarOverlayLayout;.stopNestedScroll ()V
02-25 00:53:12.177 13191-13191/edu.ramapo.camer D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x000e
02-25 00:53:12.207 13191-13191/edu.ramapo.camer I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
02-25 00:53:12.207 13191-13191/edu.ramapo.camer W/dalvikvm﹕ VFY: unable to resolve virtual method 365: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
02-25 00:53:12.207 13191-13191/edu.ramapo.camer D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
02-25 00:53:12.207 13191-13191/edu.ramapo.camer I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
02-25 00:53:12.207 13191-13191/edu.ramapo.camer W/dalvikvm﹕ VFY: unable to resolve virtual method 387: Landroid/content/res/TypedArray;.getType (I)I
02-25 00:53:12.207 13191-13191/edu.ramapo.camer D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
02-25 00:53:13.068 13191-13191/edu.ramapo.camer D/libEGL﹕ loaded /system/lib/egl/libEGL_adreno200.so
02-25 00:53:13.068 13191-13191/edu.ramapo.camer D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_adreno200.so
02-25 00:53:13.078 13191-13191/edu.ramapo.camer D/libEGL﹕ loaded /system/lib/egl/libGLESv2_adreno200.so
02-25 00:53:13.078 13191-13191/edu.ramapo.camer I/Adreno200-EGL﹕ <qeglDrvAPI_eglInitialize:265>: EGL 1.4 QUALCOMM build: HAREESHG_Nondeterministic_AU+PATCH[ES]_msm8960_JB_1.9.6_MR2_CL3219408_release_ENGG (CL3219408)
Build Date: 09/28/13 Sat
Local Branch: hhh
Remote Branch: quic/jb_1.9.6_1
Local Patches: 8d50ec23e42ef52b570aa6ff1650afac0b503d78 CL3219408: Fix in the Glreadpixels for negative offsets and larger dimensions.
801859126f6ca69482b39a34ca61447e3f7cded8 rb: fix panel settings to clear undrawn/undefined buffers
Reconstruct Branch: LOCAL_PATCH[ES]
02-25 00:53:13.118 13191-13191/edu.ramapo.camer D/OpenGLRenderer﹕ Enabling debug mode 0
02-25 00:53:27.353 13191-13191/edu.ramapo.camer D/Logtag﹕ failed to create directory
02-25 00:53:27.353 13191-13191/edu.ramapo.camer D/Logtag:﹕ Error creating media file, check storage permissions:

I think the reason for the crash is because you are trying to get the camera instance twice: when your activity is created and when button captureButton is pressed. When you try to get it the second time, it returns null because it is already in use by your activity.
You should get the camera instance once before the captureButton button is pressed and process the picture taken after that.
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "File_name";
private Camera mCamera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
CameraPreview mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
}
...
Edit
To move to the next activity when a picture is taken, you could call startActivity after the Camera.PictureCallback
has saved the byte array to a file.
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d("Logtag:", "Error creating media file, check storage permissions: "
);
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Intent intent = new Intent(this,show_image.class);
Uri fileUri = Uri.fromFile(pictureFile);
intent.putExtra(EXTRA_MESSAGE, fileUri.toString());
startActivity(intent);
} catch (FileNotFoundException e) {
Log.d("Logtag:", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Logtag:", "Error accessing file: " + e.getMessage());
}
}
};
...
Edit 2
You need to add this permission to your manifest to store the photo on the device:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I hope this helps.

Related

Android NULL Pointer Exception and Fragment data transmission [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am a beginner at android studio, I have a mission to redesign the app. I use the Fragment. But when I run my app, it has stopped and there is no error in my Gradle. I looked for many website to solve my question, but still have no idea.
I have some questions below.
How can I fix the java.lang.RuntimeException (NULL Pointer Exception) ?
09-30 02:59:56.574 17706-17706/? E/memtrack: Couldn't load memtrack module (No such file or directory)
09-30 02:59:56.574 17706-17706/? E/android.os.Debug: failed to load memtrack module: -2
09-30 02:59:56.996 17722-17722/? E/memtrack: Couldn't load memtrack module (No such file or directory)
09-30 02:59:56.996 17722-17722/? E/android.os.Debug: failed to load memtrack module: -2
09-30 02:59:57.090 17734-17734/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: tw.com.flag.parking22, PID: 17734
java.lang.RuntimeException: Unable to start activity ComponentInfo{tw.com.flag.parking22/tw.com.flag.parking22.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at tw.com.flag.parking22.MainActivity.init(MainActivity.java:102)
at tw.com.flag.parking22.MainActivity.onCreate(MainActivity.java:71)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
09-30 02:59:57.211 1160-1160/? E/EGL_emulation: tid 1160: eglCreateSyncKHR(1865): error 0x3004 (EGL_BAD_ATTRIBUTE)
09-30 03:02:15.409 2159-19872/com.google.android.gms E/Herrevad: [350] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:02:15.445 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:02:15.445 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=NetworkReportService requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=3600000 target_class=com.google.android.gms.common.stats.net.NetworkReportService runtime=1506742923454 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=7200000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:02:15.446 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.common.stats.net.NetworkReportService{u=0 tag="NetworkReportService" trigger=window{period=7200s,flex=3600s,earliest=5988s,latest=9588s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=2388s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:02:15.474 1170-1578/? E/Drm: Failed to find drm plugin
09-30 03:02:15.563 2159-2680/com.google.android.gms E/Volley: [129] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=AggregationTaskTag requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=600000 target_class=com.google.android.gms.checkin.EventLogService runtime=1506741123628 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=1800000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.checkin.EventLogService{u=0 tag="AggregationTaskTag" trigger=window{period=1800s,flex=600s,earliest=1787s,latest=2387s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=587s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:03:37.417 1170-1578/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
09-30 03:30:15.406 2159-21157/com.google.android.gms E/Herrevad: [355] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:30:15.511 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.518 2159-21168/com.google.android.gms E/ZappLogOperation: Unable to bind to Phonesky
09-30 03:30:15.526 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.526 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.551 2159-2678/com.google.android.gms E/Volley: [127] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:30:15.572 1170-1578/? E/Drm: Failed to find drm plugin
09-30 03:30:22.524 2159-2159/com.google.android.gms E/ActivityThread: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection ctn#2f714ea6 that was originally bound here
android.app.ServiceConnectionLeaked: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection ctn#2f714ea6 that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1077)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:971)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1774)
at android.app.ContextImpl.bindService(ContextImpl.java:1757)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at com.google.android.gms.chimera.container.zapp.ZappLogOperation.onHandleIntent(:com.google.android.gms#11509280:1)
at com.google.android.chimera.IntentOperation.onHandleIntent(:com.google.android.gms#11509280:2)
at bwy.run(:com.google.android.gms#11509280:10)
at bwv.run(:com.google.android.gms#11509280:14)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=AggregationTaskTag requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=600000 target_class=com.google.android.gms.checkin.EventLogService runtime=1506743055606 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=1800000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.checkin.EventLogService{u=0 tag="AggregationTaskTag" trigger=window{period=1800s,flex=600s,earliest=1199s,latest=1799s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=0s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:44:15.637 2159-21184/com.google.android.gms E/Herrevad: [371] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:44:15.755 2159-2676/com.google.android.gms E/Volley: [126] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:46:13.425 1171-1171/? E/installd: eof
09-30 03:46:13.425 1171-1171/? E/installd: failed to read size
Here is the main activity code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager =(ViewPager) findViewById(R.id.pager);
PagerAdapter padapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(padapter);
//--------------------------------------------------------------------
init();
Action();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
}
else {
}
}
private void init(){
System.out.println("start---------------------");
textView_userIDVal = (TextView) findViewById(R.id.textView_userIDVal);
textView_parkingNoVal = (TextView) findViewById(R.id.textView_parkingNoVal);
textView_pillarNoVal = (TextView) findViewById(R.id.textView_pillarNoVal);
textView_colorVal = (TextView) findViewById(R.id.textView_colorVal);
imageView = (ImageView) findViewById(R.id.imageView);
button_space = (Button) findViewById(R.id.button_space);
button_scan = (Button) findViewById(R.id.button_scan);
button_find = (Button) findViewById(R.id.button_find);
simpleDateFormat = new SimpleDateFormat("MM/dd 'at' HH");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
userID = Build.SERIAL;
//-------------error start next----------------
textView_userIDVal.setText("User ID : " + userID);
}
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 200);
}
sharedPreferences = getSharedPreferences("Data", 0);
if(sharedPreferences.contains("parkingNum") && sharedPreferences.contains("time")) {
parkingNumtmp = sharedPreferences.getString("parkingNum", "");
textView_parkingNoVal.setText("Parking No. : " + parkingNumtmp + "\t(" + sharedPreferences.getString("time", "") + ")");
}
builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder_timeout = new AlertDialog.Builder(this);
builder_timeout.setTitle("REMIND");
builder_timeout.setMessage("Do you find your car ?");
builder_timeout.setCancelable(false);
builder_timeout.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
json_data = new JSONObject();
json_data.put("MT", "timeout");
json_data.put("PlaceMac", parkingNumtmp);
json_data.put("UserMac", userID);
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", false);
isCloseScreen = false;
} catch (JSONException e) {
e.printStackTrace();
}
thread = new Thread(TCP);
thread.start();
timer_count = 0;
startFlag = false;
}
});
builder_timeout.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
maxTime = 10;
maxTime = maxTime / 2;
timer_count = 0;
startFlag = true;
}
});
}
private void Action(){
button_space.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
json_data = new JSONObject();
json_data.put("MT", "count");
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", true);
//System.out.println(json_write + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
thread = new Thread(TCP);
thread.start();
/*builder.setTitle("INFORMATION");
builder.setMessage("All : " + "\nNow : " );
AlertDialog alertDialog = builder.create();
alertDialog.show();*/
}
});
button_scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScanActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
button_find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(parkingNumtmp != null) {
try {
maxTime = 10;
json_data = new JSONObject();
json_data.put("MT", "search");
json_data.put("PlaceMac", parkingNumtmp);
json_data.put("UserMac", userID);
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", true);
//System.out.println(json_write + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Don't close the screen before you find your car ! ", Toast.LENGTH_LONG).show();
thread = new Thread(TCP);
thread.start();
}
else {
builder.setTitle("WARNING");
builder.setMessage("Please scan QRcode first!");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
if(data != null) {
final Barcode barcode = data.getParcelableExtra("barcode");
parkingNumtmp = barcode.displayValue;
Date date = new Date();
final String time = simpleDateFormat.format(date);
sharedPreferences.edit().putString("parkingNum", parkingNumtmp).putString("time", time).commit();
textView_parkingNoVal.post(new Runnable() {
#Override
public void run() {
textView_parkingNoVal.setText("Parking No. : " + parkingNumtmp + "\t(" + time +")");
}
});
}
}
}
About Fragment. Is there any setting I have to do when I receive data form sever?
I want to put the received data to TextView in the another view .
Your init() function is probably try to find views inside fragments in view pager. However, at that moment, the fragments are not inflated yet, so your views in the activity are null and trying to do operation on them gives NPE. You should use onCreateView() of Fragment classes to find those views. Then you may notify main activity via callback mechanism.
For example, create FirstFragment as follows:
public class FirstFragment extends Fragment {
private OnFirstFragmentReadyListener callback;
#Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented the callback.
try {
callback = (OnFirstFragmentReadyListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnFirstFragmentReadyListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Notify the parent activity that the fragment is inflated.
callback.onFirstFragmentReady();
}
public interface OnFirstFragmentReadyListener {
void onFirstFragmentReady();
}
}
Let the layout of FirstFragment as follows (referenced above as fragment_first):
<RelativeLayout 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">
<TextView
android:id="#+id/first_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Assume we created two more similar fragment classes named as SecondFragment and ThirdFragment. Then the activity should be like this:
public class MainActivity extends AppCompatActivity implements FirstFragment.OnFirstFragmentReadyListener,
SecondFragment.OnSecondFragmentReadyListener, ThirdFragment.OnThirdFragmentReadyListener {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager =(ViewPager) findViewById(R.id.pager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
// Don't call these functions here, spread them into callbacks.
// init();
// Action();
}
#Override
public void onFirstFragmentReady() {
TextView firstTextView = (TextView) findViewById(R.id.first_label);
...
// Now you have the views from FirstFragment instance.
// You can now call setText() or setOnClickListener() here.
}
#Override
public void onSecondFragmentReady() {
TextView secondTextView = (TextView) findViewById(R.id.second_label);
...
// Now you have the views from SecondFragment instance.
// You can now call setText() or setOnClickListener() here.
}
#Override
public void onThirdFragmentReady() {
TextView thirdTextView = (TextView) findViewById(R.id.third_label);
...
// Now you have the views from ThirdFragment instance.
// You can now call setText() or setOnClickListener() here.
}
}
Although this code works, this may not be the best way. I think it is better to do operations on views like setting texts or assigning OnClickListeners in fragments itself. If you need to notify a fragment after an action happened in the parent activity, you can implement public methods inside fragments and you can call them from the parent activity when needed.
In fragment you should call the function in onCreateView function(reason as mention by #Mehmed) which is something like below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.your_fragment, container, false);
//all findViewById;
TextView yourTextView = (Text)view.findViewById(R.id.yourTextView);
//here call for your function
init();
// any other function goes here
return view;
}

How to create an edit button in an Contextmenu in Android Studio

to say it at the beginning - i am not a good programmer.
Im trying to create an contextmenu with an delete and edit function but im kinda having trouble with the edit function. As soon as the user is pushing the edit button in the contextmenu, he should be able to change the name of the Button i long pressed to open the contextmenu.
#Override
public boolean onContextItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.Bearbeiten:
EditText editText = (EditText) findViewById(R.id.editText);
buttonActOne.setText(editText.getText());
return true;
Of course the programm keeps crashing as soon as the user pushes the edit button and im kinda running out of ideas how i could do it else.
I really hope somebody has an good answer for me.
Edit:
Ok, first of all thanks for the answers till now. Im posting my complete MainActivity.java
package com.example.michl.myapplication5;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textViewIntro;
public Button buttonActOne;
public Button buttonActTwo;
public Button buttonActThree;
public Button buttonActFour;
public Button buttonActFive;
public Button buttonActSix;
public Button buttonActSeven;
public Button buttonActEight;
public Button buttonActNine;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewIntro = (TextView) findViewById(R.id.textViewIntro);
Button ButtonActOne = (Button) findViewById(R.id.buttonActOne);
ButtonActOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Seite_zwei.class));
Button ButtonActOne = (Button)findViewById(R.id.buttonActOne);
registerForContextMenu(ButtonActOne);
}
});
Button ButtonActTwo = (Button) findViewById(R.id.buttonActTwo);
ButtonActTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Seite_drei.class));
Button ButtonActTwo = (Button)findViewById(R.id.buttonActTwo);
registerForContextMenu(ButtonActTwo);
}
});
Button ButtonActThree = (Button) findViewById(R.id.buttonActThree);
ButtonActThree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Seite_vier.class));
Button ButtonActThree = (Button)findViewById(R.id.buttonActThree);
registerForContextMenu(ButtonActThree);
}
});
Button ButtonActFour = (Button) findViewById(R.id.buttonActFour);
ButtonActFour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Seite_fuenf.class));
Button ButtonActFour = (Button)findViewById(R.id.buttonActFour);
registerForContextMenu(ButtonActFour);
}
});
Button ButtonActFive = (Button) findViewById(R.id.buttonActFive);
ButtonActFive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Seite_sechs.class));
Button ButtonActFive = (Button)findViewById(R.id.buttonActFive);
registerForContextMenu(ButtonActFive);
}
});
Button ButtonActSix = (Button) findViewById(R.id.buttonActSix);
ButtonActSix.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Seite_sieben.class));
Button ButtonActSix = (Button)findViewById(R.id.buttonActSix);
registerForContextMenu(ButtonActSix);
}
});
Button ButtonActSeven = (Button) findViewById(R.id.buttonActSeven);
ButtonActSeven.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Seite_acht.class));
Button ButtonActSeven = (Button)findViewById(R.id.buttonActSeven);
registerForContextMenu(ButtonActSeven);
}
});
Button ButtonActEight = (Button) findViewById(R.id.buttonActEight);
ButtonActEight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Seite_neun.class));
Button ButtonActEight = (Button)findViewById(R.id.buttonActEight);
registerForContextMenu(ButtonActEight);
}
});
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.menu_main, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.Bearbeiten:
EditText editText = (EditText) findViewById(R.id.editText);
buttonActOne.setText(editText.getText());
return true;
case R.id.Löschen:
return true;
default:
}
return super.onContextItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And here is my logcat log when i start the programm and try to edit something.
08-28 13:52:06.135 26482-26482/com.example.michl.myapplication5 D/dalvikvm﹕ Late-enabling CheckJNI
08-28 13:52:06.150 26482-26488/com.example.michl.myapplication5 E/jdwp﹕ Failed sending reply to debugger: Broken pipe
08-28 13:52:06.150 26482-26488/com.example.michl.myapplication5 D/dalvikvm﹕ Debugger has detached; object registry had 1 entries
08-28 13:52:06.290 26482-26482/com.example.michl.myapplication5 D/libEGL﹕ loaded /system/lib/egl/libEGL_mali.so
08-28 13:52:06.295 26482-26482/com.example.michl.myapplication5 D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_mali.so
08-28 13:52:06.295 26482-26482/com.example.michl.myapplication5 D/libEGL﹕ loaded /system/lib/egl/libGLESv2_mali.so
08-28 13:52:06.300 26482-26482/com.example.michl.myapplication5 D/﹕ Device driver API match
Device driver API version: 10
User space API version: 10
08-28 13:52:06.300 26482-26482/com.example.michl.myapplication5 D/﹕ mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Thu Oct 25 08:43:05 KST 2012
08-28 13:52:06.315 26482-26482/com.example.michl.myapplication5 D/OpenGLRenderer﹕ Enabling debug mode 0
08-28 13:52:17.355 26482-26482/com.example.michl.myapplication5 I/dalvikvm﹕ Could not find method android.view.ViewGroup.onRtlPropertiesChanged, referenced from method android.support.v7.widget.Toolbar.onRtlPropertiesChanged
08-28 13:52:17.355 26482-26482/com.example.michl.myapplication5 W/dalvikvm﹕ VFY: unable to resolve virtual method 13334: Landroid/view/ViewGroup;.onRtlPropertiesChanged (I)V
08-28 13:52:17.355 26482-26482/com.example.michl.myapplication5 D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0007
08-28 13:52:17.360 26482-26482/com.example.michl.myapplication5 I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
08-28 13:52:17.360 26482-26485/com.example.michl.myapplication5 D/dalvikvm﹕ GC_CONCURRENT freed 188K, 14% free 9612K/11143K, paused 12ms+18ms, total 49ms
08-28 13:52:17.360 26482-26482/com.example.michl.myapplication5 W/dalvikvm﹕ VFY: unable to resolve virtual method 412: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
08-28 13:52:17.360 26482-26482/com.example.michl.myapplication5 D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
08-28 13:52:17.360 26482-26482/com.example.michl.myapplication5 I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
08-28 13:52:17.360 26482-26482/com.example.michl.myapplication5 W/dalvikvm﹕ VFY: unable to resolve virtual method 434: Landroid/content/res/TypedArray;.getType (I)I
08-28 13:52:17.360 26482-26482/com.example.michl.myapplication5 D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
08-28 13:52:17.465 26482-26482/com.example.michl.myapplication5 E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
08-28 13:52:17.465 26482-26482/com.example.michl.myapplication5 E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
08-28 13:52:18.345 26482-26482/com.example.michl.myapplication5 E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
08-28 13:52:18.345 26482-26482/com.example.michl.myapplication5 E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
08-28 13:52:19.605 26482-26482/com.example.michl.myapplication5 D/AbsListView﹕ Get MotionRecognitionManager
08-28 13:52:19.635 26482-26482/com.example.michl.myapplication5 W/ResourceType﹕ Failure getting entry for 0x010802c1 (t=7 e=705) in package 0 (error -75)
08-28 13:52:20.935 26482-26482/com.example.michl.myapplication5 D/AndroidRuntime﹕ Shutting down VM
08-28 13:52:20.935 26482-26482/com.example.michl.myapplication5 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4191e2a0)
08-28 13:52:20.955 26482-26482/com.example.michl.myapplication5 E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.michl.myapplication5.MainActivity.onContextItemSelected(MainActivity.java:161)
at android.app.Activity.onMenuItemSelected(Activity.java:2647)
at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:3921)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:193)
at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:934)
at android.widget.AdapterView.performItemClick(AdapterView.java:301)
at android.widget.AbsListView.performItemClick(AbsListView.java:1280)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3071)
at android.widget.AbsListView$1.run(AbsListView.java:3973)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4921)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
at dalvik.system.NativeStart.main(Native Method)
08-28 13:52:31.590 26482-26482/com.examp
le.michl.myapplication5 I/Process﹕ Sending signal. PID: 26482 SIG: 9
Declare your button on the onCreate method of the Activity!
Button buttonActOne = findViewById(R.id.buttonActOneId);
Then add the listener to it:
buttonActOne.setOnClickListener(this);
The setOnClickListener implements the interface View.OnClickListener, so the #override method it has to be onClick(View v), then in the switch you can use the v.getId();
In resume:
public class YourActivityName extends Activity implements View.OnClickListener {
private Button buttonActOne;
#Override
public void onCreate(Bundle b) {
//set your layout
buttonActOne = findViewById(R.id.buttonActOneId); //put the id defined in your xml layout
}
#Override
public void onClick(View view) {
if (View.getId(R.id.Bearbeiten)) {
EditText editText = (EditText) findViewById(R.id.editText);
buttonActOne.setText(editText.getText());
}
}
}

GoogleMap Android API V2 Capture Error

I try #Tarsem answer already but have fatal error occur can I know why?
#Tarsem answer:
https://stackoverflow.com/a/18308611/2398886
<--- these are my error codes in eclipse: --->
08-21 18:52:23.399: W/dalvikvm(29376): threadid=1: thread exiting with uncaught exception (group=0x40018578)
08-21 18:52:23.409: E/AndroidRuntime(29376): FATAL EXCEPTION: main
08-21 18:52:23.409: E/AndroidRuntime(29376): java.lang.NoClassDefFoundError: com.example.testing01.MainActivity2$6
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.example.testing01.MainActivity2.CaptureMapScreen(MainActivity2.java:410)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.example.testing01.MainActivity2$3.onClick(MainActivity2.java:182)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.view.View.performClick(View.java:2485)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.view.View$PerformClick.run(View.java:9080)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Handler.handleCallback(Handler.java:587)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Handler.dispatchMessage(Handler.java:92)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Looper.loop(Looper.java:130)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.app.ActivityThread.main(ActivityThread.java:3687)
08-21 18:52:23.409: E/AndroidRuntime(29376): at java.lang.reflect.Method.invokeNative(Native Method)
08-21 18:52:23.409: E/AndroidRuntime(29376): at java.lang.reflect.Method.invoke(Method.java:507)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:867)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-21 18:52:23.409: E/AndroidRuntime(29376): at dalvik.system.NativeStart.main(Native Method)
<--- these are my error codes in eclipse: --->
and these are my coding, is it my coding any bug?
public void CaptureMapScreen()
{
SnapshotReadyCallback callback = new SnapshotReadyCallback() {
Bitmap bitmap;
#Override
public void onSnapshotReady(Bitmap snapshot) {
// TODO Auto-generated method stub
bitmap = snapshot;
try {
FileOutputStream out = new FileOutputStream("/mnt/sdcard/"
+ "MyMapScreen" + System.currentTimeMillis()
+ ".png");
// above "/mnt ..... png" => is a storage path (where image will be stored) + name of image you can customize as per your Requirement
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
map.snapshot(callback);
// myMap is object of GoogleMap +> GoogleMap myMap;
// which is initialized in onCreate() =>
// myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_pass_home_call)).getMap();
}
my Stop Button function:
//End Button Function
Button timerStopButton = (Button) findViewById(R.id.btnTimerStop);
timerStopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
String latitude3=Double.toString(latitude1);
String latitude4=Double.toString(latitude2);
String longitude3=Double.toString(longitude1);
String longitude4=Double.toString(longitude2);
String Kcalories=String.format("%.2f", calories);
Intent intent = new Intent(view.getContext(),NewDataActivity.class);
intent.putExtra("lat1", latitude3);
intent.putExtra("lat2", latitude4);
intent.putExtra("long1", longitude3);
intent.putExtra("long2", longitude4);
intent.putExtra("timer", timerStop1);
intent.putExtra("distance", distance2 + " m");
intent.putExtra("Ccalories", Kcalories + " kcal");
Toast.makeText(getApplicationContext(), "Calories (kcal):" + Kcalories, Toast.LENGTH_LONG).show();
startActivity(intent);
try {
CaptureMapScreen();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//kill task timer and other
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
}
});
Is it my coding have any bug or my logic any probelm?
can anyone help me? thanks :)
Note Your code to Capture Map Screen is Correct and if still you have confusion than
Please Make sure Each Step Below:-
Below are the steps to capture screen shot of Google Map V2 with example
Step 1. open Android Sdk Manager (Window > Android Sdk Manager) then Expand Extras now update/install Google Play Services to Revision 10 ignore this step if already installed
Read Notes here https://developers.google.com/maps/documentation/android/releases#august_2013
Step 2. Restart Eclipse
Step 3. import com.google.android.gms.maps.GoogleMap.SnapshotReadyCallback;
Step 4. Make Method to Capture/Store Screen/image of Map like below
public void CaptureMapScreen()
{
SnapshotReadyCallback callback = new SnapshotReadyCallback() {
Bitmap bitmap;
#Override
public void onSnapshotReady(Bitmap snapshot) {
// TODO Auto-generated method stub
bitmap = snapshot;
try {
FileOutputStream out = new FileOutputStream("/mnt/sdcard/"
+ "MyMapScreen" + System.currentTimeMillis()
+ ".png");
// above "/mnt ..... png" => is a storage path (where image will be stored) + name of image you can customize as per your Requirement
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
myMap.snapshot(callback);
// myMap is object of GoogleMap +> GoogleMap myMap;
// which is initialized in onCreate() =>
// myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_pass_home_call)).getMap();
}
Step 5. Now call this CaptureMapScreen() method where you want to capture the image
in my case i am calling this method on Button click in my onCreate() which is working fine
like:
Button btnCap = (Button) findViewById(R.id.btnTakeScreenshot);
btnCap.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
CaptureMapScreen();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
Check Doc here and here

native_takePicture() error when pressing button to take picture

I've been trying to look for a similar error but I'm having a hard time... I'm still new to android development, but hopefully someone can shine some direction.
I have a camera app that can preview, but when I tried to click on a button to take the picture, my app crashes. Can someone help me?
[PhotoActivity.java]
public class PhotoActivity extends Activity {
public static final int MEDIA_TYPE_IMAGE = 1;
protected static final String TAG = "Activity";
private Camera mCamera;
private CameraPreview mCameraPreview;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photo);
mCamera = getCameraInstant();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(id.camera_preview);
preview.addView(mCameraPreview);
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
Log.e("log", "mPicture"+mPicture);
mCamera.takePicture(null, null, mPicture);
}
}
);
}
PictureCallback mPicture = new PictureCallback(){
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if(pictureFile==null){
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e){
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
/**
* Helper method to access the camera returns null if
* it cannot get the camera or does not exist
* #return
*/
private Camera getCameraInstant(){
Camera camera = null;
try{
camera=Camera.open();
}catch (Exception e){
// cannot get camera or does not exist
}
return camera;
}
/** Create a File for saving the image */
private File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
return mediaFile;
}
}
Sorry for all the coding, but I'm really in need of some help... Thanks in advance.
UPDATED
[CameraPreview.java]
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "Preview";
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
//Constructor that obtains context and camera
public CameraPreview(Context context, Camera camera) {
super(context);
//this.mCamera = camera;
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this); // we get notified when underlying surface is created and destroyed
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); //this is a deprecated method, is not requierd after 3.0
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
mCamera.release();
mCamera = Camera.open();
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.setDisplayOrientation(90);
mCamera.startPreview();
} catch (IOException e) {
// left blank for now
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
if (mCamera != null) {
Log.d(TAG,"Stopping preview in SurfaceDestroyed().");
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mCamera.release();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
if(mSurfaceHolder.getSurface()==null){
//preview surface does not exist
return;
}
try {
mCamera.stopPreview();
}catch(Exception e){
//ignore: tried to stop a non-existent preview
}
// start preview with new settings
try {
mCamera.setPreviewDisplay(mSurfaceHolder);
mCamera.setDisplayOrientation(90);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
Log.d(TAG, "Error starting camera preview: "+e.getMessage());
}
}
}
Error
05-09 21:19:29.013: E/AndroidRuntime(3823): FATAL EXCEPTION: main
05-09 21:19:29.013: E/AndroidRuntime(3823): java.lang.RuntimeException: Method called after release()
05-09 20:21:01.214: E/AndroidRuntime(2813): at android.hardware.Camera.native_takePicture(Native Method)
05-09 20:21:01.214: E/AndroidRuntime(2813): at android.hardware.Camera.takePicture(Camera.java:746)
05-09 20:21:01.214: E/AndroidRuntime(2813): at android.hardware.Camera.takePicture(Camera.java:710)
05-09 20:21:01.214: E/AndroidRuntime(2813): at com.liu.photo.PhotoActivity$2.onClick(PhotoActivity.java:73)
05-09 20:21:01.214: E/AndroidRuntime(2813): at android.view.View.performClick(View.java:2486)
05-09 20:21:01.214: E/AndroidRuntime(2813): at android.view.View$PerformClick.run(View.java:9130)
05-09 20:21:01.214: E/AndroidRuntime(2813): at android.os.Handler.handleCallback(Handler.java:587)
05-09 20:21:01.214: E/AndroidRuntime(2813): at android.os.Handler.dispatchMessage(Handler.java:92)
05-09 20:21:01.214: E/AndroidRuntime(2813): at android.os.Looper.loop(Looper.java:130)
05-09 20:21:01.214: E/AndroidRuntime(2813): at android.app.ActivityThread.main(ActivityThread.java:3703)
05-09 20:21:01.214: E/AndroidRuntime(2813): at java.lang.reflect.Method.invokeNative(Native Method)
05-09 20:21:01.214: E/AndroidRuntime(2813): at java.lang.reflect.Method.invoke(Method.java:507)
05-09 20:21:01.214: E/AndroidRuntime(2813): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
05-09 20:21:01.214: E/AndroidRuntime(2813): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
05-09 20:21:01.214: E/AndroidRuntime(2813): at dalvik.system.NativeStart.main(Native Method)
Is this what the stack trace is? I'm very new, still learning the terms as well. Thank you
Remove these two lines from the surfaceCreated method:
mCamera.release();
mCamera = Camera.open();
You've already opened the Camera object in your Activity, no need to release it and reopen it again.
Edit You should actually remove your whole implementation of surfaceCreated and just leave the implementation empty. You're just repeating what you've already done in surfaceChanged, which is the important place to implement it anyway.
Please see this page:
http://developer.android.com/reference/android/hardware/Camera.html
And make sure you follow the rules.
Especially pay attention that you must start preview before you take a picture.

Leaked Window when dialog button clicked

I'm trying to show an about page to the users of my wallpaper app when they click the about button however i get leaked window errors in a log cat and the activity quits before it shows the dialog.
Here is the code:
/*
*
* Sensational Wallpapers Pack 1
*
* Wallpaper Designed by AZ2ENVY
*
*/
package com.death2all110.SensationalWallpapers1;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.widget.Button;
import android.content.DialogInterface;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import com.death2all110.SensationalWallpapers1.R;
public class wallpaper extends Activity implements AdapterView.OnItemSelectedListener,
OnClickListener {
private Gallery mGallery;
private ImageView mImageView;
private boolean mIsWallpaperSet;
private Bitmap mBitmap;
private ArrayList<Integer> mThumbs;
private ArrayList<Integer> mImages;
private WallpaperLoader mLoader;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
findWallpapers();
setContentView(R.layout.wallpaper_chooser);
mGallery = (Gallery) findViewById(R.id.gallery);
mGallery.setAdapter(new ImageAdapter(this));
mGallery.setOnItemSelectedListener(this);
mGallery.setCallbackDuringFling(false);
findViewById(R.id.set).setOnClickListener(this);
mImageView = (ImageView) findViewById(R.id.wallpaper);
Button alert = (Button) findViewById(R.id.about_page);
alert.setOnClickListener(this);
}
private void findWallpapers() {
mThumbs = new ArrayList<Integer>(24);
mImages = new ArrayList<Integer>(24);
final Resources resources = getResources();
final String packageName = getApplication().getPackageName();
addWallpapers(resources, packageName, R.array.wallpapers);
addWallpapers(resources, packageName, R.array.extra_wallpapers);
}
private void addWallpapers(Resources resources, String packageName, int list) {
final String[] extras = resources.getStringArray(list);
for (String extra : extras) {
int res = resources.getIdentifier(extra, "drawable", packageName);
if (res != 0) {
final int thumbRes = resources.getIdentifier(extra + "_small",
"drawable", packageName);
if (thumbRes != 0) {
mThumbs.add(thumbRes);
mImages.add(res);
}
}
}
}
#Override
protected void onResume() {
super.onResume();
mIsWallpaperSet = false;
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
mLoader.cancel(true);
mLoader = null;
}
}
public void onItemSelected(AdapterView parent, View v, int position, long id) {
if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
mLoader.cancel();
}
mLoader = (WallpaperLoader) new WallpaperLoader().execute(position);
}
/*
* When using touch if you tap an image it triggers both the onItemClick and
* the onTouchEvent causing the wallpaper to be set twice. Ensure we only
* set the wallpaper once.
*/
private void selectWallpaper(int position) {
if (mIsWallpaperSet) {
return;
}
mIsWallpaperSet = true;
try {
InputStream stream = getResources().openRawResource(mImages.get(position));
setWallpaper(stream);
setResult(RESULT_OK);
finish();
} catch (IOException e) {
Log.e("Paperless System", "Failed to set wallpaper: " + e);
}
}
public void onNothingSelected(AdapterView parent) {
}
private class ImageAdapter extends BaseAdapter {
private LayoutInflater mLayoutInflater;
ImageAdapter(wallpaper context) {
mLayoutInflater = context.getLayoutInflater();
}
public int getCount() {
return mThumbs.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView image;
if (convertView == null) {
image = (ImageView) mLayoutInflater.inflate(R.layout.wallpaper_item, parent, false);
} else {
image = (ImageView) convertView;
}
int thumbRes = mThumbs.get(position);
image.setImageResource(thumbRes);
Drawable thumbDrawable = image.getDrawable();
if (thumbDrawable != null) {
thumbDrawable.setDither(true);
} else {
Log.e("Paperless System", String.format(
"Error decoding thumbnail resId=%d for wallpaper #%d",
thumbRes, position));
}
return image;
}
}
public void onClick(View v) {
selectWallpaper(mGallery.getSelectedItemPosition());
}
public void onClick1(View about) {
// If "About was clicked.....
if (about == findViewById(R.id.about_page)) {
// Prepare the alert box!!
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
// Set message to display...
alertbox.setMessage("Test.....");
// Add a neutral button to the alert box AND assign a listener for said button...
alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener(){
// click listener for box
public void onClick(DialogInterface arg0, int arg1){
// Button was clicked!!
Toast.makeText(getApplicationContext(), "Dialog closed successfully!", Toast.LENGTH_LONG).show();
}
});
// show it!!!
alertbox.show();
}
}
class WallpaperLoader extends AsyncTask<Integer, Void, Bitmap> {
BitmapFactory.Options mOptions;
WallpaperLoader() {
mOptions = new BitmapFactory.Options();
mOptions.inDither = false;
mOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
}
protected Bitmap doInBackground(Integer... params) {
if (isCancelled()) return null;
try {
return BitmapFactory.decodeResource(getResources(),
mImages.get(params[0]), mOptions);
} catch (OutOfMemoryError e) {
return null;
}
}
#Override
protected void onPostExecute(Bitmap b) {
if (b == null) return;
if (!isCancelled() && !mOptions.mCancel) {
// Help the GC
if (mBitmap != null) {
mBitmap.recycle();
}
final ImageView view = mImageView;
view.setImageBitmap(b);
mBitmap = b;
final Drawable drawable = view.getDrawable();
drawable.setFilterBitmap(true);
drawable.setDither(true);
view.postInvalidate();
mLoader = null;
} else {
b.recycle();
}
}
void cancel() {
mOptions.requestCancelDecode();
super.cancel(true);
}
}
}
Here is the logcat:
I/ActivityManager( 59): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.death2all110.SensationalWallpapers1/.wallpaper }
I/ActivityManager( 59): Displayed activity com.death2all110.SensationalWallpapers1/.wallpaper: 474 ms (total 474 ms)
D/dalvikvm( 286): GC freed 1448 objects / 151304 bytes in 131ms
D/dalvikvm( 106): GC freed 2485 objects / 144824 bytes in 245ms
D/dalvikvm( 59): threadid=15: bogus mon 1+0>0; adjusting
D/dalvikvm( 59): GC freed 3666 objects / 207344 bytes in 360ms
D/dalvikvm( 59): GC freed 459 objects / 21096 bytes in 357ms
E/WindowManager( 286): Activity com.death2all110.SensationalWallpapers1.wallpaper has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#44c0f3d0 that was originally added here
E/WindowManager( 286): android.view.WindowLeaked: Activity com.death2all110.SensationalWallpapers1.wallpaper has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#44c0f3d0 that was originally added here
E/WindowManager( 286): at android.view.ViewRoot.<init>(ViewRoot.java:227)
E/WindowManager( 286): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
E/WindowManager( 286): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
E/WindowManager( 286): at android.view.Window$LocalWindowManager.addView(Window.java:424)
E/WindowManager( 286): at android.app.Dialog.show(Dialog.java:239)
E/WindowManager( 286): at android.app.AlertDialog$Builder.show(AlertDialog.java:802)
E/WindowManager( 286): at com.death2all110.SensationalWallpapers1.wallpaper.onClick(wallpaper.java:244)
E/WindowManager( 286): at android.view.View.performClick(View.java:2364)
E/WindowManager( 286): at android.view.View.onTouchEvent(View.java:4179)
E/WindowManager( 286): at android.widget.TextView.onTouchEvent(TextView.java:6541)
E/WindowManager( 286): at android.view.View.dispatchTouchEvent(View.java:3709)
E/WindowManager( 286): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
E/WindowManager( 286): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
E/WindowManager( 286): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
E/WindowManager( 286): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
E/WindowManager( 286): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
E/WindowManager( 286): at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
E/WindowManager( 286): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
E/WindowManager( 286): at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
E/WindowManager( 286): at android.os.Handler.dispatchMessage(Handler.java:99)
E/WindowManager( 286): at android.os.Looper.loop(Looper.java:123)
E/WindowManager( 286): at android.app.ActivityThread.main(ActivityThread.java:4363)
E/WindowManager( 286): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager( 286): at java.lang.reflect.Method.invoke(Method.java:521)
E/WindowManager( 286): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
E/WindowManager( 286): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
E/WindowManager( 286): at dalvik.system.NativeStart.main(Native Method)
D/dalvikvm( 286): GC freed 1704 objects / 168544 bytes in 330ms
Not only does it have a leaked window, but when that button is clicked it also sets the wallpaper...
Any help would be greatly appreciated
change this
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
with
AlertDialog.Builder alertbox = new AlertDialog.Builder(yourActivity.this);
EDITED:
Button alert = (Button) findViewById(R.id.about_page);
alert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// do ur logic
});
make above change to your button click
The error shows that you are using the bad context here,
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
Try to use the right context here,
getApplicationContext(); or getParent() may solve your issue...
Thanks,
Suri Sahani.

Categories