AsyncTask Example in android
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Start AsyncTask" />
</RelativeLayout>
MainActivity.java
package com.swamys.asynctaskexample;
import
android.app.Activity;
import
android.app.ProgressDialog;
import
android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import
android.view.View.OnClickListener;
import android.widget.Button;
import
android.widget.Toast;
public class MainActivity extends Activity {
ProgressDialog
dialog;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated
method stub
MyAsynctask
asynctask = new MyAsynctask();
asynctask.execute();
}
});
}
class MyAsynctask extends AsyncTask<String,
String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new
ProgressDialog(MainActivity.this);
dialog.setTitle("Loading...");
dialog.setMessage("Loading
articals...");
dialog.show();
Toast.makeText(getApplicationContext(),
"onPreExecute()",
Toast.LENGTH_SHORT).show();
}
@Override
protected String
doInBackground(String... params) {
return null;
}
@Override
protected void
onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Toast.makeText(getApplicationContext(),
"onProgressUpdate()",
Toast.LENGTH_SHORT).show();
}
@Override
protected void onPostExecute(String
result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(),
"onPostExecute()",
Toast.LENGTH_SHORT).show();
//
dialog.dismiss();
}
}
}
No comments:
Post a Comment