How to handle exception in AsyncTask - android

I am using AsyncTask like this
public class AccountReportActivity extends Activity {
private OrgaLevelTask orgaLevelTask;
public void onCreate(Bundle savedInstanceState) {
......
orgaLevelTask = new OrgaLevelTask(AccountReportActivity.this, spinner_orgaLevel, spinner_branch, txt_extra, txt_extra1);
orgaLevelTask.execute();
} //end of onCreate
} //end of class AccountReportActivity
task:
public class OrgaLevelTask extends AsyncTask<Void, Void, ArrayList<OrgaLevel>> {
//Constrcutor
public OrgaLevelTask(AccountReportActivity accountReportActivity, Spinner spinner_orgaLevel, Spinner spinner_branch, TextView txt_extra, TextView txt_extra1) {
this.accountReportActivity = accountReportActivity;
this.spinner_orgaLevel = spinner_orgaLevel;
....
} //end of constructor
#Override
protected ArrayList<OrgaLevel> doInBackground(Void... arg0) {
return callWebService();
} //end of doInBackground()
private ArrayList<OrgaLevel> callWebService() {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
......
} catch (SocketTimeoutException e) {
Toast.makeText(accountReportActivity, "Service is not connected, Please make sure your server is running", Toast.LENGTH_LONG).show();
return null;
} catch(Exception e) {
e.printStackTrace();
System.out.println();
}
} //end of callWebService()
} //end of class OrgaLevelTask
My this task call another AsyncTask which has the same code. The problem is if server is running then everything fine. But if server is not running and i call the web service then i get the exception that Force Application close. Why? I am handling SocketTimeoutException IF exception happens then i am saying that show toast on my Activity but why it is force closing the application. How can i handle it? Thanks

You can check the internet connection this way first
public static boolean checkConnection(Context context) {
final ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else
return false;
}
In this method
// Checking the internet connection
if (!InternetConnectionCheck.checkConnection(this)) {
Utilities.alertDialogBox(this, R.string.Title_String,
R.string.No_Internet_connection_String);
} else {
orgaLevelTask = new OrgaLevelTask(AccountReportActivity.this, spinner_orgaLevel, spinner_branch, txt_extra, txt_extra1);
orgaLevelTask.execute();
}

you should not use use Toast in doInBackground
catch (SocketTimeoutException e) {
Toast.makeText(accountReportActivity, "Service is not connected, Please make sure your server is running", Toast.LENGTH_LONG).show(); //<----------------------

Related

How to set a fixed time if AsyncTask is not finished

I have an asynctask and I'm looking to do a wait if the async is taking too long, I'm downloading some data of the database , but I don't want to have the user looping around the progressdialog, I want to set a fixed time, lets say I'm downloading a file but is taking forever, so I tell the user, "hey, check your internet connection and try again" I'm looking to do this with a timer, but I'm kinda stuck, this is where I do my asynctask
private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
String s;
public DownloadFilesTask(String s){
this.s = s;
}
#Override
protected Void doInBackground(Void... voids) {
DownloadMethod(s);
return null;
}
}
so let's say I want to execute that downloadmethod for a fixed time, 10 or 20 seconds, if the file is not downloaded at that time I return a message to the user saying that he needs to check for hes internet.
You can use handler to run after a definite amount time and maintain a boolean flag which you can update in postExecute function of async task.
In your activity/fragment class:
new Handler().postDelayed(new Runnable(){
public void run(){
//Check whether the flag has been updated or not
},1000)
You can use BroadcastReceiver to listen your internet connection. Here is an example:
public class NetworkControl extends BroadcastReceiver {
static boolean isConnected = false;
#Override
public void onReceive(final Context context, final Intent intent) {
isNetworkAvailable(context);
}
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
if(!isConnected){
isConnected = true;
Toast.makeText(context, "You're online!!", Toast.LENGTH_LONG).show();
}
return true;
}
}
}
}
isConnected = false;
Toast.makeText(context, "Connection interrupted.", Toast.LENGTH_LONG).show();
return false;
}
}
Also you need some permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Then start the service in your activity.
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkControl();
registerReceiver(receiver, filter);
If you are using HttpURLConnection to download the file then you can do something like this:
private class DownloadFilesTask extends AsyncTask<String, Integer, Integer> {
#Override
protected Integer doInBackground(String... ulr) {
URL url = null;
try {
url = new URL(ulr[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setConnectTimeout(2000); //Timeout
//...Other codes for downloading
return 101;
} catch (java.net.SocketTimeoutException e) {
return 102;
} catch (MalformedURLException e) {
return 103;
} catch (IOException e) {
return 104;
}
}
#Override
protected void onPostExecute(Integer result) {
if(result == 102) {
Toast.makeText(getApplicationContext(), "Connection Timeout.", Toast.LENGTH_LONG).show();
}
}
}
First thing I want to say that is, while running downloading task it's not a good practice, to message a user that check your internet connection or
no internet connection. Because in this condition, if user do switch off then on network connection then your downloading task restarts again and takes whole time again. So, avoid this types of messages.
Now about solution, after execute background task you can check your task is running or completed. If it takes too much time
then show a message. For example,
YourBackgroundTask task = new YourBackgroundTask();
task.execute();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (task.getStatus == AsyncTask.Status.RUNNING){
Toast.makeText(this, "Please wait...", Toast.LENGTH_SHORT).show();
}
}
},20000); // time in milisecond
And if you want to repeat this, you can easily re-run handler.
Here is a basic idea you can try if it works
private class DownloadFilesTask extends AsyncTask<Void, Integer, Void> implements TimerTask{
String s;
Timer timer;
Object objectResult;
public DownloadFilesTask(String s){
this.s = s;
timer = new Timer();
}
#Override
protected Void doInBackground(Void... voids) {
objectResult = DownloadMethod();
return null;
}
private Object DownloadMethod() {
//here implement the download logic and return the object
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
// your code to update progress
}
public void checkProgress(){
timer.schedule(this,2000);
}
#Override
public void run() {
if (objectResult!=null){
//download completed
}else{
//show dialog here and schedule a task again
timer.schedule(this,2000);
}
}
}

