Exception in AsyncTask due to enormous number of data - java

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.

Related

AsyncTask with progressbar

The following code is a part of my app and it isn't working and I don't know why.
I don't know at which place I can put the "new MormaKaugummi().execute();". At any place the App crashed and gave me the error "Unfortunately, Criminal Life has stopped."
The "counter textview" is in an another activity in the same app.
(The name of the App is Criminal Life).
I need a unique solution because I'm new in Android programming.
public class Morma extends AppCompatActivity {
class MormaKaugummi extends AsyncTask<String, String, String> {
private int count = 0;
private void count() {
count++;
}
private void update() {
TextView counter = (TextView) findViewById(R.id.counter);
String Kcounter = Integer.toString(count);
counter.setText(Kcounter);
}
#Override
protected String doInBackground(String... params) {
count();
update();
return null;
}
}
private ProgressBar progressBarKaugummi;
private int progressStatusKaugummi = 0;
private Handler handlerKaugummi = new Handler();
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_morma);
Button buttonMormaKaugummiKlauen = (Button) findViewById(R.id.buttonMormaKaugummiKlauen);
buttonMormaKaugummiKlauen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBarKaugummi = (ProgressBar) findViewById(R.id.progressBarMormaKaugummi);
new Thread(new Runnable() {
public void run() {
while (progressStatusKaugummi < 100) {
progressStatusKaugummi += 1;
handlerKaugummi.post(new Runnable() {
public void run() {
progressBarKaugummi.setProgress(progressStatusKaugummi);
}
});
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
if (progressStatusKaugummi == 100) {
progressBarKaugummi.setProgress(0);
recreate();
new MormaKaugummi().execute();
}
}
});
That's the logcat
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: Caused by: java.lang.NullPointerException
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.update(Morma.java:26)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.doInBackground(Morma.java:32)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.doInBackground(Morma.java:15)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)
11-07 13:48:35.514 622-622/peppermine_studios.criminallife W/EGL_emulation: eglSurfaceAttrib not implemented
11-07 13:48:35.674 622-622/peppermine_studios.criminallife W/EGL_emulation: eglSurfaceAttrib not implemented
11-07 13:48:37.364 622-1376/? I/Process: Sending signal. PID: 622 SIG: 9
You are trying to do findviewbyId and update the text view in your doInBackground method via the update function, which you cannot do.
As for the crash its happening because of a null pointer exception as you can read for yourself in the logcat's caused by clause it tells you the exact line number where the null pointer exception is thrown
Caused by: java.lang.NullPointerException
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.update(Morma.java:26)
as you can see here, its caused by null pointer at line 26 in Morma.java and I am guessing that your TextView counter is null since you are trying to initialize a variable to reference a UI element from a non-UI thread, the counter variable will be initialized as null obviously.
Now for the solution:
What you need to do is put the update function in the onPostExecute method for the async task class. Reason: onPostExceute runs on whatever thread the asyntcTask.execute method was called from so you are supposed to do your UI update in the onPostExecute method
#Override
protected String doInBackground(String... params) {
count();
return null;
}
#Override
protect void onPostExecute(String result) {
update();
}
Also since you are returning null from doInBackground anyway you should Extend AsyncTask<String,String,Void> ideally.
EDIT 1:
Added code
public class Morma extends AppCompatActivity {
// make the text view class variable if you want to update it outside of onCreate.
private TextView mCounterTextView;
class MormaKaugummi extends AsyncTask<Void, Void, Void> {
private int count = 0;
private void count() {
count++;
}
private void update() {
String Kcounter = Integer.toString(count);
mCounterTextView.setText(Kcounter);
}
#Override
protected void doInBackground(Void... aVoid) {
count();
}
#Override
protected void onPostExecute(Void aVoid) {
update();
}
}
private ProgressBar progressBarKaugummi;
private int progressStatusKaugummi = 0;
private Handler handlerKaugummi = new Handler();
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_morma);
Button buttonMormaKaugummiKlauen = (Button) findViewById(R.id.buttonMormaKaugummiKlauen);
// initiate all your view items in onCreate.
mCounterTextView = (TextView) findViewById(R.id.counter);
buttonMormaKaugummiKlauen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBarKaugummi = (ProgressBar) findViewById(R.id.progressBarMormaKaugummi);
new Thread(new Runnable() {
public void run() {
while (progressStatusKaugummi < 100) {
progressStatusKaugummi += 1;
handlerKaugummi.post(new Runnable() {
public void run() {
progressBarKaugummi.setProgress(progressStatusKaugummi);
}
});
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
if (progressStatusKaugummi == 100) {
progressBarKaugummi.setProgress(0);
recreate();
new MormaKaugummi().execute();
}
}
});
You need to initialize all your view elements like the textview in onCreate itself and keep the reference as a class variable if you are going to use that view outside of onCreate.

Error Occured while retrieving A Bitmap In AsyncTask process

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");
}
}
}

ASyncTask with progressdialog and button

