Sunday, July 11, 2010

Splashscreen, Customizing List, Connecting Internet, XML Parsing,Downloading Images, Updating the User Interface Images at Runtime

Hi Friends,

              Here is the next part of my blog. Here I am going to discuss about the important things today. Every project will starts with a splash in first page. So let’s discuss about the splash.

 

Splash Screen

              We need to display the logo at the middle of the screen, whatever the screen mode it may be. So in order to handle this we will use the below XML file.

 

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:background="@color/white">

 

<ImageView android:id="@+id/ImageView01"

android:scaleType="center"

android:layout_height="fill_parent"

android:layout_width="fill_parent"

android:layout_centerInParent="true" android:src="@drawable/sun">

</ImageView>

</LinearLayout>

 

In the above XML file we have a layout with an ImageView which is centered in parent, without stretching it completely to its parent. Here according to the background of the logo we need to change the background color of the layout. Here it is “@color/White” in the above example. These colors will be maintained in project\res\values\color.xml folder. We can add new colors, which are needed for our project over there. That’s it, our layout is ready now. Let’s go to source.

 

 

             

              There is a class named Handler in android which will be going to handle the assigned work to do after some particular time. You may already know that we can start the Activities by using the Intents, we will start the activity after a period of splashTime as shown below.

 

 

 

new Handler().postDelayed(new Runnable(){

            public void run() {

                          startActivity(new Intent(MainActivity.this, MainMenu.class));

                finish();

            }

        }, _splashTime);

 

              Finally we are moving to the main menu from splash. The whole above process works perfectly if and only if the logo doesn’t have designs and different colors on the background screen. If you have different kinds of logo with lot of background colors  then let’s go for the second option.

              Here we need to prepare two images of splash one is for portrait and another is for landscape.  Create a xml file in the folder project\res\layout-land\menu.xml with the same name in the layout folder. According to the screen mode the xml files will be used. But don’t forget to maintain the same names just like in \layout folder.

 

If we want Fade-in or fade-out effects for our splash then we need to create xml files with desired effects as shown below and need to place it in \anim folder.

 

 

<?xml version="1.0" encoding="utf-8"?>

<set>

  <alpha xmlns:android="http://schemas.android.com/apk/res/android"

              android:interpolator="@android:anim/accelerate_interpolator"

              android:fromAlpha="0.0"

              android:toAlpha="1.0"

              android:duration="1000" />

</set>

fromAlpha, toAlpha and duration will be used according to your requirements. If we change the values fromAlpha to toAlpha then we will get fadeout effect.

The total source with Fadein and Fadeout effects  can be downloaded from below link.

You can download the project with source from here. or You can download the project with source from here.

Customizing List, Connecting Internet, XML Parsing,Downloading Images, Updating the User Interface Images at Runtime, Handling UI without specifying height and width of any view in the layout

 

Connecting to the internet

              We have two methods in connecting the internet server.

1.      Get

2.      Post

In first method as you already know all the values will be appended to the url . In the second (Post) method we will send the data separately which is secured. I am going to give both the methods to connect the net.

1)Get Method

 

 

 

 

 

 

 

 

 

 

 

private InputStream openHttpConnection(String urlStr) {

                            InputStream in = null;

                            int resCode = -1;

                           

                            try {

                            Log.d("openHttpConnection", "URL:"+urlStr);

                            URL url = new URL(urlStr);

                            URLConnection urlConn = url.openConnection();//Opening Connection

                                         

                            if (!(urlConn instanceof HttpURLConnection)) {

                                          throw new IOException ("URL is not an Http URL");

                            }

                            Log.d("openHttpConnection", "httpConn:1");

                            HttpURLConnection httpConn = (HttpURLConnection)urlConn;

                            httpConn.setAllowUserInteraction(false);

            httpConn.setInstanceFollowRedirects(true);

            httpConn.setRequestMethod("GET");

            httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux "+"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");

            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            Log.d("openHttpConnection", "setting requests and properties");

            httpConn.connect();

            Log.d("openHttpConnection", "Connected successfully");

           

            resCode = httpConn.getResponseCode();   

           

            Log.d("openHttpConnection", "resCode"+resCode);

            if (resCode == HttpURLConnection.HTTP_OK) {

                in = httpConn.getInputStream();

                Log.d("openHttpConnection", "Fetchinf data done");

            }        

                            } catch (MalformedURLException e) {

                                          e.printStackTrace();

                                          Log.d("openHttpConnection", "1"+e);

                            } catch (IOException e) {

                                          e.printStackTrace();

                                          Log.d("openHttpConnection", ""+e);

                            }

                            return in;

              }

 

The above code will connect to the specific site and will get the response and the data in the form of InputStream. The variable resCode will get the  response from the server. The value should be 200 i.e., HttpURLConnection.HTTP_OK otherwise we have some problem with server.