Android sockets reconnect to server

I'm building a android app that using connection with Java server (on computer).
I have a problem- when I find that there is no connection with the server, I'm trying to reconnect to the server but it doesn't work.
Here is the Client class code:
public class Client extends AsyncTask {
private final int port = 1978;
private final String ip = "192.168.14.22";
private Socket socket;
private DataOutputStream output;
private DataInputStream input;
public Client() {
}
#Override
protected Object doInBackground(Object[] objects) {
try {
socket = new Socket(ip, port);
output = new DataOutputStream(socket.getOutputStream());
input = new DataInputStream(socket.getInputStream());
Log.d("Network c1", "Connected");
} catch (IOException e) {
socket = null;
Log.d("Network c1", "Not connected");
}
return null;
}
public boolean checkConnection() {
if (output == null)
return false;
try {
output.writeUTF("abc");
return true;
} catch (IOException e) {
return false;
}
}
#Override
protected void onProgressUpdate(Object[] values) {
}
}
And the Activity code:
public class LogInActivity extends AppCompatActivity {
Client client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
client = new Client();
client.execute();
//I used timer because it didn't work without it- That saied always 'not connected' message/Toast
new CountDownTimer(5, 0) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
check();
}
}.start();
}
private void check() {
boolean isProcess;
isProcess = !checkConnection();
if (isProcess) {
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Theme_AppCompat_Dialog_Alert);
builder.setTitle(getResources().getString(R.string.app_name));
builder.setMessage("Unable connect to the library");
builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//See note 1.
check();
}
});
builder.setCancelable(false);
builder.show();
}
}
public boolean checkConnection() {
if (client.checkConnection()) {
Toast.makeText(getApplicationContext(), "Connected to the library", Toast.LENGTH_SHORT).show();
return true;
} else {
Toast.makeText(this, "Unable connect to the library", Toast.LENGTH_SHORT).show();
return false;
}
}
}
Note 1:
The problem is here.
This Dialog need to be shown until the server/Library connected.
If the server is on before the app turned on, the check() method works well and says 'Connected successful' and the Dialog doesn't show.
But if when the app started, the server was unreachable, and turned on later (And became reachable)- the check() method don't work and always shows the Dialog.
What is the problem?
By the way, I tried to restart the client AsyncTask Class, but i didn't succeed.
(I tried to do close(true) to it, and after do excute() to it again, but the cancel() method didn't worked, and was a error that said that after a AsyncTask Class excuted, it can't excute again)
Thanks.
You should not check for connectivity periodically (every couple of seconds like you do in this code).
Instead you should let the OS do this for you, it will be more reliable and more efficient in terms of battery and CPU.
Take a look at this answer

