0

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);
    }
}
Hiral Vadodaria
  • 19,158
  • 5
  • 39
  • 56
Reth
  • 67
  • 1
  • 10

3 Answers3

2

Use an AsyncTask for background operations.

P Varga
  • 19,174
  • 12
  • 70
  • 108
1

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();
Sandeep Kumar P K
  • 7,412
  • 6
  • 36
  • 40
  • THank you ,sandy!! But i got an error notification like "The constructor LinearLayout(viewstoryActivity.LoadData) is undefined" while defining new items inside the for loop .. – Reth Jan 12 '12 at 08:00
  • Create a `public Context context;` variable and then in `onCreate()` method you have to do `context = this;` and replace all `this` in `test()` method with `context` – Sandeep Kumar P K Jan 12 '12 at 08:13
  • tried this out...the errors are gone..but I could not see any content in my layout... – Reth Jan 12 '12 at 08:27
  • this was the error.."01-12 14:36:01.980: I/System.out(6026): XML Pasing Excpetion = android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views." – Reth Jan 12 '12 at 09:06
0

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.

Hiral Vadodaria
  • 19,158
  • 5
  • 39
  • 56
  • thanks Hiral!! But i got an rror notification like "The constructor LinearLayout(viewstoryActivity.LoadData) is undefined" while defining new items inside the for loop... – Reth Jan 12 '12 at 07:39
  • Use YourActivity.this there.it is context conflict. – Hiral Vadodaria Jan 12 '12 at 07:50
  • Here in this case "YourActivity.this" is "viewstoryActivity.this" right? – Reth Jan 12 '12 at 07:58
  • Yes.You just need to pass correct context there as an argument in LinearLayout. – Hiral Vadodaria Jan 12 '12 at 08:00
  • Im a newbie to both android and java...sorry if it seems stupid; wot does an appropriate context be like, in my case ?? – Reth Jan 12 '12 at 08:02
  • It is clearly said in the error you get in logcat.You cannot create a LinearLayout with context of AsyncTask.So here you need to pass your activity's context into LinearLayout constructor.For more reference on context,please refer http://developer.android.com/reference/android/content/Context.html and http://stackoverflow.com/questions/3572463/what-is-context-in-android – Hiral Vadodaria Jan 12 '12 at 08:08