2)Post Method:

              This method will send the data separately .The code is as shown below.This method needs two strings. One is for URL and the other is for the data which we want to post the data.

 

 

private InputStream postPage(String url, String data) {

                  InputStream is = null;

                  ret = null;

 

                  httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);

 

                  httpPost = new HttpPost(url);

                  response = null;

 

                  StringEntity tmp = null;                           

 

                  httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux " +

                                "i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");

                  httpPost.setHeader("Accept", "text/html,application/xml," +

                                "application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");

                  httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

 

                  try {

                                tmp = new StringEntity(data,"UTF-8");

                  } catch (UnsupportedEncodingException e) {

                                System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);

                  }

 

                  httpPost.setEntity(tmp);

 

                  try {

                                response = httpClient.execute(httpPost,localContext);

                  } catch (ClientProtocolException e) {

                                System.out.println("HTTPHelp : ClientProtocolException : "+e);

                  } catch (IOException e) {

                                System.out.println("HTTPHelp : IOException : "+e);

                  }

                ret = response.getStatusLine().toString();

                HttpEntity he = response.getEntity();

                try {

                                                                      InputStream inStream = he.getContent();

                                                                      is = inStream;

                                                        } catch (IllegalStateException e) {

                                                                      // TODO Auto-generated catch block

                                                                      e.printStackTrace();

                                                        } catch (IOException e) {

                                                                      // TODO Auto-generated catch block

                                                                      e.printStackTrace();

                                                        }

                                                        return is;

                  }

 

 

 

 

Downloading Images

              Lets discuss about downloading the images. Here we have some issues with google api. Some times this is throwing decoder->decode returned false.  For this I am also trying. 95% it wont come. Most of the cases it works well and code is as shown below.

 

public Drawable downloadDrawable(String imageUrl) {

    try {

                  Log.d("downloadDrawable", "Starting Connection");

        URL url = new URL(imageUrl);

        URLConnection conn = url.openConnection();

        conn.connect();

        Log.d("downloadDrawable", "Connection Created Successfully");

        InputStream is = conn.getInputStream();

        Log.d("downloadDrawable", "InputStream created Successfully");

        d = Drawable.createFromStream(is, url.toString());

        Log.d("downloadDrawable", "Drawable created Successfully");

                is.close();

                } catch (IOException e) {

                   Log.d("ERROR3", "Ex::"+e);

                }

              return d;

                            }

 

 

Updating UI at Runtime after completion of the downloading Image using AsyncTask

              This is very important one in Android. Normally in the other Technologies we will download the images using a separate Thread. But here if we use the same separate thread then it will create issue at the time of setting the image to the ImageView.

              Android doesn’t support updating the UI in a separate  thread. So, we cannot create a separate thread for updating the UI with images after downloading it. So, Inorder to handle this Android is having a class named AsyncTask. This really helps us a lot. The code is as shown below.

Calling AsyncTask

 

try {

      DownloadFilesTask d = new DownloadFilesTask();

              d.execute(new URL(bookImageUrl));//url of the image

              d.sendObjectImageView(iv_logo);// This is the object to which the image                        //has to set

} catch (Exception e)                                                                                                  e.printStackTrace();

}

 

 

AsyncTask Code