using method inside asyntask in android

i have created one simple login application which takes user name and password from sqlserver..it works fine...
i want during login process one progeress bar should be displayed using asyntask...
but i am unaware to use parameters in asyntask...if some one plzz tell me how to put my method in doInbackground of asyntask and what param should i use....
my code is;.....
public void save(){
initilize();
ResultSet rs = null;
String mylog=id.getText().toString();
String mypass=pass.getText().toString();
try{
Statement statement=connect.createStatement();
rs=statement.executeQuery("LOGIN '"+mylog+"', '"+mypass+"'");
}catch(Exception e){
e.printStackTrace();
}
if(mylog.equals("")||mypass.equals("")){
Toast.makeText(getApplicationContext(), "empty fields", Toast.LENGTH_SHORT).show();
} else
try {
if(rs.next()){
Intent i=new Intent(getApplicationContext(),Act2.class);
startActivity(i);
}
else if(rs.next()==false){
Toast.makeText(getApplicationContext(), "incorrect login", Toast.LENGTH_SHORT).show();
id.setText("");
pass.setText("");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if it is possible that same method save() be kept inside doInbackground() of asyntask...
making a fast refactorization (note that this as it stand it's really bad practice and coding, you MUST refactor this code to be more maintanable and to avoid duplication):
public class MyAsyncTask extends AsyncTask<> {
private Activity activity;
boolean result;
private String myLog;
private String myPass;
private Connection connect;
public MyAsyncTask(Activity activity, Connection connect) {
this.activity = activity;
this.connect = connect;
}
#Override
protected void onPreExecute() {
//show your progress dialog
}
#Override
protected Object doInBackground(Object[] objects) {
ResultSet rs = null;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
initilize();
mylog=id.getText().toString();
mypass=pass.getText().toString();
}
});
try{
Statement statement=connect.createStatement();
rs=statement.executeQuery("LOGIN '"+mylog+"', '"+mypass+"'");
}catch(Exception e){
e.printStackTrace();
}
if(mylog.equals("")||mypass.equals("")){
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity.getApplicationContext(), "empty fields", Toast.LENGTH_SHORT).show();
}
});
} else
try {
if(rs.next()){
result = true;
}
else if(rs.next()==false){
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity.getApplicationContext(), "incorrect login", Toast.LENGTH_SHORT).show();
id.setText("");
pass.setText("");
}
});
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object o) {
//hide your progress dialog
if(result == Boolean.TRUE){
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Intent i=new Intent(activity.getApplicationContext(),Act2.class);
activity.startActivity(i);
}
});
}
}
}
then in your Activity you do this:
MyAsyncTask a = new MyAsyncTask(this, connect); //im guessing "connect" is your Connection object
a.execute();
As i said i made this fast refactoring for the code to work but best practice and good implementation is not in consideration here.
Maybe, you could use a timer, to check if your
login is ready. As long as it is not, you Show your progress Bar. If its ready, you can close the Bar and start a new activity or anything. timers run can run on u UI thread.
regards :)

can't dismiss ProgressDialog (using BroadcastReceiver)