I am beginner and I had a test. I did all tasks, but I have a problem -
public class HttpTask extends AsyncTask<Integer, String, String> {####
ProgressDialog dialog;
Context context;
public HttpTask(Activity activity) {
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
protected void onPreExecute() {
// show progress dialog
dialog.setMessage("Loading...");
dialog.setCancelable(false);
}
protected String doInBackground(Integer... params) {
//freeze system to 5 seconds
try {
int seconds = params[0]*5;####
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
// if there is progress dialog hide it
dialog.dismiss();
}
}
It crashes, when I try to compile it (I showed where are problems with * sign):
08-03 10:43:10.873 29441-29441/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
at android.app.AlertDialog.<init>(AlertDialog.java:98)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at net.joerichard.androidtest.main.f.HttpTask.<init>(HttpTask.java:26)
at net.joerichard.androidtest.main.f.F_Networking_Activity$1.onClick(F_Networking_Activity.java:27)
at android.view.View.performClick(View.java:4107)
at android.view.View$PerformClick.run(View.java:17166)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5559)
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:1074)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
at dalvik.system.NativeStart.main(Native Method)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
This is class of main activity.
public class F_Networking_Activity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_f__networking_);
// bDownload: start HttpTask
Button bDownload = (Button) findViewById(R.id.bDownload);
bDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HttpTask task = new HttpTask(F_Networking_Activity.this);****
task.execute();
}
});
}
Thank you for your answers. Now I have another problem (I showed with # sign of second problems)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest'
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
08-03 11:28:18.292 30544-30726/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
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:864)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:40)
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:20)
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:864)
Actually, your context is null because you didn't initialize it.
Add one extra line inside your HttpTask:
public HttpTask(Activity activity) {
this.context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
and change Context to Activity like this:
Activity context;
Now call this context anywhere in your class.
Yes you must get NullPointer. Because your context is null.
Change this like
public HttpTask(Context _context) {
context = _context;
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}

Android paging mechanism handle

How do I handle paging mechanism?
I have created a code to create paging of data. But when I specify a limit that has expired, the application will be damaged and force closed.
My paging class :
public class SetPaging {
public static final String[] PAGING = new String[] {
"0,5","5,5","10,5","15,5","20,5"
};
}
My listener :
pullRefresh = ((PullAndLoadListView) listView);
pullRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
public void onLoadMore() {
new LoadMoreData().execute();
}
});
My async code :
private class LoadMoreData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
page = page + 1;
if (page > SetPaging.PAGING.length) {
page = 0;
}
}
protected Void doInBackground(Void... params) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
try {
ArrayList<UtamaBean> NextUtama = new ArrayList<UtamaBean>();
NextUtama = PushServer.getNextUtama(SetPaging.PAGING[page]);
if (page > 0) {
utamabean.addAll(NextUtama);
} else {
utamabean = PushServer.getNextUtama(SetPaging.PAGING[page]);
}
} catch (Exception e) {
netError.setVisibility(View.VISIBLE);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
listView.setVisibility(View.VISIBLE);
adapter.setItem(utamabean);
pullRefresh.onLoadMoreComplete();
}
#Override
protected void onCancelled() {
pullRefresh.onLoadMoreComplete();
}
}
All went smoothly. Only when the sixth paging applications (outside the rules "20,5") then the application will be immediately force closed.
How best to conduct the sixth restrictions if paging is done, the application will not be entered into async function and request the data?
Thanks
===UPDATE===
My LogCat :
11-24 19:59:40.587: E/AndroidRuntime(16223): FATAL EXCEPTION: AsyncTask #1
11-24 19:59:40.587: E/AndroidRuntime(16223): java.lang.RuntimeException: An error occured while executing doInBackground()
11-24 19:59:40.587: E/AndroidRuntime(16223): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-24 19:59:40.587: E/AndroidRuntime(16223): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-24 19:59:40.587: E/AndroidRuntime(16223): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-24 19:59:40.587: E/AndroidRuntime(16223): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-24 19:59:40.587: E/AndroidRuntime(16223): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-24 19:59:40.587: E/AndroidRuntime(16223): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-24 19:59:40.587: E/AndroidRuntime(16223): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-24 19:59:40.587: E/AndroidRuntime(16223): at java.lang.Thread.run(Thread.java:841)
11-24 19:59:40.587: E/AndroidRuntime(16223): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
11-24 19:59:40.587: E/AndroidRuntime(16223): at com.joris.babe.F_Test$LoadMoreData.doInBackground(F_Test.java:156)
11-24 19:59:40.587: E/AndroidRuntime(16223): at com.joris.babe.F_Test$LoadMoreData.doInBackground(F_Test.java:1)
11-24 19:59:40.587: E/AndroidRuntime(16223): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-24 19:59:40.587: E/AndroidRuntime(16223): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-24 19:59:40.587: E/AndroidRuntime(16223): ... 4 more
You have this
netError.setVisibility(View.VISIBLE);
Updating ui from doInbackground.doInbackground is invoked on the background thread.
Hence the exception. Update ui on the ui thread. Return a value in doInbackground. Based on the value returned set the visibility accrodingly in onPostExecute.

Still working in Android Login

