Reth
Reth

Reputation: 67

How to perform background activity in android?

This is my avtivity...How can I perform test() function in background, so that i can display something before execution of test() ?? Is it possible to load the contents dynamically after displaying the layout???Please help me...........

public class viewstoryActivity extends Activity {

     LinearLayout layout1;

     @Override
     public void onCreate(Bundle savedInstanceState) {

          super.onCreate(savedInstanceState);
          setContentView(R.layout.list);

          /** Create a new layout to display the view */
          //ScrollView sv = (ScrollView)findViewById(R.id.sv);
          layout1 =(LinearLayout)findViewById(R.id.LinearLayout);
          test();           
     } 
     public void test(){

        try{
               LinearLayout layout[];
               LinearLayout layout2[];
               LinearLayout layout3[];
               TextView name[];
               TextView desc[];
               TextView viewCount[];
               ImageView website[];
               ImageView star[];
               TextView category[];
               //ImageButton img[];
               URL url = new URL("http://gdata.youtube.com/feeds/api/videos?start-index=1&max-results=25&vq=itsaperfectstory&orderby=relevance");

               DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
               DocumentBuilder db = dbf.newDocumentBuilder();
               Document doc = db.parse(new InputSource(url.openStream()));
               //doc.getDocumentElement().normalize();

               NodeList nodeList = doc.getElementsByTagName("entry");

               /** Assign textview array lenght by arraylist size */
               layout= new LinearLayout[nodeList.getLength()];
               layout2= new LinearLayout[nodeList.getLength()];
               layout3= new LinearLayout[nodeList.getLength()];
               name = new TextView[nodeList.getLength()];
               desc = new TextView[nodeList.getLength()];
               viewCount = new TextView[nodeList.getLength()];
               website = new ImageView[nodeList.getLength()];
               star = new ImageView[nodeList.getLength()];
               category = new TextView[nodeList.getLength()];
                   //img = new ImageButton[nodeList.getLength()];

               for (int i = 0; i < nodeList.getLength(); i++) {

                        Node node = nodeList.item(i);
                        layout[i]= new LinearLayout(this);
                        layout[i].setOrientation(LinearLayout.HORIZONTAL);
                        layout[i].setBackgroundResource(R.anim.bg);
                        layout[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,150));
                        layout2[i]= new LinearLayout(this);
                        layout2[i].setOrientation(LinearLayout.VERTICAL);
                        layout2[i].setLayoutParams(new LayoutParams(400,150));
                        layout3[i]= new LinearLayout(this);
                        layout3[i].setOrientation(LinearLayout.VERTICAL);
                        layout3[i].setLayoutParams(new LayoutParams(150,150));
                        name[i] = new TextView(this);
                        desc[i] = new TextView(this);
                        viewCount[i]=new TextView(this);
                        website[i] = new ImageView(this);
                        star[i]=new ImageView(this);
                        category[i] = new TextView(this);
                        //img[i] = new ImageButton(this);
                        //img[i].setBackgroundResource(R.anim.button);
                        //img[i].setLayoutParams(new LayoutParams(74,35));
                        name[i].setPadding(10, 20,0,0);
                        name[i].setTextSize(16);
                        Element fstElmnt = (Element) node;

                        NodeList nameList = fstElmnt.getElementsByTagName("title");
                        Element nameElement = (Element) nameList.item(0);
                        nameList = nameElement.getChildNodes();
                        name[i].setText(((Node) nameList.item(0)).getNodeValue());
                        name[i].setLines(1);

                        NodeList websiteList = fstElmnt.getElementsByTagName("media:content");
                        Element websiteElement = (Element) websiteList.item(0);
                        websiteList = websiteElement.getChildNodes();
                        final String url1=websiteElement.getAttribute("url");

                        NodeList websiteList1 = fstElmnt.getElementsByTagName("media:thumbnail");
                        Element websiteElement1 = (Element) websiteList1.item(0);
                        String test=websiteElement1.getAttribute("url");

                        NodeList descitem = fstElmnt.getElementsByTagName("content");
                        Element descElement = (Element) descitem.item(0);
                        nameList = descElement.getChildNodes();
                        desc[i].setText(((Node) nameList.item(0)).getNodeValue());
                        desc[i].setLines(1);
                        desc[i].setTextColor(Color.DKGRAY);
                        desc[i].setPadding(10,8,0,0);                   

                        NodeList gditem = fstElmnt.getElementsByTagName("yt:statistics");
                        Element gdElement = (Element) gditem.item(0);
                        String view1=gdElement.getAttribute("viewCount");
                        viewCount[i].setText(view1+" views");
                        viewCount[i].setPadding(10,8,0,0);
                        Bitmap bm = null;  URL aURL = new URL(test); URLConnection conn = aURL.openConnection(); conn.connect();
                        InputStream is = conn.getInputStream(); BufferedInputStream bis = new  BufferedInputStream(is); 
                        bm = BitmapFactory.decodeStream(bis); bis.close(); is.close();  // TODO:  handle exception 
                        website[i].setImageBitmap(bm);
                        website[i].setPadding(30, 20, 0, 0);

                        layout3[i].addView(website[i]);
                        layout2[i].addView(name[i]);
                        layout2[i].addView(desc[i]);
                        layout2[i].addView(viewCount[i]);
                        NodeList staringitem = fstElmnt.getElementsByTagName("gd:rating");
                        if ((staringitem==null)||(staringitem.getLength()==0)) {                        
                            star[i].setImageResource(R.drawable.star0);
                            layout2[i].addView(star[i]);
                        }
                        else
                        {
                            Element starElement = (Element) staringitem.item(0);
                            String stars = starElement.getAttribute("average");
                            double d=Double.parseDouble(stars);
                            DecimalFormat decimalFormat=new DecimalFormat("#");
                            stars=decimalFormat.format(d);
                            if (stars.contentEquals("1")) {

                                star[i].setImageResource(R.drawable.star1);
                                layout2[i].addView(star[i]);
                            }
                            else if (stars.contentEquals("2")) {

                                 star[i].setImageResource(R.drawable.star2);
                                 layout2[i].addView(star[i]);
                            }
                            else if (stars.contentEquals("3")) {

                                 star[i].setImageResource(R.drawable.star3);
                                 layout2[i].addView(star[i]);
                            } 
                            else if (stars.contentEquals("4")) {

                                 star[i].setImageResource(R.drawable.star4);
                                 layout2[i].addView(star[i]);
                            }
                            else if (stars.contentEquals("5")) {

                                 star[i].setImageResource(R.drawable.star5);
                                 layout2[i].addView(star[i]);
                            } 
                            else if (stars.contentEquals("0")) {

                                 star[i].setImageResource(R.drawable.star0);
                                 layout2[i].addView(star[i]);
                            }
                         }
                         layout[i].addView(layout3[i]);
                         layout[i].addView(layout2[i]);
                         //layout.addView(category[i]);
                         //layout[i].addView(img[i]);
                         ((LinearLayout)layout1).addView(layout[i]);
                         layout[i].setOnClickListener(new OnClickListener() {

                              public void onClick(View v) {

                                  /*Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url1));                    
                                  startActivity(intent);*/
                                  Bundle bundle = new Bundle();
                                  // add data to bundle
                                  bundle.putString("url", url1);
                                  Intent intent=new     Intent(viewstoryActivity.this , VidActivity.class);
                                  intent.putExtras(bundle);
                                  startActivityForResult(intent, 0);
                                  overridePendingTransition  (R.anim.right_slide_out, R.anim.right_slide_out);
                              }     
                        });
               }
         } 
         catch (Exception e) {

             System.out.println("XML Pasing Excpetion = " + e);
         }