my problem is:
I want my application to block buttons or whole activity when there is no internet connection and unblock them when internet connection is back. I'm using BroadcastReceiver to check internet in main activity and it works well:
public class MainActivity extends BroadCast {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.registerReceiver(this.mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
// code
}
To block MainActivity I'm using ProgressDialog with method setCancelable set to false.
BroadCast Activity:
public class BroadCast extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
public BroadcastReceiver mConnReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
#SuppressWarnings("deprecation")
NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if(currentNetworkInfo.isConnected()) {
BlockActivity(true);
}
else {
BlockActivity(false);
}
}
};
public void BlockActivity(Boolean connected)
{
final ProgressDialog pausingDialog = ProgressDialog.show(this, "", "Application waiting for internet connection...");
if (!connected)
{
Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_LONG).show();
pausingDialog.show();
pausingDialog.setCancelable(false);
}
else
{
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
pausingDialog.setCancelable(true);
pausingDialog.dismiss();
}
}
}
Toast information works good, but the problem is with ProgressDialog. It shows up when internet connection is gone, but it don't want to disappear when internet connection is back. How to fix it? Thanks.
Keep a global reference to your dialog so you don't keep recreating it. You should also use primitive types (boolean instead of Boolean)where possible and adhere to Java naming conventions (camelCase).
ProgressDialog pausingDialog;
public void blockActivity(boolean connected)
{
if (pausingDialog == null){
pausingDialog = new ProgressDialog (this);
pausingDialog.setMessage ("Application waiting for internet connection...");
}
if (!connected)
{
Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_LONG).show();
pausingDialog.show();
pausingDialog.setCancelable(false);
}
else
{
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
pausingDialog.setCancelable(true);
pausingDialog.dismiss();
}
}
Simple Code In Kotlin
var pausingDialog:SweetAlertDialog?=null
fun blockActivity(connected: Boolean,context: Context) {
if (pausingDialog == null) {
pausingDialog =SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE)
pausingDialog!!.titleText = "Application waiting for internet connection..."
pausingDialog!!.setCancelable(false)
pausingDialog!!.setConfirmClickListener{
var MyReceiver: BroadcastReceiver?= null;
MyReceiver = com.example.myrecharge.Helper.MyReceiver()
context.registerReceiver(MyReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
}
}
if (!connected) {
Toast.makeText(
context,
"Disconnected",
Toast.LENGTH_LONG
).show()
pausingDialog!!.show()
Log.d("##", "onReceive: 1")
} else {
Toast.makeText(
context,
"Connected",
Toast.LENGTH_LONG
).show()
pausingDialog!!.dismiss()
}
}

Handle threads on Android UI