me again, in my previous post, i was told to use AsyncTask in codes, to avoid mainexceptionthread, and now i'm encountering this errors:
**
01-26 09:39:06.220: E/AndroidRuntime(17218): FATAL EXCEPTION: AsyncTask #1
01-26 09:39:06.220: E/AndroidRuntime(17218): java.lang.RuntimeException: An error occured while executing doInBackground()
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-26 09:39:06.220: E/AndroidRuntime(17218): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-26 09:39:06.220: E/AndroidRuntime(17218): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-26 09:39:06.220: E/AndroidRuntime(17218): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-26 09:39:06.220: E/AndroidRuntime(17218): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-26 09:39:06.220: E/AndroidRuntime(17218): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-26 09:39:06.220: E/AndroidRuntime(17218): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-26 09:39:06.220: E/AndroidRuntime(17218): at java.lang.Thread.run(Thread.java:856)
01-26 09:39:06.220: E/AndroidRuntime(17218): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4609)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:867)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.view.ViewGroup.invalidateChild(ViewGroup.java:4066)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.view.View.invalidate(View.java:10193)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.widget.TextView.invalidateRegion(TextView.java:4375)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.widget.TextView.invalidateCursor(TextView.java:4318)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.widget.TextView.spanChange(TextView.java:7172)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.widget.TextView$ChangeWatcher.onSpanAdded(TextView.java:8759)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.text.SpannableStringBuilder.sendSpanAdded(SpannableStringBuilder.java:979)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:688)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:588)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.text.Selection.setSelection(Selection.java:76)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.text.Selection.setSelection(Selection.java:87)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.text.method.ArrowKeyMovementMethod.initialize(ArrowKeyMovementMethod.java:302)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.widget.TextView.setText(TextView.java:3535)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.widget.TextView.setText(TextView.java:3405)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.widget.EditText.setText(EditText.java:80)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.widget.TextView.setText(TextView.java:3380)
01-26 09:39:06.220: E/AndroidRuntime(17218): at com.example.projectthesis.Main$phpconnect.doInBackground(Main.java:98)
01-26 09:39:06.220: E/AndroidRuntime(17218): at com.example.projectthesis.Main$phpconnect.doInBackground(Main.java:1)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-26 09:39:06.220: E/AndroidRuntime(17218): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-26 09:39:06.220: E/AndroidRuntime(17218): ... 5 more
**
i think it is because of the Exception e part, which has inputEmail.setText(e.toString());
but when i am changing it to just e.printstacktrace, it results nothing. Can you help me here guys these are my codes:
android:
**
public class Main extends Activity {
EditText inputEmail;
EditText inputPassword;
Button btnLogin;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
inputEmail = (EditText) findViewById(R.id.inputEmail);
inputPassword = (EditText) findViewById(R.id.inputPassword);
Button btnLogin = (Button) findViewById(R.id.btnLogin);
// button click event
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
validation();
}
});
}
public void validation()
{
if(inputEmail.getText().toString().equals("") || inputPassword.getText().toString().equals(""))
{
Toast.makeText( getApplicationContext(),"Fill Empty Fields",Toast.LENGTH_SHORT ).show();
}
else
{
new phpconnect().execute();
}
}
class phpconnect extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Main.this);
pDialog.setMessage("Logging in..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("eadd", inputEmail.getText().toString()));
postParameters.add(new BasicNameValuePair("password", inputPassword.getText().toString()));
//Passing Parameter to the php web service for authentication
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/TheCalling/log_in.php", postParameters); //Enter Your remote PHP,ASP, Servlet file link
String res=response.toString();
//res = res.trim();
res= res.replaceAll("\\s+","");
//error.setText(res);
if(res.equals("1"))
{
Toast.makeText( getApplicationContext(),"Correct Username or Password",Toast.LENGTH_SHORT ).show();
Intent i = new Intent(Main.this,MainMenu.class);
startActivity(i);
}
else
if(res.equals("0"))
{
Toast.makeText( getApplicationContext(),"Sorry!! Incorrect Username or Password",Toast.LENGTH_SHORT ).show();
}
} catch (Exception e) {
inputEmail.setText(e.toString());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
**
This again my PHP codes:
**
<?php
include("db_config.php");
$eadd=addslashes($_POST['eadd']);
$password=addslashes($_POST['password']);
$sql="SELECT * FROM users WHERE eadd='$eadd' and password='$password'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$count=mysql_num_rows($result);
if($count==1)
{
echo "1";
//(If result found send 1 to android)
}
else
{
echo "0";
//(If result not found send o to android)
}
?>
**
You get an error because of:
catch (Exception e) {
inputEmail.setText(e.toString());
}
Over here you try to alter the app's UI by altering the contents of an EditText from the background thread of the AsyncTask. Since I doubt you actually want to show an error to the user in the email input field and are doing this just for debugging purposes, try using e.printStackTrace() instead of inputEmail.setText(e.toString());
Additionally, you'll want to wrap your Toast.show() calls in a runOnUiThread() runnable.
You can't show the toast messages in doInBackground just move it to onPostExecute. and yes also this
catch (Exception e) {
inputEmail.setText(e.toString());
}

Categories