I know that the stop method has been deprecated and I am using destroy now, but I get this error:
11-09 11:42:28.740: E/AndroidRuntime(1538): FATAL EXCEPTION: main
11-09 11:42:28.740: E/AndroidRuntime(1538): java.lang.NoSuchMethodError: Thread.destroy()
11-09 11:42:28.740: E/AndroidRuntime(1538): at java.lang.Thread.destroy(Thread.java:600)
11-09 11:42:28.740: E/AndroidRuntime(1538): at com.rathbones.src.NewslettersActivity.onKeyDown(NewslettersActivity.java:144)
11-09 11:42:28.740: E/AndroidRuntime(1538): at android.view.KeyEvent.dispatch(KeyEvent.java:1037)
11-09 11:42:28.740: E/AndroidRuntime(1538): at android.app.Activity.dispatchKeyEvent(Activity.java:2068)
11-09 11:42:28.740: E/AndroidRuntime(1538): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1643)
11-09 11:42:28.740: E/AndroidRuntime(1538): at android.view.ViewRoot.deliverKeyEventToViewHierarchy(ViewRoot.java:2471)
11-09 11:42:28.740: E/AndroidRuntime(1538): at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2441)
11-09 11:42:28.740: E/AndroidRuntime(1538): at android.view.ViewRoot.handleMessage(ViewRoot.java:1735)
11-09 11:42:28.740: E/AndroidRuntime(1538): at android.os.Handler.dispatchMessage(Handler.java:99)
11-09 11:42:28.740: E/AndroidRuntime(1538): at android.os.Looper.loop(Looper.java:123)
11-09 11:42:28.740: E/AndroidRuntime(1538): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-09 11:42:28.740: E/AndroidRuntime(1538): at java.lang.reflect.Method.invokeNative(Native Method)
11-09 11:42:28.740: E/AndroidRuntime(1538): at java.lang.reflect.Method.invoke(Method.java:521)
11-09 11:42:28.740: E/AndroidRuntime(1538): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-09 11:42:28.740: E/AndroidRuntime(1538): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-09 11:42:28.740: E/AndroidRuntime(1538): at dalvik.system.NativeStart.main(Native Method)
11-09 11:42:28.760: W/ActivityManager(59): Force finishing activity com.rathbones.src/.NewslettersActivity
The application is not crashing, it's just that I get this error in logcat.
Actually I have a newsletter module which enables users to view the PDF file. When they press the view button it opens up a progress bar and in the same time if someone presses the backbutton it should stop the thread and exit gracefully. It does that but in the log I get the above error.
Here is the code snippet causing this error:
private void viewOnline() {
if (currentNewsletter == null) {
Log.e(Constants.APP_NAME, "No newsletter selected");
return;
}
final ProgressDialog d = new ProgressDialog(this);
d.setMessage("Downloading...");
d.show();
final Context context = getApplicationContext();
t = new Thread(new Runnable() {
public void run() {
String fileName = currentNewsletter.mFilename;
Log.d(Constants.APP_NAME, "Downloading/showing: " + fileName);
final File file = Utilities.getFileFromURL(context, currentNewsletter.mUrl, currentNewsletter.mExpectedSizeInBytes, fileName, false);
d.dismiss();
// Now we can show the file
viewPDF(file);
}
});
t.start();
// Utilities.List(getApplicationContext().getFilesDir().getPath());
// Utilities.List(getApplicationContext().getDir("files", Context.MODE_WORLD_WRITEABLE).getAbsolutePath());
// Utilities.DeleteDirectory(getApplicationContext().getDir("files", Context.MODE_WORLD_WRITEABLE).getAbsolutePath());
}
private void viewPDF(File file) {
//DEBUG DEBUG DEBUG
//Log.d(Constants.APP_NAME, "ViewPDF: showing " + file.getName());
//Log.d(Constants.APP_NAME, "Path: " + file.getPath());
//Log.d(Constants.APP_NAME, "Exists: " + file.exists());
//Log.d(Constants.APP_NAME, "Length: " + file.length());
//DEBUG DEBUG DEBUG
// Now it's all safe and sound and local, open it
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(this, "No Application Available to View PDF", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onStop() {
finish();
super.onStop();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
t.destroy();
Intent i = new Intent(NewslettersActivity.this,MainMenuActivity.class);
startActivity(i);
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
If you have a thread with a while loop inside, you can control this thread by a boolean flag for the while condition. When you set the flag to false the thread just finishes its task.
Here's a little example:
boolean flag = true;
Thread secondary = new Thread(new Runnable() {
#Override
public void run() {
while (flag) {
// do something
}
}
});
secondary.start(); //start the thread
flag = false; // this will force secondary to finish its execution
try {
secondary.join(); // wait for secondary to finish
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
I will found this code in SO and it also works for me.
Use interrupt() instead of destroy().
To the user370305 answer, maybe two changes could help:
Use AtomicBoolean instead boolean, if the Thread runs in another core, changes could not be visible for flag.
Remove the throw new RuntimeException(e) within the catch. It will crash as you are throwing an Exception.
Related
I've been trying develop a custom camera application for my project. I have followed pretty much every steps on the android developers website for the deprecated android.hardware.Camera class, as I need to stay compatible for older devices. I have added the permission for the camera and the features for the camera and the autofocus. I am currently testing with the emulator provided by android studio, the Nexus 5 API 23 x86 with both front-facing and back-facing cameras set on emulated. When my code reaches the Camera.open() bit, I get the error -13: Fail to connect to camera service.
I moved my camera initialization at many places but it always throws that error and returns null. The built-in Camera app in the emulator does work properly for both camera and they are both detected in my code. I simply cannot find why it doesn't work.
Here's my code just in case:
CameraActivity.java
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
public class CameraActivity extends AppCompatActivity {
private static final boolean AUTO_HIDE = true;
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
private static final int UI_ANIMATION_DELAY = 300;
private View mControlsView;
private boolean mVisible;
private CameraView mCameraView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mVisible = true;
mControlsView = findViewById(R.id.fullscreen_content_controls);
mCameraView = new CameraView(this);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_view);
preview.addView(mCameraView);
// Set up the user interaction to manually show or hide the system UI.
mCameraView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggle();
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.capture_button).setOnTouchListener(mDelayHideTouchListener);
//// TODO: 2015-11-05 Create a preview class extending SurfaceView and implementing SurfaceHolder.callback and put camera code there
//// TODO: 2015-11-05 http://developer.android.com/guide/topics/media/camera.html#custom-camera
//// TODO: 2015-11-05 http://stackoverflow.com/questions/26305107/how-to-fix-fail-to-connect-to-camera-service-exception-in-android-emulator
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
private void toggle() {
if (mVisible) {
hide();
} else {
show();
}
}
private void hide() {
// Hide UI first
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
mControlsView.setVisibility(View.GONE);
mVisible = false;
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.removeCallbacks(mShowPart2Runnable);
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}
private final Runnable mHidePart2Runnable = new Runnable() {
#SuppressLint("InlinedApi")
#Override
public void run() {
// Delayed removal of status and navigation bar
// Note that some of these constants are new as of API 16 (Jelly Bean)
// and API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mCameraView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
#SuppressLint("InlinedApi")
private void show() {
// Show the system bar
mCameraView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
mVisible = true;
// Schedule a runnable to display UI elements after a delay
mHideHandler.removeCallbacks(mHidePart2Runnable);
mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
}
private final Runnable mShowPart2Runnable = new Runnable() {
#Override
public void run() {
// Delayed display of UI elements
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.show();
}
mControlsView.setVisibility(View.VISIBLE);
}
};
private final Handler mHideHandler = new Handler();
private final Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
#Override
protected void onPause(){
super.onPause();
mCameraView.releaseCamera();
}
}
CameraView.java
import android.hardware.Camera; //This is the good import!
/**
* TODO: document your custom view class.
*/
#SuppressWarnings("deprecation")
public class CameraView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraView(Context context) {
super(context);
try{
mCamera = Camera.open();
} catch (Exception e){
Log.e("CameraView", "Error creating camera: " + e.getMessage());
}
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try{
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e){
Log.d("surfaceCreated", "Error starting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(mHolder.getSurface() == null)
return;
try{
mCamera.stopPreview();
} catch (Exception e) {
//Non-existent o.O
}
//Resize, etc
try{
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("CameraView", "Error starting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if(mCamera != null)
mCamera.stopPreview();
}
public void releaseCamera(){
if(mCamera != null){
mCamera.release();
mCamera = null;
}
}
}
The logcat:
11-09 14:13:13.144 7791-7791/? I/art: Not late-enabling -Xcheck:jni (already on)
11-09 14:13:13.144 7791-7791/? I/art: Late-enabling JIT
11-09 14:13:13.146 7791-7791/? I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
11-09 14:13:13.212 7791-7791/com.weebly.olipro007.cameracontrol W/System: ClassLoader referenced unknown path: /data/app/com.weebly.olipro007.cameracontrol-1/lib/x86
11-09 14:13:13.427 7791-7791/com.weebly.olipro007.cameracontrol W/CameraBase: An error occurred while connecting to camera: 0
11-09 14:13:13.427 7791-7791/com.weebly.olipro007.cameracontrol E/CameraView: Error creating camera: Fail to connect to camera service
11-09 14:13:13.489 7791-7820/com.weebly.olipro007.cameracontrol D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
11-09 14:13:13.508 7791-7791/com.weebly.olipro007.cameracontrol D/: HostConnection::get() New Host Connection established 0xab645030, tid 7791
11-09 14:13:13.584 7791-7820/com.weebly.olipro007.cameracontrol D/: HostConnection::get() New Host Connection established 0xab6451c0, tid 7820
11-09 14:13:13.611 7791-7820/com.weebly.olipro007.cameracontrol I/OpenGLRenderer: Initialized EGL, version 1.4
11-09 14:13:13.693 7791-7820/com.weebly.olipro007.cameracontrol W/EGL_emulation: eglSurfaceAttrib not implemented
11-09 14:13:13.693 7791-7820/com.weebly.olipro007.cameracontrol W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xabdff9a0, error=EGL_SUCCESS
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol D/AndroidRuntime: Shutting down VM
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: FATAL EXCEPTION: main
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: Process: com.weebly.olipro007.cameracontrol, PID: 7791
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.Camera.setPreviewDisplay(android.view.SurfaceHolder)' on a null object reference
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at com.weebly.olipro007.cameracontrol.CameraView.surfaceCreated(CameraView.java:43)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.SurfaceView.updateWindow(SurfaceView.java:582)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:177)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:944)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2055)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.Choreographer.doCallbacks(Choreographer.java:670)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.Choreographer.doFrame(Choreographer.java:606)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-09 14:13:16.909 7791-7791/? I/Process: Sending signal. PID: 7791 SIG: 9
Well it seems that the service was completely blocked for the old api in Marshmallow. I switched the emulator to lollipop and it loads...
I have an error on 264 and 163 of two file but in editor it's look fine
line 264 :
if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
line 163 :
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
I can't find why my activity unable to start
Logcat:
1266-1266/com.exercise.AndroidHTML E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exercise.AndroidHTML/com.company.clipboard.AndroidHTMLActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.company.clipboard.util.IabHelper.startSetup(IabHelper.java:264)
at com.company.clipboard.AndroidHTMLActivity.onCreate(AndroidHTMLActivity.java:163)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at android.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
This is the whole block of payment that contain line 163:
//=====================================================
String base64EncodedPublicKey = "MIHNMA0GCSqGSIb3DQEBAQUAA4G7ADCBtwKBrwDtUWVdLt6clZldCQGZxcyyWeeBp8vF/6qm7qCKuQPdXg6HB71hVu8lmcEO0VcyS2xpzXt03iW7LhKXRtDsxi5H9wHLESfY9SQUc0ugPD+n5nE+I6zCiB/RB2WscvZFa3JCiYRbmsvez+DwaQSHfq6CNUawl0fbz4NfJntZHKYHanm6PtjquO9JSj+Pa9PV38C3o5Y3ALCvPMCAwEAAQ==";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
Log.d(TAG, "Query inventory finished.");
if (result.isFailure()) {
Log.d(TAG, "Failed to query inventory: " + result);
return;
}
else {
Log.d(TAG, "Query inventory was successful.");
// does the user have the premium upgrade?
mIsPremium = inventory.hasPurchase(SKU_PREMIUM);
if (mIsPremium){
MasrafSeke(inventory.getPurchase(SKU_PREMIUM));
}
// update UI accordingly
Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
}
Log.d(TAG, "Initial inventory query finished; enabling main UI.");
}
};
mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
Log.d(TAG, "Error purchasing: " + result);
return;
}
else if (purchase.getSku().equals(SKU_PREMIUM)) {
// give user access to premium content and update the UI
Toast.makeText(AndroidHTMLActivity.this,"خرید موفق",Toast.LENGTH_SHORT).show();
MasrafSeke(purchase);
}
}
};
Log.d(TAG, "Starting setup.");
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
Log.d(TAG, "Setup finished.");
if (!result.isSuccess()) {
// Oh noes, there was a problem.
Log.d(TAG, "Problem setting up In-app Billing: " + result);
}
// Hooray, IAB is fully set up!
mHelper.queryInventoryAsync(mGotInventoryListener);
}
});
Seems an issue of IabHelper. The method queryIntentServices returns a null, instead an empty list.
Try to update the code from this:
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(
new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
}
}
to this:
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
List<ResolveInfo> intentServices = mContext.getPackageManager().queryIntentServices(serviceIntent, 0);
if (intentServices != null && intentServices.isEmpty() == false) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(
new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
}
}
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
I am getting the exceptions unless I delete this:
android:targetSdkVersion="15"
I found that in another thread here on SO.
However, I have had this running with that targetSdkVersion in there for a few days. Here is my code:
public class MainActivity extends BaseActivity {
private TextView textView;
private String url = "http://www.backcountryskiers.com/sac/sac-full.html";
private ImageView image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.todaysReport);
image = (ImageView) findViewById(R.id.dangerRose);
fetcher task = new fetcher();
task.execute();
}
public static Bitmap getBitmapFromURL(String src) {
try {
Log.e("src", src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap", "returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception", e.getMessage());
return null;
}
}
class fetcher extends AsyncTask<String, Void, String> {
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
private Document doc = null;
private Elements content = null;
private Document parse = null;
private String results = null;
private Element dangerRatingImg = null;
private String dangerRatingSrc = null;
private Bitmap bimage;
#Override
protected String doInBackground(String... params) {
try {
// bimage = getBitmapFromURL(drUrl);
doc = Jsoup.connect(url).get();
Log.e("Jsoup", "...is working...");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Exception", e.getMessage());
}
content = doc.select("#content");
parse = Jsoup.parse(doc.html());
results = doc.select("#content").outerHtml();
return results;
}
#Override
protected void onPostExecute(String result) {
// smooth out the long scrolling...
textView.setMovementMethod(ScrollingMovementMethod.getInstance());
// find rating image...
dangerRatingImg = doc.select("img").first();
dangerRatingSrc = dangerRatingImg.absUrl("src");
// Get the rating image
bimage = getBitmapFromURL(dangerRatingSrc);
image.setImageBitmap(bimage);
image.setPadding(10, 10, 10, 10);
image.setScaleType(ScaleType.FIT_XY);
// return the summary
results = parse.select("#reportSummary").outerHtml();
textView.setText(Html.fromHtml(results));
textView.setPadding(10, 10, 10, 10);
// ditch the dialog, it's all loaded.
dialog.dismiss();
}
#Override
protected void onPreExecute() {
// before we get the async results show this
dialog.setMessage("Loading Latest Update from the Sierra Avalanche Center...");
dialog.show();
}
}
}
I have network connection and can see the results fine taking that targetSdkVersion out... but I know that is not right. Thanks everyone.
EDIT:
11-09 08:24:55.316: D/dalvikvm(9165): GC_CONCURRENT freed 148K, 3% free 11365K/11655K, paused 12ms+12ms, total 39ms
11-09 08:24:55.410: D/dalvikvm(9165): GC_CONCURRENT freed 331K, 5% free 11484K/11975K, paused 1ms+1ms, total 20ms
11-09 08:24:55.418: E/Jsoup(9165): ...is working...
11-09 08:24:55.558: D/dalvikvm(9165): GC_CONCURRENT freed 465K, 5% free 11506K/12103K, paused 12ms+12ms, total 39ms
11-09 08:24:55.558: E/src(9165): http://www.sierraavalanchecenter.org/sites/default/files/images/danger_icons_and_bars/0_nodangerrate.png
11-09 08:24:55.558: D/AndroidRuntime(9165): Shutting down VM
11-09 08:24:55.558: W/dalvikvm(9165): threadid=1: thread exiting with uncaught exception (group=0x40bc2300)
11-09 08:24:55.566: E/AndroidRuntime(9165): FATAL EXCEPTION: main
11-09 08:24:55.566: E/AndroidRuntime(9165): android.os.NetworkOnMainThreadException
11-09 08:24:55.566: E/AndroidRuntime(9165): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
11-09 08:24:55.566: E/AndroidRuntime(9165): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-09 08:24:55.566: E/AndroidRuntime(9165): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-09 08:24:55.566: E/AndroidRuntime(9165): at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
11-09 08:24:55.566: E/AndroidRuntime(9165): at com.backcountryskiers.avalanche.report.norcal.MainActivity.getBitmapFromURL(MainActivity.java:49)
11-09 08:24:55.566: E/AndroidRuntime(9165): at com.backcountryskiers.avalanche.report.norcal.MainActivity$fetcher.onPostExecute(MainActivity.java:102)
11-09 08:24:55.566: E/AndroidRuntime(9165): at com.backcountryskiers.avalanche.report.norcal.MainActivity$fetcher.onPostExecute(MainActivity.java:1)
11-09 08:24:55.566: E/AndroidRuntime(9165): at android.os.AsyncTask.finish(AsyncTask.java:631)
11-09 08:24:55.566: E/AndroidRuntime(9165): at android.os.AsyncTask.access$600(AsyncTask.java:177)
11-09 08:24:55.566: E/AndroidRuntime(9165): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
11-09 08:24:55.566: E/AndroidRuntime(9165): at android.os.Handler.dispatchMessage(Handler.java:99)
11-09 08:24:55.566: E/AndroidRuntime(9165): at android.os.Looper.loop(Looper.java:137)
11-09 08:24:55.566: E/AndroidRuntime(9165): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-09 08:24:55.566: E/AndroidRuntime(9165): at java.lang.reflect.Method.invokeNative(Native Method)
11-09 08:24:55.566: E/AndroidRuntime(9165): at java.lang.reflect.Method.invoke(Method.java:511)
11-09 08:24:55.566: E/AndroidRuntime(9165): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
11-09 08:24:55.566: E/AndroidRuntime(9165): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
11-09 08:24:55.566: E/AndroidRuntime(9165): at dalvik.system.NativeStart.main(Native Method)
You're calling getBitmapFromURL from onPostExecute:
bimage = getBitmapFromURL(dangerRatingSrc);
onPreExecute and onPostExecute run on the UI thread. You need this code to be within doInBackground (as that's the part that runs on the new thread).
UPDATE: You can reorganize your code like this (as described in comments):
#Override
protected String doInBackground(String... params) {
try {
doc = Jsoup.connect(url).get();
Log.e("Jsoup", "...is working...");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Exception", e.getMessage());
}
content = doc.select("#content");
parse = Jsoup.parse(doc.html());
results = doc.select("#content").outerHtml();
// find rating image...
dangerRatingImg = doc.select("img").first();
dangerRatingSrc = dangerRatingImg.absUrl("src");
// Get the rating image
bimage = getBitmapFromURL(dangerRatingSrc);
return results;
}
#Override
protected void onPostExecute(String result) {
// smooth out the long scrolling...
textView.setMovementMethod(ScrollingMovementMethod.getInstance());
// Set the rating image
image.setImageBitmap(bimage);
image.setPadding(10, 10, 10, 10);
image.setScaleType(ScaleType.FIT_XY);
// return the summary
results = parse.select("#reportSummary").outerHtml();
textView.setText(Html.fromHtml(results));
textView.setPadding(10, 10, 10, 10);
// ditch the dialog, it's all loaded.
dialog.dismiss();
}
I am new to android programming.I have been trying to establish connection between two emulators.While my server emulator is up and running,client has a problem.Here is the code and logcat error description.Please tell me the error in this.
public class SocketClient extends Activity
{
private Button bt;
private TextView tv;
private Socket socket;
private String serverIpAddress = "192.168.0.5";
private static final int REDIRECTED_SERVERPORT = 5000;
public void connect()
{
try
{
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
tv.setText((CharSequence) serverAddr);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
}
catch (UnknownHostException e1)
{
e1.printStackTrace();
System.out.println("Here");
}
catch (IOException e1)
{
e1.printStackTrace();
System.out.println("Here too");
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
connect();
bt.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try
{
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
}
catch (UnknownHostException e)
{
tv.setText("Error1");
e.printStackTrace();
}
catch (IOException e)
{
tv.setText("Error2");
e.printStackTrace();
}
catch (Exception e)
{
tv.setText("Error3");
e.printStackTrace();
}
}
}
);
}
}
The logcat error is
01-31 04:42:51.170: W/dalvikvm(529): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
01-31 04:42:51.187: E/AndroidRuntime(529): FATAL EXCEPTION: main
01-31 04:42:51.187: E/AndroidRuntime(529): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.ServerClient/com.app.ServerClient.SocketClient}: java.lang.ClassCastException: java.net.Inet4Address cannot be cast to java.lang.CharSequence
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.access$600(ActivityThread.java:123)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.os.Handler.dispatchMessage(Handler.java:99)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.os.Looper.loop(Looper.java:137)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-31 04:42:51.187: E/AndroidRuntime(529): at java.lang.reflect.Method.invokeNative(Native Method)
01-31 04:42:51.187: E/AndroidRuntime(529): at java.lang.reflect.Method.invoke(Method.java:511)
01-31 04:42:51.187: E/AndroidRuntime(529): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-31 04:42:51.187: E/AndroidRuntime(529): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-31 04:42:51.187: E/AndroidRuntime(529): at dalvik.system.NativeStart.main(Native Method)
01-31 04:42:51.187: E/AndroidRuntime(529): Caused by: java.lang.ClassCastException: java.net.Inet4Address cannot be cast to java.lang.CharSequence
01-31 04:42:51.187: E/AndroidRuntime(529): at com.app.ServerClient.SocketClient.connect(SocketClient.java:25)
01-31 04:42:51.187: E/AndroidRuntime(529): at com.app.ServerClient.SocketClient.onCreate(SocketClient.java:48)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.Activity.performCreate(Activity.java:4465)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
01-31 04:42:51.187: E/AndroidRuntime(529): ... 11 more
Thanks in advance.
Thank You David and Jitendra.
I corrected the error and I get a nullPointerException in one part of the code.What did I do wrong?
public void onClick(View v)
{
try // The error is in this block
{
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
}
catch (UnknownHostException e)
{
tv.setText("Error1");
e.printStackTrace();
}
catch (IOException e)
{
tv.setText("Error2");
e.printStackTrace();
}
catch (Exception f) // I get the error here. java.lang.NullPointerException
{
tv.setText("Error3");
tv.setText(f.toString());
f.printStackTrace();
}
}
Your error is on this line:
tv.setText((CharSequence) serverAddr);
serverAddr is of type InetAddress, and you're trying to cast it to a CharSequence which cannot be done. Perhaps you meant:
tv.setText(serverIpAddress);
Exception is in following line:
tv.setText((CharSequence) serverAddr);
and it is because you are trying to cast serverAddr into CharSequence.
If you really want to print serverAddr use
tv.setText((CharSequence) serverAddr.toString());