Can anybody tell me how to update the UI using ASyncTask and give an example?
I am getting the value from two webservices. From two webservices I am getting value in two arraylist on post method will not return value it will rounding in loop. How do I return from onPostExecuteMethod?
This is my async class:
public class HomeTask extends AsyncTask<Void,Void,Bundle>
{
private Context ctx;
public HomeTask(Context context) {
ctx = context;
}
#Override
protected void onPreExecute() {
//super.onPreExecute();
//setContentView(R.layout.splash);
dlg = new ProgressDialog(getDialogContext());
dlg.setMessage("Loading....");
dlg.show();
//setContentView(R.layout.splash);
}
#Override
protected Bundle doInBackground(Void... params) {
Bundle b=new Bundle();
// TODO Auto-generated method stub
try
{
WebService tableservice=new WebService();
tableservicevalue=tableservice.callTableServer(SOAP_ACTION,"",strUsername,strPassWord,questGroupId,URL);
tableservicevalue=decodeXMLData(tableservicevalue);
DomTableParser parser=new DomTableParser();
parser.setTableservicevalue(tableservicevalue);
parsedValue=parser.parseXmlFile(tableservicevalue);
Log.d("1234%%%%$$$$$$$parsed value$$$$$", parsedValue.toString());
WebService service=new WebService();
webservicevalue=service.callHomeServer(SOAP_ACTION,"",strUsername,strPassWord,questGroupId,URL);
webservicevalue=decodeXMLData(webservicevalue);
ArticleParser articleParser=new ArticleParser();
articleParsedValue=articleParser.parseXmlArticle(webservicevalue);
//b.putStringArrayList("articleParsedValue", articleParsedValue);
Log.d("(((((((parsed value is",parsedValue.toString());
b.putStringArrayList("parsedValue", parsedValue);
b.putStringArrayList("articleParsedValue", articleParsedValue);
Log.d("(((((((parsed value is",articleParsedValue.toString());
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return b;
}
#Override
protected void onPostExecute(Bundle b) {
Log.d("vijay checking","checking&&&&");
Log.d("****","*********");
Log.d("calling","handler");
Log.d("****","*********");
parsedValue1=b.getStringArrayList("parsedValue");
articleParsedValue1=b.getStringArrayList("articleParsedValue");
}
onupdating user interface
new HomeTask(HomeActivity2.this).execute(null);
for(int i=0;i<parsedValue1.size();i++)
{
DomParserTableDataSet dataSet=(DomParserTableDataSet)parsedValue1.get(i);
if(i==0)
{
Log.d("&&&&&&index name is", dataSet.getIndexName());
Log.d("&&&&&&index name is", dataSet.getLastValue());
Log.d("&&&&&&index name is",dataSet.getChangePercentage() );
txtindex0.setText(dataSet.getIndexName());
txtlast0.setText(dataSet.getLastValue());
txtchange0.setText(dataSet.getChangePercentage());
}
if(i==1)
{
Log.d("&&&&&&index name is", dataSet.getIndexName());
Log.d("&&&&&&index name is", dataSet.getLastValue());
Log.d("&&&&&&index name is",dataSet.getChangePercentage() );
txtindex1.setText(dataSet.getIndexName());
txtlast1.setText(dataSet.getLastValue());
txtchange1.setText(dataSet.getChangePercentage());
}
if(i==2)
{
Log.d("&&&&&&index name is", dataSet.getIndexName());
Log.d("&&&&&&index name is", dataSet.getLastValue());
Log.d("&&&&&&index name is",dataSet.getChangePercentage() );
txtindex2.setText(dataSet.getIndexName());
txtlast2.setText(dataSet.getLastValue());
txtchange2.setText(dataSet.getChangePercentage());
}
if(i==3)
{
Log.d("&&&&&&index name is", dataSet.getIndexName());
Log.d("&&&&&&index name is", dataSet.getLastValue());
Log.d("&&&&&&index name is",dataSet.getChangePercentage() );
txtindex3.setText(dataSet.getIndexName());
txtlast3.setText(dataSet.getLastValue());
txtchange3.setText(dataSet.getChangePercentage());
}
}
//
for(int i=0;i<articleParsedValue1.size();i++)
{
System.out.println("for loop checking i is"+i);
ArticleDataSet articleDataset=(ArticleDataSet)articleParsedValue1.get(i);
System.out.println("articleDataset.getArticle_title()"+articleDataset.getArticle_title());
HashMap<String, String> mapValue=new HashMap<String, String>();
WebView webviewcontent=new WebView(HomeActivity2.this);
if(articleDataset.getArticle_summary().length()>75)
{
summary=articleDataset.getArticle_summary().substring(0,75)+"...";
}
else
{
summary=articleDataset.getArticle_summary();
}
String html ="<html><body><div><label> <font face=\"verdana\" color=\"#C1002B\" size=\"4\"><b>"+articleDataset.getArticle_title()+"</b> </font> </label>"+ "<label> <font color=\"#000000\" size=\"2\" face=\"verdana\">"+"|"+"</font></label> "+"<label> <font color=\"#AAAAAA\" face=\"verdana\" size=\"2\">"+articleDataset.getArticle_date()+" </font></label></div>";
html=html+"<div><label> <font color=\"#000000\" face=\"verdana\" size=\"2\">"+summary+" </font></label></div></body></html>" ;
webviewcontent.getSettings().setJavaScriptEnabled(true);
webviewcontent.clearCache(true);
final Activity activity = HomeActivity2.this;
webviewcontent.loadData(html, "text/html", "utf-8");
if(i==articleParsedValue1.size()-1)
{
webviewcontent.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url)
{
// setContentView(R.layout.home);
if (dlg.isShowing())
{
dlg.dismiss();
dlg = null;
}
splash.setVisibility(View.GONE);
// setContentView(repl);
}
});
}
mainlinear4.addView(webviewcontent);
//webviewcontent.setOnTouchListener(HomeActivity2.this);
}
}
List<String> data; // declare here so that we can use it in onPostExecute().
public class YourActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
starttask();
}
private void starttask() {
new FileAsync().execute("start");
Toast toast = Toast.makeText(yourActivity.this," start:" , 7);toast.show();
}
class FileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
m_ProgressDialog = ProgressDialog.show(yourActivity.this,
"", "Loading ...", true);
}
#Override
protected String doInBackground(String... aurl) {
// These methods are calling data from web service made
// in sperate class but you can do this here as well.
TempDAO tempDAO = new TempDAOImpl();
data = tempDAO.getDataList(arg1,arg2);
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
}
#Override
protected void onPostExecute(String unused) {
TextView textData= new TextView(YourActivity.this);
textData.setText(data.get(1));
textData.setTextColor(Color.WHITE);
textData.setGravity(Gravity.CENTER);
setContentView(textData);
m_ProgressDialog.dismiss();
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
AlertDialog.Builder builder;
protected void onPreExecute() {
super.onPreExecute();
builder = new AlertDialog.Builder(TabGroup2ProductsActivity.this);
}
#Override
protected String doInBackground(String... urls) {
if (urls.length == 1) {
return POST(urls[0]);
} else {
if ("pdf".equalsIgnoreCase(urls[1])) {
downloadPDF(urls[0]);
return "";
} else {
downloadImage(urls[0]);
return "";
}
}
}
#Override
protected void onPostExecute(String result) {
}
}
public String POST(String url) {
System.out.println("I am in post data./..............................");
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(url);
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
System.out.println("Status is : " + status);
ParseProductJson parseJson = new ParseProductJson();
if (status == 200) {
result = EntityUtils.toString(response.getEntity());
System.out
.println("################result1###############################"
+ result);
FileOutputStream fos = openFileOutput("productsJson.json",
Context.MODE_PRIVATE);
fos.write(result.getBytes());
fos.close();
System.out.println("Done");
HashMap<String, List<Product>> hashmap = parseJson
.parseProductJson(readProductsJSON("productsJson.json"));
arrGroupelements = parseJson.getHeadingArray(hashmap);
arrChildelements = parseJson.get2dArray(hashmap);
statusClass = status;
} else {
statusClass = 400;
result = "Did not work!";
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
and from Activity onCreate(){
int statusClass = 2;
new HttpAsyncTask()
.execute("http://104.130.240.26:8080/bhn/service/products/");
do {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (statusClass == 2);
}
Sample Async task to request webservice
Following is the way how to make AsyncTask :
private class AsyncTaskGetPlaces extends AsyncTask<Void, Void, AsyncTaskResult<Object>>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected AsyncTaskResult<Object> doInBackground(Void... params)
{
try
{
LibHttp libHttp = new LibHttp();
String res = libHttp.listBusiness("21","test#ns.com");
return new AsyncTaskResult<Object>(res);
}
catch (Exception e)
{
e.printStackTrace();
return new AsyncTaskResult<Object>(e);
}
}
#Override
protected void onPostExecute(AsyncTaskResult<Object> result)
{
if(result.getError()!= null)
{
showOKAlertMsg("App",getResources().getString(R.string.txt_data_not_found), false);
}
else
{
String res = result.getResult().toString();
try {
JSONObject resObj = new JSONObject(res);
if(resObj.getString("status_code").equals("1")){
//parse
// Do your task here
}
} catch (JSONException e) {
e.printStackTrace();
showOKAlertMsg("",getResources().getString(R.string.txt_internal_server_error), false);
}
}
}
}
Where AsyncTaskResult is
public class AsyncTaskResult<T>
{
private T result;
private Exception error;
public T getResult()
{
return result;
}
public Exception getError()
{
return error;
}
public AsyncTaskResult(T result)
{
this.result = result;
}
public AsyncTaskResult(Exception error)
{
this.error = error;
}
}
Related
My Activity Code: Note this is not my main activity, right now i am using a button to fetch images from the database but instead I need to fetch all the images when the app load.
public class QuotesPictures extends Activity implements View.OnClickListener {
private String imagesJSON;
private static final String JSON_ARRAY = "result";
private static final String IMAGE_URL = "url";
private JSONArray arrayImages = null;
private int TRACK = 0;
private Button buttonMoveNext;
private Button buttonMovePrevious;
private ImageView imageView;
private static final String IMAGES_URL = "http://stressreliefapp.esy.es/getAllImages.php";
private Button buttonFetchImages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes_pictures);
//Defining all the buttons
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
}
//Using AsyncTask to load the data in the background thread and then publishing on the UI thread
private void getImage(String urlToImage) {
class GetImage extends AsyncTask<String, Void, Bitmap> {
ProgressDialog loading;
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
Bitmap image = null;
String urlToImage = params[0];
try {
url = new URL(urlToImage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(QuotesPictures.this, "Loading Images...", "Please wait...", true, true);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
loading.dismiss();
imageView.setImageBitmap(bitmap);
}
}
GetImage gi = new GetImage();
gi.execute(urlToImage);
}
// Method used to get all the images from the database using AsyncTask
public void getAllImages() {
class GetAllImages extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(QuotesPictures.this, "Loading Images...", "Please wait...", true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
imagesJSON = s;
extractJSON();
showImage();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetAllImages gai = new GetAllImages();
gai.execute(IMAGES_URL);
}
private void extractJSON() {
try {
JSONObject jsonObject = new JSONObject(imagesJSON);
arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showImage() {
try {
JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
getImage(jsonObject.getString(IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext() {
if (TRACK < arrayImages.length()) {
TRACK++;
showImage();
}
}
private void movePrevious() {
if (TRACK > 0) {
TRACK--;
showImage();
}
}
#Override
public void onClick(View v) {
if (v == buttonFetchImages) {
getAllImages();
}
if (v == buttonMoveNext) {
moveNext();
}
if (v == buttonMovePrevious) {
movePrevious();
}
}
}
Just execute your download method in onCreate method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes_pictures);
//Defining all the buttons
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
getImage("your image url");
}
Move your code at onclicklistener to onResume.
public void onResume()
{
super.onResume();
/* your code at OnClickListener */
}
This is my java code. I have been getting no value for url in my android studio. I intend to get image from sql database at wamp server.
public class MainActivity extends AppCompatActivity implements
View.OnClickListener{
private String imagesJSON;
private static final String JSON_ARRAY ="result";
private static final String IMAGE_URL = "url";
private JSONArray arrayImages= null;
private int TRACK = 0;
private static final String IMAGES_URL =
"http://192.168.43.214/apexStore2/image.php";
private Button buttonFetchImages;
private Button buttonMoveNext;
private Button buttonMovePrevious;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(imagesJSON);
arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showImage(){
try {
JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
getImage(jsonObject.getString(IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext(){
if(TRACK < arrayImages.length()){
TRACK++;
showImage();
}
}
private void movePrevious(){
if(TRACK>0){
TRACK--;
showImage();
}
}
private void getAllImages() {
class GetAllImages extends AsyncTask<String,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Fetching
Data...","Please Wait...",true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
imagesJSON = s;
extractJSON();
showImage();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection)
url.openConnection();
con.setRequestProperty("Content-Type",
"application/json;charset=utf-8");
con.setRequestProperty("X-Requested-With",
"XMLHttpRequest");
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new
InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
}
GetAllImages gai = new GetAllImages();
gai.execute(IMAGES_URL);
}
private void getImage(String urlToImage){
class GetImage extends AsyncTask<String,Void,Bitmap>{
ProgressDialog loading;
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
Bitmap image = null;
String urlToImage = params[4];
try {
url = new URL(urlToImage);
image =
BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Downloading
Image...","Please wait...",true,true);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
loading.dismiss();
imageView.setImageBitmap(bitmap);
}
}
GetImage gi = new GetImage();
gi.execute(urlToImage);
}
#Override
public void onClick(View v) {
if(v == buttonFetchImages) {
getAllImages();
}
if(v == buttonMoveNext){
moveNext();
}
if(v== buttonMovePrevious){
movePrevious();
}
}
This is my php code. When i run my php code, i got the following output:
{
"result": [{
"product_img1": "product-131.jpg"
}, {
"product_img1": "product-124.jpg"
}, {
"product_img1": "product-118.jpg"
}, {
"product_img1": "product-126.jpg"
}, {
"product_img1": "USM_New_Logo1.jpg"
}, {
"product_img1": "UI.PNG"
}, {
"product_img1": "cat402.PNG"
}, {
"product_img1": "launcher.png"
}]
}
My php code got fetch the image from sql database, however, my android studio could not fetch it. Is there any solutions to it?
<?php
include ('classes/functions.php');
$check_product = "SELECT * FROM products WHERE cat_id = '0';";
$run_product_checking = mysqli_query($con, $check_product);
$result = array();
while($row = mysqli_fetch_array($run_product_checking)){
array_push($result,
array('product_img1'=>$row[4]
));
}
echo json_encode(array("result"=>$result));
?>
Change the IP-address into it's Domain-name value.
According to your AsyncTask class, you are passing the url as the first parameter,
class GetImage extends AsyncTask<String,Void,Bitmap>{
.....
}
But here you are receiving it as the 4'th parameter,
String urlToImage = params[4];
To solve this, simply replace the param value from 4 to 0,
String urlToImage = params[0];
PS: Make sure the JSON string " IMAGE_URL " doesn't returns null value,
getImage(jsonObject.getString(IMAGE_URL));
I am having a trouble dismiss Progress Dialog if any exception occurs at doInBackground in my AsyncTask as it never reaches the onPostExecute and never dismiss the Progress Dialog which makes ANR.
Below is the code for AsyncTask
private class checkAS extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialogue;
#Override
protected void onPostExecute() {
// TODO Auto-generated method stub
super.onPostExecute();
dialogue.dismiss();
}
#Override
protected Void doInBackground(Void... params) {
//Long Network Task
return null;
}
#Override
protected void onPreExecute(Void result) {
// TODO Auto-generated method stub
super.onPreExecute(result);
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
}
My question is if any exception occurs at doInBackground how will I handle it and how onPostExecute will be called to dismiss the dialogue? I can not dismiss it on doInBackground. How to sync this up?
Try this..
Return something like string from doInBackground. If Exception came catch that assign string value error otherwise return success
private class checkAS extends AsyncTask<Void, Void, String>
{
ProgressDialog dialogue;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
#Override
protected String doInBackground(Void... params) {
//Long Network Task
String result;
try{
result = "success"
}
catch(Exception e){
result = "error";
}
return result;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result.equals("error"))
dialogue.dismiss();
else
// do something
}
}
You are creating dialog dialog in onPostExecute method it should be in onPreExecute method.
try this.
private class checkAS extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialogue;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
#Override
protected Void doInBackground(Void... params) {
//Long Network Task
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialogue.dismiss();
}
}
#Override
protected String doInBackground(String... params)
{
System.out.println("check user profile");
try
{
}
catch (Exception e)
{
e.printStackTrace();
publishProgress((e.getMessage()));
}
return result;
}
#Override
protected void onProgressUpdate(String... values)
{
// TODO Auto-generated method stub
super.onProgressUpdate(values);
Toast.makeText(activity, values[0], Toast.LENGTH_LONG);
if(dialog != null && dialog.isShowing())
dialog.dismiss();
}
#SuppressLint("InlinedApi")
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(dialog != null && dialog.isShowing())
{
dialog.dismiss();
}
}
You may want to dismiss dialog in finally block of try catch construct.
i.e.
try {
...
} catch {
...
finally{
//dismiss dialog here.
}
first check whether the dialog is showing or not using this code you can check
if(dialog.isShowing())
dialog.dismiss();
And use Exception handling to avoid unknown Exceptions
private class checkAS extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
private static final String TAG = "checkAS";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 12000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 12000;
private int taskType = POST_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public checkAS(int taskType, Context mContext, String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
#SuppressWarnings("deprecation")
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
handleResponse(response);
pDlg.dismiss();
}
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost= new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
}
}
catch (Exception e) {
// display("Remote DataBase can not be connected.\nPlease check network connection.");
Log.e(TAG, e.getLocalizedMessage(), e);
return null;
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
public void handleResponse(String response)
{
//display("Response:"+response);
if(!response.equalsIgnoreCase(""))
{
JSONObject jso;
try {
//do your stuff
}
catch (JSONException e1) {
Log.e(TAG, e1.getLocalizedMessage(), e1);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
else
{
display("Could not able to reach Server!");
}
}
Try this:
private class checkAS extends AsyncTask<Void, Void, Boolean> {
ProgressDialog dialogue;
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
dialogue.dismiss();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
Thread.sleep(15000);
} catch (Exception e) {}
return true;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialogue = new ProgressDialog(Main.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
}
This is my Activity class where i use AsyncTask to get data from a server:
public class UserProfileActivity extends Activity {
private ImageView userImage;
private TextView userName;
private TextView userLocation;
private TextView editInfo;
private TextView chnageImage;
private TextView userScore;
private ListView friendsList;
public ArrayAdapter<String> adapter;
public int score;
public int level;
public String image;
public String fname;
public String lname;
public String city;
public int id;
public String email;
protected Activity activity = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_profile);
userImage = (ImageView) findViewById(R.id.profileImage);
userName = (TextView) findViewById(R.id.userName_profile);
userLocation = (TextView) findViewById(R.id.userLocation_profile);
editInfo = (TextView) findViewById(R.id.edit_profile);
chnageImage = (TextView) findViewById(R.id.changeImage_profile);
userScore = (TextView) findViewById(R.id.userScore_profile);
friendsList = (ListView) findViewById(R.id.friendsList);
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
private InputStream is;
private StringBuilder sb;
private String result;
#Override
protected String doInBackground(String... params) {
try {
HttpPost httppost = new HttpPost(
"http://www.xxxxxxxxx.com/mobile/getProfileInfo");
HttpResponse response = SignUpActivity.httpclient
.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
}
try {
JSONObject jObj = new JSONObject(result);
String status = jObj.getString("status");
score = jObj.getInt("credits");
level = jObj.getInt("level");
image = jObj.getString("image");
fname = jObj.getString("fname");
lname = jObj.getString("lname");
city = jObj.getString("city");
id = jObj.getInt("user_id");
email = jObj.getString("email");
JSONArray friendsJsonArray = jObj.getJSONArray("friends");
int size = friendsJsonArray.length();
ArrayList<String> friendsNames = new ArrayList<String>();
String[] friendsIds = new String[size];
for (int i = 0; i < size; i++) {
friendsNames.add(friendsJsonArray.getJSONObject(i)
.getString("name"));
}
adapter = new ArrayAdapter<String>(getApplicationContext(),
R.layout.simple_listview_item, friendsNames);
} catch (Exception e) {
}
} catch (Exception e) {
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
friendsList.setAdapter(adapter);
userScore.setText(score + " points" + " level " + level);
userName.setText(fname + " " + lname);
userLocation.setText(city);
Bitmap bitmap = null;
try {
bitmap = BitmapFactory
.decodeStream((InputStream) new URL(image).getContent());
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
userImage.setImageBitmap(bitmap);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
when this activity is loaded it shows all the default values and images and then changes when background code execution is competed(as excepted), but this takes 2-3 secs for which user will be seeing default values, which i dont want to. So how can i keep a spinner like this:
for 2-3 secs and then when the spinner disappears the activity must show the actual values.
Thank you
Refer the below code
private class FetchRSSFeeds extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(HomeActivity.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
#Override
protected Boolean doInBackground(final String... args) {
try {
Utilities.arrayRSS = objRSSFeed
.FetchRSSFeeds(Constants.Feed_URL);
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
// Setting data to list adapter
setListData();
}
Do This:-
Declare the ProgressDialog at the Top.
ProgressDialog pd;
Start it in onPreExecute Method of Async Task.
pd=ProgressDialog.show(ActivityName.this,"","Please Wait",false);
Stop it in the onPostExecute Method.
pd.dismiss();
In onCreate method call some like below
mdialog=new Dialog(this);
new LongOperation().execute("");
Then override onPostExecute of AyncTask
#Override
protected void onPostExecute() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mdialog.dismiss();
}
});
}
I believe I'm doing this correctly, in my activity class I'm calling execute the alert dialog appears and then the data load but the alert dialog never goes away. Here is my AsyncTask code:
Followed by my activity code.
public class Worker extends AsyncTask<URL, Integer, Long>{
private Activity ne;
private ProgressDialog progressDialog;
private Handler handler;
public Worker(Handler handler, Activity ne){
this.handler = handler;
this.ne = ne;
}
protected void onPreExecute() {
progressDialog = ProgressDialog.show(ne,"", "Retrieving News Events", true);
}
protected void onProgressUpdate(Void... progress) {
}
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
/* (non-Javadoc)
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Long doInBackground(URL... urls) {
HttpClient client = new DefaultHttpClient();
HttpGet get;
try {
get = new HttpGet(urls[0].toURI());
ResponseHandler<String> response = new BasicResponseHandler();
String responseBody = client.execute(get, response);
String page = responseBody;
Bundle data = new Bundle();
data.putString("page",page);
Message msg = new Message();
msg.setData(data);
handler.sendMessage(msg);
}
catch (Throwable t) {
Log.d("UpdateNews", "PROBLEMS");
}
return null;
}
}
public class NewsEvents extends ListActivity{
private URL JSONNewsEvents;
private ArrayList<NewsEvent> neList;
private ArrayList<String> keyWordList;
private Worker worker;
private TextView selection;
private ProgressDialog progressDialog;
static final int PROGRESS_DIALOG = 0;
public static final String KEYWORDS = "keywords";
private NewsEvents ne;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsevents);
ne = this;
neList = new ArrayList<NewsEvent>();
selection=(TextView)findViewById(R.id.selection);
try {
JSONNewsEvents = new URL(getString(R.string.jsonnewsevents));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
worker = new Worker(handler, this);
setListAdapter(new IconicAdapter());
getKeywords();
worker.execute(JSONNewsEvents);
}
/**
* #return
*/
public ArrayList<String> getKeywords(){
try {
InputStream fi = openFileInput(KEYWORDS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
keyWordList = (ArrayList<String>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(keyWordList == null){
keyWordList = new ArrayList<String>();
return keyWordList;
}
return keyWordList;
}
public void onListItemClick(ListView parent, View v,
int position, long id) {
startFullNewsEvent(neList.get(position));
}
/**
* #param newsEvent
*/
public void startFullNewsEvent(NewsEvent ne) {
Intent intent = new Intent(this, FullNewsEvent.class);
intent.putExtra("ne", ne);
this.startActivity(intent);
finish();
}
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
String page = msg.getData().getString("page");
try {
JSONArray parseArray = new JSONArray(page);
for (int i = 0; i < parseArray.length(); i++) {
JSONObject jo = parseArray.getJSONObject(i);
String title = jo.getString("title");
String body =jo.getString("body");
String pd = jo.getString("postDate");
String id = jo.getString("id");
NewsEvent ne = new NewsEvent(title, pd , body, id);
boolean unique = true;
for(NewsEvent ne0 : neList){
if(ne.getId().equals(ne0.getId())){
unique = false;
}else{
unique = true;
}
}
if(unique == true){
neList.add(ne);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ne.setListAdapter(new IconicAdapter());
}
};
public class IconicAdapter extends ArrayAdapter<NewsEvent> {
IconicAdapter() {
super(NewsEvents.this, R.layout.rownews, neList);
}
public View getView(int position, View convertView,ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.rownews, parent, false);
TextView label=(TextView)row.findViewById(R.id.label);
ImageView image= (ImageView)row.findViewById(R.id.icon);
String body = neList.get(position).getBody();
body.replaceAll("\\<.*?>", "");
String title = neList.get(position).getTitle();
for(String s : keyWordList){
if(body.contains(s) || body.contains(s.toLowerCase()) ||
title.contains(s) || title.contains(s.toLowerCase())){
neList.get(position).setInterested(true);
}
}
if(neList.get(position).isInterested() == true){
image.setImageResource(R.drawable.star);
}
label.setText(neList.get(position).getTitle());
return(row);
}
}
}
First of all change your onPostExecute to include the #Override:
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
In your class definition include this:
public class Worker extends AsyncTask<Void, Void, Void>
The first parameter is the type of input to the doInBackground method, the second is the type of the input to the onProgressUpdate and the third is the type of the input to the onPostExecute and the result from doInBackground.
It does not look like you are using the input parameter to the doInBackground method, so just change that to Void... and change the return type as well:
protected Void doInBackground(Void... paramArrayOfParams) { ... }
Does this help?
Edit:
I saw you had changed your code to use the parameter of the doInBackground, so the first parameter in your class definition is correct. However, try putting Void as the two last parameters. And change the return type of the doInBackground to Void too.
Like this:
public class Worker extends AsyncTask<URL, Void, Void>{
private Activity ne;
private ProgressDialog progressDialog;
private Handler handler;
public Worker(Handler handler, Activity ne){
this.handler = handler;
this.ne = ne;
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(ne,"", "Retrieving News Events", true);
}
protected void onProgressUpdate(Void... progress) {
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
/* (non-Javadoc)
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Void doInBackground(URL... urls) {
HttpClient client = new DefaultHttpClient();
HttpGet get;
try {
get = new HttpGet(urls[0].toURI());
ResponseHandler<String> response = new BasicResponseHandler();
String responseBody = client.execute(get, response);
String page = responseBody;
Bundle data = new Bundle();
data.putString("page",page);
Message msg = new Message();
msg.setData(data);
handler.sendMessage(msg);
}
catch (Throwable t) {
Log.d("UpdateNews", "PROBLEMS");
}
return null;
}
You're not overriding the asynctask method correctly. Take a look at an example
http://developer.android.com/reference/android/os/AsyncTask.html
and note now they declare their asynctask
extends AsyncTask<URL, Integer, Long>