         /** Set the layout view to display */
         // ((ScrollView) sv).addView(layout1);

         //setContentView(sv);
    }
}

Upvotes: 0

Views: 322

Answers (3)

Hiral Vadodaria
Hiral Vadodaria

Reputation: 19250

Create a subclass:

public class LoadData extends AsyncTask<Void, Void, Void>
{       
    ProgressDialog progressDialog;
        //declare other objects as per your need

    @Override
    protected void onPreExecute()
    {
        progressDialog= ProgressDialog.show(YourActivity.this, "Progress Dialog Title Text","Process Description Text", true);

        //do initialization of required objects objects here                
    };      
    @Override
    protected Void doInBackground(Void... params)
    {   
         test();
         //do other operation as required   
        return null;
    }       
    @Override
    protected void onPostExecute(Void result)
    {
        super.onPostExecute(result);
        progressDialog.dismiss();
    };      
}

Now create its objects wherever you need to load data and use it like:

...
LoadData ld=new LoadData();
ld.execute();    
...

Using this will give you a progess dialog with activity running in background and does not let user do anything until it completes the operation. You can set your custom title text and description text here in onPreExecute(),as per your requirement.

Upvotes: 0

Sandeep Kumar P K
Sandeep Kumar P K

Reputation: 7482

Create a class extending AsyncTask as

private class DownloadTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        test();
        return "";
    }

    @Override
    protected void onPostExecute(String result) {
    }
}

In oncreate you can execute test() as

DownloadTask task = new DownloadTask();
    task.execute();

Upvotes: 1

P Varga
P Varga

Reputation: 20269

Use an AsyncTask for background operations.

Upvotes: 2

Related Questions