This Class will take care of downloading the image. This is not only for downloading. If we want to know whenever the work completed to it then chose this. The method onPostExecute method will be called by the Asynctask then we can do what ever we want to do after completion of that work. Here we need to set the image to the object that we got from the method sendObjectImageView.

 

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {

                  ImageView iv;

                  int id;

                  protected Long doInBackground(URL... urls) {

                      int count = urls.length;

                      long totalSize = 0;

                      downloadDrawable(urls[0].toString());

                       return totalSize;

                  }

                  public void sendObjectImageView(ImageView ivLogo) {

                                          // TODO Auto-generated method stub

                                this.iv = ivLogo;

                                id = -1;

                            }

                            public void sendObjectImageView(ImageView iv,int id) {

                                          // TODO Auto-generated method stub

                                          this.iv = iv;

                                          this.id = id;

                            }

                            protected void onProgressUpdate(Integer... progress) {

                                Log.d("DownloadFilesTask", "onProgressUpdate"+progress[0]);

                  }

                            protected void onPostExecute(Long result) {

                                          Log.d("DownloadFilesTask", "onPostExecute"+result);

                                          if(d!=null && iv!=null)

                                          {

                                                        iv.setImageDrawable(d);

                                                        if(id!=-1)

                                                        booksImagesList[id] = d;

                                          }

                  }

 

XML Parsing

              The description of these things will be displayed soon. until then check out the project.

 

Layout Handling

              The description of these things will be displayed soon. until then check out the project.

 

Customizing Lists

              The description of these things will be displayed soon. until then check out the project.

 

 

You can download the project source from here or You can download the project source from here

 

25 comments:

  1. Hello,

    Could to tell Android development can be done in DOTNET framework. help me out

    Regards,
    Sitaram

    ReplyDelete
  2. No, Till now there is no such options available....

    ReplyDelete
  3. Ori..pavan putra. Enti malli android ..Stop it

    ReplyDelete
  4. Hi How do i make the buy buttons go to a URL (open up browser) hope you can help.

    Thanks
    Lucy

    ReplyDelete
  5. Hi Guys,
    If you are Mobile App Developer, Here is a chance to showcase your App in front of 1000+ live audience only at Mobile Developer Summit 2010 in Bangalore, by just sending a small pitch which will offer you a chance a glory, fame and the potential to meet the people that can take your App to the next level. For details log on to www.mobiledevelopersummit.com

    ReplyDelete
  6. Hi how would I make the button grab the url from the xml file and download it to /mnt/sdcard/ if it was a .apk file any help would be great

    ReplyDelete
  7. Ok so with this there is a issue somewhere where it does not pull the bookUrl correctly if you do a toast onscreen of the bookUrl you will see it always says the very last url in the xml file. How do I go about fixing this?

    ReplyDelete
  8. @Lucy Try below code

    Uri uri = Uri.parse(url);
    Intent intent=new Intent(Intent.ACTION_VIEW,uri); startActivity(intent);

    ReplyDelete
  9. @twitch Its working perfectly with my project.

    Can you please explain a bit more ......

    Are you inserting the correct values in to bean ?

    If that is proper then it should work well .....

    ReplyDelete
  10. Ok I am in Eclipse with my phone as a dev device I am not using a emulator I used the code posted to Lucy above I used a fresh unzip of your archive and this is my button code I had to import android.net.Uri; here is the rest

    Button b_get_book = (Button)v.findViewById(R.id.Button01);
    b_get_book.setOnClickListener(
    new View.OnClickListener()
    {
    public void onClick(View v) {
    Uri uri = Uri.parse(bookUrl);
    Intent intent=new Intent(Intent.ACTION_VIEW,uri); startActivity(intent);
    Log.d(LOG_TAG, "View Position"+position);
    }
    });

    ReplyDelete
  11. oops I hit the wrong button there that is my button code I had to change url to bookUrl because url threw a error and wanted me to create the local variable. also your link is not working for the download or books.xml it says deleted for inactivity. So using that above it is always going to the last listing in the xml file could you reupload the books.xml file for me as I have edited it and maybe that is my issue. or could you post a working full button code to open in a browser? I am new to all this but I dont get where I am going wrong. Thanks

    ReplyDelete
  12. also i would like to add that it loads all the different items fine like the images and descriptions but it is only passing the very last url in the xml file as the bookUrl any way to email me twitch at hackode 0 com the books.xml or repost it

    ReplyDelete
  13. @Twitch Hi Twitch, Sorry for the missing XML file. That one is a free hosting site and is disabled. I reactivated it...


    Check the project now and temme if u have any issues.....

    ReplyDelete
  14. Ok so in your example xml every site is listed as www.gmail.com switch those up and also change the very last one to something other than gmail.com you will see what I'm talking about. For me it is loading the very last url in that xml file. If this works for you could you post a updated zip of the code? also is my button code correct a few posts up? Im intrigued to know why this is not working right.

    ReplyDelete
  15. Dude, I will check and if there is a need i will surely fix it and update it by nyt or tomarrow morning... am in ofc :) now.

    ReplyDelete
  16. Hey you are the man Thanks for looking into this for me I am stumped lol you can find my xml at ps3-brew.com/books.xml if that helps at all I only changed the urls there.

    ReplyDelete
  17. @Twitch I had checked my code again. That one is working fine. Till now i didn't used the bookURL variable. Now i did. any way i modified the project with your URL and i toasted the URL on the screen and also opening the URL in Browser.

    The link for downloading the source is "http://pavandroid.ucoz.com/XmlParsing_URLUpdate.zip". Download it and check the code. any issues reply me......

    ReplyDelete
  18. Hey thanks its working flawlessly now. I will be sure to send you a copy of this app when I'm done so you can include it in your example here. I modified it heavily and that was the final touch. Thanks again. you should update your links with the new zip.

    ReplyDelete
  19. sorry had to post this to rid my email out of my post name

    ReplyDelete
  20. the xml file is not available :(

    ReplyDelete
  21. Excellent tutorial.wht exactly i am looking .
    Thank u very............. much

    ReplyDelete
  22. Nice Initiation raa Pavan..Good Keep Going..

    ReplyDelete
  23. This is one of the fantastic Information.Your post will help us to clarify our doubt.This is one of the out knowledgeable Information.Android app developers

    ReplyDelete