开发者

How to implement ASyncTask in Android

开发者 https://www.devze.com 2023-02-06 20:20 出处:网络
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

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\" si开发者_高级运维ze=\"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;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消