In my application I want to check the network status on device,If no network connectivity is detected on device the i want to show a toast saying no network connection and then exit the application.And if the connection is detected on device then i have to load a list from webservice and display it on screen
I have done following code in onCreate function of application.It is running on emulator but not on real device.The reason for this to showANR on device is i am trying to handle so many threads on UI which is not appreciated in android.Please guide me how to do this using AsyncTask.
any code snippet or link to tutorial or suggestions will be helpful to me
boolean connected = false;
ConnectivityManager connectivitymanager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkinfo = connectivitymanager.getActiveNetworkInfo();
connected = networkinfo != null && networkinfo.isAvailable()
&& networkinfo.isConnected();
Log.v("Message ", connected + "");
Log.v("Message ", networkinfo.getReason());
//Toast.makeText(CategoryActivity.this, connected + "", 2000).show();
//connected = false;
Log.v("Message 1", connected + "");
if (connected == false) {
CategoryActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// Log.v("Message ", connected + "");
Toast.makeText(CategoryActivity.this,
"No Internet Connection detected on device", 3000).show();
}
});
Handler handler1 = new Handler();
handler1.postDelayed(new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
finish();
System.exit(0);
}
}), 4000);
} else {
CategoryArray = new JSONArray();
final ProgressDialog pd = ProgressDialog.show(
CategoryActivity.this, "", "Loading...", false, true);
pd.setIcon(getResources().getDrawable(R.drawable.icon));
new Thread() {
public void run() {
try {
sleep(5000);
// Log.v("TAG","in try block");
} catch (Exception e) {
// Log.e("tag", e.getMessage());
}
pd.dismiss();
// Log.v("TAG","progress dismiss");
}
}.start();
handler.postDelayed(new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
CategoryArray = CW
.getCategory("http://www.balajeebazaar.com/RestServiceImpl.svc/categorydetails");
// TODO: handle exception
for (int i = 0; i <= CategoryArray.length() - 1; i++) {
try {
String[] val = new String[3];
Log.v("category array : ",
CategoryArray.getString(i));
val = CategoryArray.getString(i).split(",");
CategoryID.add(i, val[0]);
CategoryList.add(i, val[1]);
val = null;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
adapter = new CategoryListAdapter(CategoryActivity.this,
CategoryList);
list.setAdapter(adapter);
}
}), 5000);
Thanks
EDIT
ERROR/AndroidRuntime(5486): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception
ERROR/AndroidRuntime(5486): java.lang.RuntimeException: An error occured while executing doInBackground()
ERROR/AndroidRuntime(5486): at android.os.AsyncTask$3.done(AsyncTask.java:200)
ERROR/AndroidRuntime(5486): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:234)
ERROR/AndroidRuntime(5486): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:258)
ERROR/AndroidRuntime(5486): at java.util.concurrent.FutureTask.run(FutureTask.java:122)
ERROR/AndroidRuntime(5486): at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:648)
ERROR/AndroidRuntime(5486): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:673)
ERROR/AndroidRuntime(5486): at java.lang.Thread.run(Thread.java:1060)
ERROR/AndroidRuntime(5486): Caused by: java.lang.ArrayIndexOutOfBoundsException
ERROR/AndroidRuntime(5486): at com.ecommerce.balajeebazaar.CategoryActivity$Loader.doInBackground(CategoryActivity.java:181)
ERROR/AndroidRuntime(5486): at com.ecommerce.balajeebazaar.CategoryActivity$Loader.doInBackground(CategoryActivity.java:1)
ERROR/AndroidRuntime(5486): at android.os.AsyncTask$2.call(AsyncTask.java:185)
11-18 18:30:07.582: ERROR/AndroidRuntime(5486):
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:256)
ERROR/AndroidRuntime(5486): 4 more
I suggest you read up on the AsyncTask yourself before applying the solution I have posted below, in order to better understand what is going on.
This is what you need in your Activity (it must replace all the code you posted):
boolean connected = false;
ConnectivityManager connectivitymanager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkinfo = connectivitymanager.getActiveNetworkInfo();
connected = networkinfo != null && networkinfo.isAvailable()
&& networkinfo.isConnected();
Log.v("Message ", connected + "");
Log.v("Message ", networkinfo.getReason());
//Toast.makeText(CategoryActivity.this, connected + "", 2000).show();
//connected = false;
Log.v("Message 1", connected + "");
if (connected == false) {
Toast.makeText(CategoryActivity.this, "No Internet Connection detected on device", Toast.LENGTH_LONG ).show();
finish();
} else {
new Loader().execute();
}
This is the AsyncTask which should be an inner class of your Activity:
private class Loader extends AsyncTask<Void, Void, Void> {
final ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = ProgressDialog.show( CategoryActivity.this, "", "Loading...", false, true);
pd.setIcon(getResources().getDrawable(R.drawable.icon));
super.onPreExecute();
}
#Override
protected Void doInBackground( Void... arg0 ) {
CategoryArray = new JSONArray();
CategoryArray = CW.getCategory("http://www.balajeebazaar.com/RestServiceImpl.svc/categorydetails");
for (int i = 0; i <= CategoryArray.length() - 1; i++) {
try {
String[] val = new String[3];
Log.v("category array : ", CategoryArray.getString(i));
val = CategoryArray.getString(i).split(",");
CategoryID.add(i, val[0]);
CategoryList.add(i, val[1]);
val = null;
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter = new CategoryListAdapter(CategoryActivity.this, CategoryList);
return null;
}
#Override
protected void onPostExecute( Void result ) {
pd.dismiss();
list.setAdapter(adapter);
super.onPostExecute( result );
}
}
Note
I wasn't able to check if the above actually works - but it should put you on the right track.
A nice tutorial on AsyncTasks and Handlers.
In really short, the idea of AsyncTask - you make a private class which extends AsyncTask in your Activity.
Doing this, you automatically get access to this Activities UI Thread from the AsyncTask class.
In AsyncTaks there are a couple of methods you should pay attention to. They are explained here.
What you should know is that only doInBackground() is executed in a separate Thread. Everything else is invoked on the UI thread of the Activity, where your AsyncTask is defined.
Simple scenario:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// stuff
new MyAsyncTask().execute(); //this should be invoked only once
}
private class MyAsyncTask() extends AsyncTask<Void, Void, <TypeOfResult Or Void>> {
#Override //executed on the UI thread of MyActivity
protected void onPreExecute() {
super.onPreExecute();
//prepare some stuff
}
#Override //executed in a separate Thread. This thread is automatically handled by AsyncTask
protected <TypeOfResult or Void> doInBackground(Void... params) {
//long operation
}
#Override //executed on the UI thread of MyActivity
protected void onPostExecute(<TypeOf Result Or Void>) {
super.onPostExecute(result);
// do stuff with result from long operation
}
}
}
You don't necessarily need an AsyncTask, you can use regular Java threading to accomplish what you need (far easier for a background task like this).

Categories

Resources