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();
}
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...
Error Occured white retriving Bitmap In AsyncTask process the Logcat log is below,
please tell me how to clear this Error
I am beginner to android help me
thanks in advance
10-14 18:09:19.380 14124-16035/com.fragments D/dalvikvm﹕ GC_FOR_ALLOC freed 747K, 4% free 37438K/38855K, paused 191ms, total 193ms
10-14 18:09:19.400 14124-16035/com.fragments I/dalvikvm-heap﹕ Forcing collection of SoftReferences for 14155792-byte allocation
10-14 18:09:19.490 14124-16035/com.fragments D/dalvikvm﹕ GC_BEFORE_OOM freed 15K, 4% free 37422K/38855K, paused 91ms, total 91ms
10-14 18:09:19.490 14124-16035/com.fragments E/dalvikvm-heap﹕ Out of memory on a 14155792-byte allocation.
10-14 18:09:19.490 14124-16035/com.fragments I/dalvikvm﹕ "AsyncTask #4" prio=5 tid=16 RUNNABLE
10-14 18:09:19.490 14124-16035/com.fragments I/dalvikvm﹕ | group="main" sCount=0 dsCount=0 obj=0x432d6fc0 self=0x4d7c1fe8
10-14 18:09:19.490 14124-16035/com.fragments I/dalvikvm﹕ | sysTid=16035 nice=10 sched=3/0 cgrp=[fopen-error:2] handle=1300340400
10-14 18:09:19.490 14124-16035/com.fragments I/dalvikvm﹕ | schedstat=( 0 0 0 ) utm=15 stm=3 core=0
10-14 18:09:19.490 14124-16035/com.fragments I/dalvikvm﹕ at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
10-14 18:09:19.500 14124-16035/com.fragments I/dalvikvm﹕ at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:663)
10-14 18:09:19.500 14124-16035/com.fragments I/dalvikvm﹕ at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:735)
10-14 18:09:19.510 14124-16035/com.fragments I/dalvikvm﹕ at com.fragments.NewsListAdapter$ImageLoader.doInBackground(NewsListAdapter.java:128)
10-14 18:09:19.520 14124-16035/com.fragments I/dalvikvm﹕ at com.fragments.NewsListAdapter$ImageLoader.doInBackground(NewsListAdapter.java:112)
10-14 18:09:19.520 14124-16035/com.fragments I/dalvikvm﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-14 18:09:19.530 14124-16035/com.fragments I/dalvikvm﹕ at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
10-14 18:09:19.530 14124-16035/com.fragments I/dalvikvm﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-14 18:09:19.530 14124-16035/com.fragments I/dalvikvm﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-14 18:09:19.530 14124-16035/com.fragments I/dalvikvm﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
10-14 18:09:19.530 14124-16035/com.fragments I/dalvikvm﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
10-14 18:09:19.530 14124-16035/com.fragments I/dalvikvm﹕ at java.lang.Thread.run(Thread.java:856)
10-14 18:09:19.530 14124-16035/com.fragments I/dalvikvm﹕ [ 10-14 18:09:19.530 14124:14133 W/SQLiteConnectionPool ]
A SQLiteConnection object for database '+data+data+com_fragments+databases+news_db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
10-14 18:09:19.530 14124-14133/com.fragments D/AbsListView﹕ [unregisterDoubleTapMotionListener]
10-14 18:09:19.530 14124-14133/com.fragments I/MotionRecognitionManager﹕ .unregisterListener : / listener count = 0->0, ubvf 9budiwrd5ordgfl5BakTrklMrfo$,#,+)de/a(
10-14 18:09:19.560 14124-16035/com.fragments D/skia﹕ --- decoder->decode returned false
10-14 18:09:19.580 14124-16035/com.fragments W/dalvikvm﹕ threadid=16: thread exiting with uncaught exception (group=0x41ccd2b8)
10-14 18:09:19.740 14124-16035/com.fragments E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #4
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:663)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:735)
at com.fragments.NewsListAdapter$ImageLoader.doInBackground(NewsListAdapter.java:128)
at com.fragments.NewsListAdapter$ImageLoader.doInBackground(NewsListAdapter.java:112)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
10-14 18:09:28.740 14124-14124/com.fragments D/AndroidRuntime﹕ Shutting down VM
10-14 18:09:28.740 14124-14124/com.fragments W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41ccd2b8)
10-14 18:09:28.740 14124-14124/com.fragments I/Process﹕ Sending signal. PID: 14124 SIG: 9
Update:
This is my AsyncTask class
private class ImageLoader extends AsyncTask<NewsAndImages, Void, NewsAndImages> {
#Override
protected NewsAndImages doInBackground(NewsAndImages... params) {
NewsAndImages container = params[0];
News news = container.news;
try {
if (container.position > 0) {
InputStream in = (InputStream) new URL(news.getImage150()).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
news.setBitmap(bitmap);
in.close();
container.bitmap = bitmap;
return container;
} else {
InputStream in = (InputStream) new URL(news.getRealImage()).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
news.setBitmap(bitmap);
in.close();
container.bitmap = bitmap;
return container;
}
} catch (Exception e) {
Log.v("LOGTAG", e + " streaming pic"+news.getImage150());
}
return null;
}
#Override
protected void onPostExecute(NewsAndImages newsAndImages) {
try {
if (newsAndImages.position > 0) {
ImageView imageView = (ImageView) newsAndImages.view.findViewById(R.id.newsListImage);
imageView.setImageBitmap(newsAndImages.bitmap);
newsAndImages.news.setBitmap(newsAndImages.bitmap);
}else {
ImageView imageView = (ImageView) newsAndImages.view.findViewById(R.id.newsHeadLineImage);
imageView.setImageBitmap(newsAndImages.bitmap);
newsAndImages.news.setBitmap(newsAndImages.bitmap);
}
} catch (Exception e) {
Log.v("LOGTAG", e + " post exe");
}
}
}
Now Tell me what to do...
Apparently your method doInBackground cant process your image. Do you have other images process in your app at all? Also, I recommend you to use this:
bitmap.recycle();
bitmap = null;
This will assure the bitmap is garbage collected. If you don't recycle your bitmaps you will have an out of memory exception
Don't set bitmap inside doInBackground. rather return new downloaded bitmap and set only inside onPostExecute.
you set bitmap twice right now so remove from doInBackground and recycle after use.
update code
private class ImageLoader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(NewsAndImages... params) {
NewsAndImages container = params[0];
News news = container.news;
try {
if (container.position > 0) {
InputStream in = (InputStream) new URL(news.getImage150()).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
in.close();
return bitmap;
} else {
InputStream in = (InputStream) new URL(news.getRealImage()).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
in.close();
return bitmap;
}
} catch (Exception e) {
Log.v("LOGTAG", e + " streaming pic"+news.getImage150());
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
try {
if (bitmap !=null) {
ImageView imageView = (ImageView) newsAndImages.view.findViewById(R.id.newsListImage);
imageView.setImageBitmap(bitmap);
newsAndImages.news.setBitmap(bitmap);
}else {
ImageView imageView = (ImageView) newsAndImages.view.findViewById(R.id.newsHeadLineImage);
imageView.setImageBitmap(bitmap);
newsAndImages.news.setBitmap(bitmap);
}
bitmap.recycle();
} catch (Exception e) {
Log.v("LOGTAG", e + " post exe");
}
}
}
It Works...
By Using LruCache
private class ImageLoader extends AsyncTask<NewsAndImages, Void, NewsAndImages> {
#Override
protected NewsAndImages doInBackground(NewsAndImages... params) {
NewsAndImages container = params[0];
News news = container.news;
try {
if (container.position > 0) {
InputStream in = (InputStream) new URL(news.getImage150()).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
news.setBitmap(bitmap);
in.close();
container.bitmap = bitmap;
return container;
} else {
InputStream in = (InputStream) new URL(news.getRealImage()).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
news.setBitmap(bitmap);
in.close();
container.bitmap = bitmap;
return container;
}
} catch (Exception e) {
Log.v("LOGTAG", e + " streaming pic" + news.getImage150());
}
return null;
}
#Override
protected void onPostExecute(NewsAndImages newsAndImages) {
try {
if (newsAndImages.position > 0) {
ImageView imageView = (ImageView) newsAndImages.view.findViewById(R.id.newsListImage);
imageView.setImageBitmap(newsAndImages.bitmap);
imageCache.put(newsAndImages.news.getNews_id(),newsAndImages.bitmap);
} else {
ImageView imageView = (ImageView) newsAndImages.view.findViewById(R.id.newsHeadLineImage);
imageView.setImageBitmap(newsAndImages.bitmap);
imageCache.put(newsAndImages.news.getNews_id(),newsAndImages.bitmap);
}
} catch (Exception e) {
Log.i(NewsDBOpenHelper.LOGTAG, e + " onPostExecute");
}
}
}
This question already has an answer here:
Application crashes while starting the new thread
(1 answer)
Closed 9 years ago.
I have a class where I have implemented runnable and I start the thread in one of the function of this class, and I call this function from the main activity,I create the object of this class and call the method of thread class.My main activity code from where I call this class method is:
broadcast broadcastobject.threadfunc(messages);
My class where I create threads is:
public class broadcast {
private DatagramSocket socket;
String str;
private static final int TIMEOUT_MS = 10;
WifiManager mWifi;
EditText et;
DatagramPacket packet;
Button bt;
private static final int SERVERPORT = 11111;
private static final String SERVER_IP = "192.168.1.255";
public void threadfunc(String message){
str=message;
new Thread(new ClientThread()).start();
}
/*
private InetAddress getBroadcastAddress() throws IOException {
DhcpInfo dhcp = mWifi.getDhcpInfo();
if (dhcp == null) {
//Log.d(TAG, "Could not get dhcp info");
return null;
}
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
*/
class ClientThread implements Runnable {
#Override
public void run() {
try {
socket = new DatagramSocket(SERVERPORT);
socket.setBroadcast(true);
// socket.setSoTimeout(TIMEOUT_MS);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InetAddress serverAddr = null;
try {
serverAddr = InetAddress.getByName(SERVER_IP);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
packet = new DatagramPacket(str.getBytes(), str.length(),serverAddr,SERVERPORT);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
My log cat is:
08-31 21:55:56.277: D/gralloc_goldfish(1669): Emulator without GPU emulation detected.
08-31 21:56:02.467: D/AndroidRuntime(1669): Shutting down VM
08-31 21:56:02.467: W/dalvikvm(1669): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
08-31 21:56:02.517: E/AndroidRuntime(1669): FATAL EXCEPTION: main
08-31 21:56:02.517: E/AndroidRuntime(1669): java.lang.NullPointerException
08-31 21:56:02.517: E/AndroidRuntime(1669): at soft.b.peopleassist.Send$1.onClick(Send.java:113)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.view.View.performClick(View.java:3480)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.view.View$PerformClick.run(View.java:13983)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Handler.handleCallback(Handler.java:605)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Handler.dispatchMessage(Handler.java:92)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Looper.loop(Looper.java:137)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.app.ActivityThread.main(ActivityThread.java:4340)
08-31 21:56:02.517: E/AndroidRuntime(1669): at java.lang.reflect.Method.invokeNative(Native Method)
08-31 21:56:02.517: E/AndroidRuntime(1669): at java.lang.reflect.Method.invoke(Method.java:511)
08-31 21:56:02.517: E/AndroidRuntime(1669): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-31 21:56:02.517: E/AndroidRuntime(1669): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-31 21:56:02.517: E/AndroidRuntime(1669): at dalvik.system.NativeStart.main(Native Method)
This simply means that the emulator you are using does not have GPU emulation enabled. In Android SDK Tools R15 you can enable GPU emulation.You need to create a new emulator virtual device and set GPU emulation to true in Hardware properties.
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());
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.