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");
}
}
}
Related
I am getting the following runtime exception.
Fatal signal 6 (SIGABRT) at 0x00000820 (code=-6), thread 2080
thread eixiting with uncaught exception
java.lang.RuntimeException: An error occured while executing doInBackground()
I am posted the full stacktrace errors below:
Stacktrace:
02-02 02:13:17.137: E/dalvikvm(2080): VM aborting
02-02 02:13:17.137: A/libc(2080): Fatal signal 6 (SIGABRT) at 0x00000820 (code=-6), thread 2080 (e.quranmadeeasy)
02-02 02:13:20.177: D/dalvikvm(2140): GC_FOR_ALLOC freed 101K, 8% free 2981K/3208K, paused 74ms, total 75ms
02-02 02:13:20.177: I/dalvikvm-heap(2140): Grow heap (frag case) to 3.637MB for 635812-byte allocation
02-02 02:13:20.217: D/dalvikvm(2140): GC_FOR_ALLOC freed 0K, 6% free 3602K/3832K, paused 36ms, total 36ms
02-02 02:13:20.397: W/dalvikvm(2140): threadid=13: thread exiting with uncaught exception (group=0xb3a3cba8)
02-02 02:13:20.397: E/AndroidRuntime(2140): FATAL EXCEPTION: AsyncTask #1
02-02 02:13:20.397: E/AndroidRuntime(2140): Process: com.qrme.quranmadeeasy, PID: 2140
02-02 02:13:20.397: E/AndroidRuntime(2140): java.lang.RuntimeException: An error occured while executing doInBackground()
02-02 02:13:20.397: E/AndroidRuntime(2140): at android.os.AsyncTask$3.done(AsyncTask.java:300)
02-02 02:13:20.397: E/AndroidRuntime(2140): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
02-02 02:13:20.397: E/AndroidRuntime(2140): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
02-02 02:13:20.397: E/AndroidRuntime(2140): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
02-02 02:13:20.397: E/AndroidRuntime(2140): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-02 02:13:20.397: E/AndroidRuntime(2140): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-02 02:13:20.397: E/AndroidRuntime(2140): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-02 02:13:20.397: E/AndroidRuntime(2140): at java.lang.Thread.run(Thread.java:841)
02-02 02:13:20.397: E/AndroidRuntime(2140): Caused by: java.lang.NullPointerException
02-02 02:13:20.397: E/AndroidRuntime(2140): at com.qrme.quranmadeeasy.LessonActivity$getLesson.doInBackground(LessonActivity.java:259)
02-02 02:13:20.397: E/AndroidRuntime(2140): at com.qrme.quranmadeeasy.LessonActivity$getLesson.doInBackground(LessonActivity.java:1)
02-02 02:13:20.397: E/AndroidRuntime(2140): at android.os.AsyncTask$2.call(AsyncTask.java:288)
02-02 02:13:20.397: E/AndroidRuntime(2140): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-02 02:13:20.397: E/AndroidRuntime(2140): ... 4 more
I am pointed out the error line in below code.
LessonActivity.java:
public class LessonActivity extends Activity implements OnItemClickListener {
AdapterLesson al; // creating object of AdapterLesson class
static ArrayList<Lesson> lessonList = null;
static ArrayList<Settings> settings = null;
int chapterId;
AdapterPages adapPage;
static ArrayList<Page> selectedpageList = null;
static ArrayList<Page> pageList = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_lesson);
ParseAnalytics.trackAppOpened(getIntent());
if (getIntent() != null && getIntent().getExtras() != null) {
String chapt_id = getIntent().getExtras().getString("CHAPTER_ID");
chapter = getIntent().getExtras().getString("CHAPTER_NAME");
// txtChapterdetails.setText(chapter);
if (chapt_id != null && !chapt_id.equalsIgnoreCase("")) {
chapterId = Integer.parseInt(chapt_id);
}
}
initialize();
listLesson.setOnItemClickListener(this);
}
public class getLesson extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
lessonList = DatabaseQueryHelper.getInstance().getLesson(chapterId); --->259th line
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
if(lessonList!=null)
{
if(lessonList.size()>0)
{
al = new AdapterLesson(LessonActivity.this, lessonList);
listLesson.setAdapter(al);
}
}
}
}
}
Anyone can help me with this.Thank you.
The problem is in DatabaseQueryHelper class. The method getInstance() is called before an instance has been initialized. So when you call it you get NullPointerException. Look for ways to implement a Singleton in order to correct this one.
I am new to android. I have created an app which was a pull parser in order to extract items from an Rss feed, into a ListView. Unfortunately my app seems to force close when I try and place code in order implement some sort of filtering mechanism in my ListView. This is the code I have so far, and I have no idea why it seems to crash. Any help would be appreciated.
public class RssFeed extends ListActivity {
// Listview Adapter
ArrayAdapter<string> adapter;
EditText SearchBox;
List titles;
public static List description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rss);
// Initialising instance variables
titles = new ArrayList();
description = new ArrayList();
try {
URL url = new URL("http://my.url");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
/** While the rss feed has not displayed end_document, pull the title and description information */
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
titles.add(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("description")) {
if (insideItem)
description.add(xpp.nextText());
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, titles);
setListAdapter(adapter);
/**
* Enabling Search Filter
* */
SearchBox.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
RssFeed.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
}
And the LogCat:
04-12 20:43:00.792: D/dalvikvm(324): GC freed 7597 objects / 316440 bytes in 88ms
04-12 20:43:00.852: D/AndroidRuntime(324): Shutting down VM
04-12 20:43:00.852: W/dalvikvm(324): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
04-12 20:43:00.852: E/AndroidRuntime(324): Uncaught handler: thread main exiting due to uncaught exception
04-12 20:43:00.862: E/AndroidRuntime(324): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.me.myandroidstuff.simpleRssReader/org.me.myandroidstuff.TrafficScotlandPrototype.RssFeed}: java.lang.NullPointerException
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.os.Handler.dispatchMessage(Handler.java:99)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.os.Looper.loop(Looper.java:123)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.main(ActivityThread.java:4363)
04-12 20:43:00.862: E/AndroidRuntime(324): at java.lang.reflect.Method.invokeNative(Native Method)
04-12 20:43:00.862: E/AndroidRuntime(324): at java.lang.reflect.Method.invoke(Method.java:521)
04-12 20:43:00.862: E/AndroidRuntime(324): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
04-12 20:43:00.862: E/AndroidRuntime(324): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
04-12 20:43:00.862: E/AndroidRuntime(324): at dalvik.system.NativeStart.main(Native Method)
04-12 20:43:00.862: E/AndroidRuntime(324): Caused by: java.lang.NullPointerException
04-12 20:43:00.862: E/AndroidRuntime(324): at org.me.myandroidstuff.TrafficScotlandPrototype.RssFeed.onCreate(RssFeed.java:142)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
04-12 20:43:00.862: E/AndroidRuntime(324): ... 11 more
04-12 20:43:00.892: I/dalvikvm(324): threadid=7: reacting to signal 3
04-12 20:43:00.892: E/dalvikvm(324): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
First of all: the class you posted doesn't have 142 lines, be sure to post the whole class.
Second: SearchBox is null here.
That is because you declared it with
EditText SearchBox;
but never assigned it which you would usually do from your layout like
SearchBox = (EditText) findViewById(R.id.searchBox);
(just an example)
SeachBox does not have an assigned value at this point so you can't use any methods on it.
Third: Use lower case names like searchBox, it'll make your code easier to read for others and yourself.
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 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 connecting from my Android app to a RESTful Web Service in Java. I am using AsyncTask to fetch the data. It works perfectly for normal amount of data. but when I have a huge amount of data, an Exception happens in the Android app. I tried to catch this exception, but I couldn't:
private class LoadingDataFromServer extends AsyncTask<Void, Void, Void> {
private boolean outOfMemory = false;
#Override
public void onPreExecute() {
progress = ProgressDialog.show(main_activity, null,"Loading ...", true);
}
#Override
protected void onPostExecute(Void result) {
if(outOfMemory) {
Toast.makeText(StatisticActivity.this, "Out of memory, select smaller criteria", Toast.LENGTH_SHORT).show();
finish();
}
else
setListView();
try {
progress.dismiss();
} catch (Exception e) { }
}
#Override
protected Void doInBackground(Void... params) {
TextView txtProject = (TextView) main_activity.findViewById(R.id.project);
txtProject.setBackgroundColor(Color.DKGRAY);
txtProject.setText(project);
TextView label = (TextView) main_activity.findViewById(R.id.label);
label.setText(R.string.deliverable);
try {
loadStatistic();
} catch (OutOfMemoryError e) {
outOfMemory = true;
progress.dismiss();
} catch (RuntimeException e) {
outOfMemory = true;
progress.dismiss();
} catch (Exception e) {
outOfMemory = true;
progress.dismiss();
}
return null;
}
}
This is the error I got:
10-14 22:24:10.952: ERROR/AndroidRuntime(4179): Uncaught handler: thread AsyncTask #3 exiting due to uncaught exception
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): java.lang.RuntimeException: An error occured while executing doInBackground()
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): at android.os.AsyncTask$3.done(AsyncTask.java:200)
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): at java.lang.Thread.run(Thread.java:1102)
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): at android.os.Handler.<init>(Handler.java:121)
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): at android.widget.Toast.<init>(Toast.java:68)
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): at android.widget.Toast.makeText(Toast.java:231)
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): at se.softwerk.timelog.statistic.StatisticActivity$LoadingDataFromServer.doInBackground(StatisticActivity.java:301)
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): at se.softwerk.timelog.statistic.StatisticActivity$LoadingDataFromServer.doInBackground(StatisticActivity.java:1)
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): at android.os.AsyncTask$2.call(AsyncTask.java:185)
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
10-14 22:24:10.962: ERROR/AndroidRuntime(4179): ... 4 more
The exception is happening in doInBackground, but my exception handeling did not work. Can you help me?
You should call any UI-related code from within onPreExecute(), onProgressUpdate(Progress... values) or onPostExecute(Result result) (which run in main thread, the UI thread), and use doInBackground(Params... params) only to perform CPU-intensive operations.
Calling publishProgress(Progress... values) within doInBackground(Params... params) will send data to onProgressUpdate(Progress... values), where you can use it to update the UI.