• Thumbnail

     

    Kota Malang telah menaklukan hati banyak traveler dengan pesonanya. Banyak kekayaan alam dan tempat wisata lainnya yang menjadi kelebihan kota apel ini. Malang semakin menjadi salah satu destinasi yang […]

  • ThumbnailAplikasi Mobile View merupakan aplikasi yang dibangung dengan komponen Web View pada android dan dikolaborasi dengan komponen jQuery mobile. Aplikasi ini bisa juga dibangun dengan memanfaatkan phonegap sebagai […]

  • STACKSITES ANDROID

    Aplikasi StackSites merupakan aplikasi android yang menampilkan situs web. situs web yang tersedia yaitu SIAM, Herman Class, Website PTIIK, Dota2Lounge, dan 9gag. Situs web ini diperoleh dari file xml yang telah dibuat di Dropbox, sehingga Dropbox berperan sebagai server. File xml berisi link website yang akan diakses beserta logonya. File xml pada server di parsing agar dapat ditampilkan pada sistem android.

     

    Berikut tampilan source code MainActivity.java

    package com.makemyandroidapp.example.stacksites;import java.io.FileNotFoundException;

     

    import android.app.Activity;

    import android.content.Context;

    import android.content.Intent;

    import android.net.ConnectivityManager;

    import android.net.NetworkInfo;

    import android.net.Uri;

    import android.os.AsyncTask;

    import android.os.Bundle;

    import android.util.Log;

    import android.view.View;

    import android.widget.AdapterView;

    import android.widget.AdapterView.OnItemClickListener;

    import android.widget.ListView;

     

    public class MainActivity extends Activity {

     

          private SitesAdapter mAdapter;

          private ListView sitesList;

     

     

          @Override

          protected void onCreate(Bundle savedInstanceState) {

                super.onCreate(savedInstanceState);

                Log.i(“StackSites”, “OnCreate()”);

                setContentView(R.layout.activity_main);

     

                //Get reference to our ListView

                sitesList = (ListView)findViewById(R.id.sitesList);

     

                //Set the click listener to launch the browser when a row is clicked.

                sitesList.setOnItemClickListener(new OnItemClickListener() {

     

                      @Override

                      public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {

                            String url = mAdapter.getItem(pos).getLink();

                            Intent i = new Intent(Intent.ACTION_VIEW);

                            i.setData(Uri.parse(url));

                            startActivity(i);

     

                      }

     

                });

     

                /*

                * If network is available download the xml from the Internet.

                * If not then try to use the local file from last time.

                */

                if(isNetworkAvailable()){

                      Log.i(“StackSites”, “starting download Task”);

                      SitesDownloadTask download = new SitesDownloadTask();

                      download.execute();

                }else{

                      mAdapter = new SitesAdapter(getApplicationContext(), -1, SitesXmlPullParser.getStackSitesFromFile(MainActivity.this));

                      sitesList.setAdapter(mAdapter);

                }

     

          }

     

          //Helper method to determine if Internet connection is available.

          private boolean isNetworkAvailable() {

              ConnectivityManager connectivityManager

                     = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

              NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

              return activeNetworkInfo != null && activeNetworkInfo.isConnected();

          }

     

          /*

          * AsyncTask that will download the xml file for us and store it locally.

          * After the download is done we’ll parse the local file.

          */

          private class SitesDownloadTask extends AsyncTask<Void, Void, Void>{

     

                @Override

                protected Void doInBackground(Void… arg0) {

                      //Download the file

                      try {

                            Downloader.DownloadFromUrl(“https://dl.dropboxusercontent.com/s/rhekn85r1unt1cc/stacksite.xml?dl=0”, openFileOutput(“StackSites.xml”, Context.MODE_PRIVATE));

                      } catch (FileNotFoundException e) {

                            e.printStackTrace();

                      }

     

                      return null;

                }

     

                @Override

                protected void onPostExecute(Void result){

                      //setup our Adapter and set it to the ListView.

                      mAdapter = new SitesAdapter(MainActivity.this, -1, SitesXmlPullParser.getStackSitesFromFile(MainActivity.this));

                      sitesList.setAdapter(mAdapter);

                      Log.i(“StackSites”, “adapter size = “+ mAdapter.getCount());

                }

          }

     

    }

     

     

    Berikut tampilan source code MainAnnotationsActivity.java

    package com.makemyandroidapp.example.stacksites;/*

    import java.io.FileNotFoundException;

     

    import android.app.Activity;

    import android.content.Context;

    import android.content.Intent;

    import android.net.ConnectivityManager;

    import android.net.NetworkInfo;

    import android.net.Uri;

    import android.os.Bundle;

    import android.widget.ListView;

     

    import com.googlecode.androidannotations.annotations.AfterViews;

    import com.googlecode.androidannotations.annotations.Background;

    import com.googlecode.androidannotations.annotations.EActivity;

    import com.googlecode.androidannotations.annotations.ItemClick;

    import com.googlecode.androidannotations.annotations.UiThread;

    import com.googlecode.androidannotations.annotations.ViewById;

     

    @EActivity(R.layout.activity_main)

    public class MainAnnotationsActivity extends Activity {

     

          private SitesAdapter mAdapter;

     

          @ViewById

          ListView sitesList;

     

          @Override

          protected void onCreate(Bundle savedInstanceState) {

                super.onCreate(savedInstanceState);

          }

          @AfterViews

          public void refreshUI(){

                if(isNetworkAvailable())

                      fetchFeed();

                else

                      loadList();

          }

     

          @ItemClick

          protected void sitesListItemClicked(StackSite selectedSite) {

                String url = selectedSite.getLink();

                Intent i = new Intent(Intent.ACTION_VIEW);

                i.setData(Uri.parse(url));

                startActivity(i);

          }

     

          @Background

          protected void fetchFeed(){

                try {

                      Downloader.DownloadFromUrl(“https://dl.dropboxusercontent.com/u/5724095/XmlParseExample/stacksites.xml”, openFileOutput(“StackSites.xml”, Context.MODE_PRIVATE));

                      loadList();

                } catch (FileNotFoundException e) {

                      e.printStackTrace();

                }

          }

     

          @UiThread

          protected void loadList(){

                mAdapter = new SitesAdapter(this, -1, SitesXmlPullParser.getStackSitesFromFile(this));

                sitesList.setAdapter(mAdapter);

          }

     

          //Helper method to determine if Internet connection is available.

          private boolean isNetworkAvailable() {

                ConnectivityManager connectivityManager

                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

                NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

                return activeNetworkInfo != null && activeNetworkInfo.isConnected();

          }

    }

    */

     

     

    Berikut tampilan source code Downloader.java

    package com.makemyandroidapp.example.stacksites;import java.io.BufferedInputStream;

    import java.io.BufferedOutputStream;

    import java.io.FileOutputStream;

    import java.io.IOException;

    import java.io.InputStream;

    import java.net.URL;

    import java.net.URLConnection;

     

    import android.util.Log;

     

    /*

    * Helper class for downloading a file.

    */

    public class Downloader {

     

          //Tag for Log statements

          private static String myTag = “StackSites”;

     

          //Handler msg that represents we are posting a progress update.

          static final int POST_PROGRESS = 1;

     

          /************************************************

          * Download a file from the Internet and store it locally

          *

          * @param URL – the url of the file to download

          * @param fos – a FileOutputStream to save the downloaded file to.

          ************************************************/

          public static void DownloadFromUrl(String URL, FileOutputStream fos) { //this is the downloader method

                try {

     

                      URL url = new URL(URL); //URL of the file

     

                      //keep the start time so we can display how long it took to the Log.

                      long startTime = System.currentTimeMillis();

                      Log.d(myTag, “download begining”);

     

                      /* Open a connection to that URL. */

                      URLConnection ucon = url.openConnection();

     

                      // this will be useful so that you can show a tipical 0-100% progress bar

               //int lenghtOfFile = ucon.getContentLength();

     

                      Log.i(myTag, “Opened Connection”);

     

                      /************************************************

                      * Define InputStreams to read from the URLConnection.

                      ************************************************/

                      InputStream is = ucon.getInputStream();

                      BufferedInputStream bis = new BufferedInputStream(is);

                      Log.i(myTag, “Got InputStream and BufferedInputStream”);

     

                      /************************************************

                      * Define OutputStreams to write to our file.

                      ************************************************/

     

                      BufferedOutputStream bos = new BufferedOutputStream(fos);

                      Log.i(myTag, “Got FileOutputStream and BufferedOutputStream”);

     

                      /************************************************

                      * Start reading the and writing our file.

                      ************************************************/

                      byte data[] = new byte[1024];

               //long total = 0;

               int count;

               //loop and read the current chunk

               while ((count = bis.read(data)) != -1) {            

                     //keep track of size for progress.

                   //total += count;

     

                     //write this chunk

                   bos.write(data, 0, count);

               }

                      //Have to call flush or the file can get corrupted.

                      bos.flush();

                      bos.close();

     

                      Log.d(myTag, “download ready in “

                                  + ((System.currentTimeMillis() – startTime))

                                  + ” milisec”);

                } catch (IOException e) {

                      Log.d(myTag, “Error: ” + e);

                }

          }

    }     static final int POST_PROGRESS = 1;

     

          /************************************************

          * Download a file from the Internet and store it locally

          *

          * @param URL – the url of the file to download

          * @param fos – a FileOutputStream to save the downloaded file to.

          ************************************************/

          public static void DownloadFromUrl(String URL, FileOutputStream fos) { //this is the downloader method

                try {

     

                      URL url = new URL(URL); //URL of the file

     

                      //keep the start time so we can display how long it took to the Log.

                      long startTime = System.currentTimeMillis();

                      Log.d(myTag, “download begining”);

     

                      /* Open a connection to that URL. */

                      URLConnection ucon = url.openConnection();

     

                      // this will be useful so that you can show a tipical 0-100% progress bar

               //int lenghtOfFile = ucon.getContentLength();

     

                      Log.i(myTag, “Opened Connection”);

     

                      /************************************************

                      * Define InputStreams to read from the URLConnection.

                      ************************************************/

                      InputStream is = ucon.getInputStream();

                      BufferedInputStream bis = new BufferedInputStream(is);

                      Log.i(myTag, “Got InputStream and BufferedInputStream”);

     

                      /************************************************

                      * Define OutputStreams to write to our file.

                      ************************************************/

     

                      BufferedOutputStream bos = new BufferedOutputStream(fos);

                      Log.i(myTag, “Got FileOutputStream and BufferedOutputStream”);

     

                      /************************************************

                      * Start reading the and writing our file.

                      ************************************************/

                      byte data[] = new byte[1024];

               //long total = 0;

               int count;

               //loop and read the current chunk

               while ((count = bis.read(data)) != -1) {            

                     //keep track of size for progress.

                    //total += count;

     

                     //write this chunk

                   bos.write(data, 0, count);

               }

                      //Have to call flush or the file can get corrupted.

                      bos.flush();

                      bos.close();

     

                      Log.d(myTag, “download ready in “

                                  + ((System.currentTimeMillis() – startTime))

                                  + ” milisec”);

                } catch (IOException e) {

                      Log.d(myTag, “Error: ” + e);

                }

          }

    }

     

     

    Berikut tamplan source code SitesAdapter.java

    package com.makemyandroidapp.example.stacksites;import java.util.List;

     

    import android.content.Context;

    import android.graphics.Bitmap;

    import android.util.Log;

    import android.view.LayoutInflater;

    import android.view.View;

    import android.view.ViewGroup;

    import android.widget.ArrayAdapter;

    import android.widget.ImageView;

    import android.widget.ProgressBar;

    import android.widget.RelativeLayout;

    import android.widget.TextView;

     

    import com.nostra13.universalimageloader.core.DisplayImageOptions;

    import com.nostra13.universalimageloader.core.ImageLoader;

    import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

    import com.nostra13.universalimageloader.core.assist.FailReason;

    import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;

     

     

    /*

    * Custom Adapter class that is responsible for holding the list of sites after they

    * get parsed out of XML and building row views to display them on the screen.

    */

    public class SitesAdapter extends ArrayAdapter<StackSite> {

     

          ImageLoader imageLoader;

          DisplayImageOptions options;

     

     

          public SitesAdapter(Context ctx, int textViewResourceId, List<StackSite> sites) {

                super(ctx, textViewResourceId, sites);

     

                //Setup the ImageLoader, we’ll use this to display our images

           ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx).build();

           imageLoader = ImageLoader.getInstance();

           imageLoader.init(config);

     

           //Setup options for ImageLoader so it will handle caching for us.

           options = new DisplayImageOptions.Builder()

                .cacheInMemory()

                .cacheOnDisc()

                .build();

     

     

          }

     

     

          /*

          * (non-Javadoc)

          * @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)

          *

          * This method is responsible for creating row views out of a StackSite object that can be put

          * into our ListView

          */

          @Override

          public View getView(int pos, View convertView, ViewGroup parent){

                RelativeLayout row = (RelativeLayout)convertView;

                Log.i(“StackSites”, “getView pos = ” + pos);

                if(null == row){

                      //No recycled View, we have to inflate one.

                      LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                      row = (RelativeLayout)inflater.inflate(R.layout.row_site, null);

                }

     

                //Get our View References

                final ImageView iconImg = (ImageView)row.findViewById(R.id.iconImg);

                TextView nameTxt = (TextView)row.findViewById(R.id.nameTxt);

                TextView aboutTxt = (TextView)row.findViewById(R.id.aboutTxt);

                final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress);

     

                //Initially we want the progress indicator visible, and the image invisible

                indicator.setVisibility(View.VISIBLE);

                iconImg.setVisibility(View.INVISIBLE);

     

                //Setup a listener we can use to swtich from the loading indicator to the Image once it’s ready

                ImageLoadingListener listener = new ImageLoadingListener(){

     

     

     

                      @Override

                      public void onLoadingStarted(String arg0, View arg1) {

                            // TODO Auto-generated method stub

     

                      }

     

                      @Override

                      public void onLoadingCancelled(String arg0, View arg1) {

                            // TODO Auto-generated method stub

     

                      }

     

                      @Override

                      public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {

                            indicator.setVisibility(View.INVISIBLE);

                            iconImg.setVisibility(View.VISIBLE);

                      }

     

                      @Override

                      public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {

                            // TODO Auto-generated method stub

     

                      }

     

                };

     

                //Load the image and use our options so caching is handled.

                imageLoader.displayImage(getItem(pos).getImgUrl(), iconImg,options, listener);

     

                //Set the relavent text in our TextViews

                nameTxt.setText(getItem(pos).getName());

                aboutTxt.setText(getItem(pos).getAbout());

     

     

     

                return row;

     

     

          }

     

    }

     

     

    Berikut tampilan source code SitesXmlDomParser.java

    package com.makemyandroidapp.example.stacksites;import java.io.BufferedReader;

    import java.io.FileInputStream;

    import java.io.FileNotFoundException;

    import java.io.IOException;

    import java.io.InputStreamReader;

    import java.io.StringReader;

    import java.util.ArrayList;

    import java.util.List;

     

    import javax.xml.parsers.DocumentBuilder;

    import javax.xml.parsers.DocumentBuilderFactory;

    import javax.xml.parsers.ParserConfigurationException;

     

    import org.w3c.dom.Document;

    import org.w3c.dom.Element;

    import org.w3c.dom.Node;

    import org.w3c.dom.NodeList;

    import org.xml.sax.InputSource;

    import org.xml.sax.SAXException;

     

    import android.content.Context;

    import android.util.Log;

     

    /*

    * Helper object for parsing StackExchange Sites listen from XML source.

    * This class is modeled after the example given here:

    * http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/

    */

    public class SitesXmlDomParser {

          static final String KEY_SITE = “site”;

          static final String KEY_NAME = “name”;

          static final String KEY_LINK = “link”;

          static final String KEY_ABOUT = “about”;

          static final String KEY_IMAGE_URL = “image”;

     

          /*

          * High level method that will read the xml file and parse it

          * into a List of StackSite objects.

          */

          public static List<StackSite> getStackSitesFromFile(Context ctx){

                List<StackSite> stackSites = new ArrayList<StackSite>();

     

                String xml = readFile(ctx); // getting XML

                Document doc = getDomElement(xml); // getting DOM element

     

                NodeList nl = doc.getElementsByTagName(KEY_SITE);

     

                // looping through all site nodes <site>

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

                      StackSite curStackSite = new StackSite();

                      Element e = (Element) nl.item(i);

     

                      curStackSite.setName(getValue(e,KEY_NAME));

                      curStackSite.setLink(getValue(e,KEY_LINK));

                      curStackSite.setAbout(getValue(e,KEY_ABOUT));

                      curStackSite.setImgUrl(getValue(e,KEY_IMAGE_URL));

     

                      //Log.i(“StackSites”, curStackSite.getName());

                      stackSites.add(curStackSite);

                }

     

                return stackSites;

          }

     

          //Helper method to read the file and return its text.

          private static String readFile(Context ctx){

                String xml = “”;

                try {

                      FileInputStream fis = ctx.openFileInput(“StackSites.xml”);

                      BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

                      String line;

                      while((line = reader.readLine()) != null){

                            xml += line;

                            xml += “n”;

                      }

                      //Log.i(“StackSites”, xml);

                } catch (FileNotFoundException e) {

                      e.printStackTrace();

                } catch (IOException e) {

                      // TODO Auto-generated catch block

                      e.printStackTrace();

                }

     

     

                return xml;

          }

     

          //Get a value from an XML Element.

          private static String getValue(Element item, String str) {

              NodeList n = item.getElementsByTagName(str);

              return getElementValue(n.item(0));

          }

     

          //Get an Element Value from an XML Node object.

          private static String getElementValue( Node elem ) {

                StringBuilder value = new StringBuilder();

             Node child;

             if( elem != null){

                 if (elem.hasChildNodes()){

                     for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){

                         if( child.getNodeType() == Node.TEXT_NODE ){

                           value.append(child.getNodeValue());

     

                         }

                     }

                     return value.toString();

                 }

             }

             return “”;

            }

     

          //Get dom Document object from raw text.

          private static Document getDomElement(String xml){

           Document doc = null;

           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

           try {

               DocumentBuilder db = dbf.newDocumentBuilder();

               InputSource is = new InputSource();

                   is.setCharacterStream(new StringReader(xml));

                   doc = db.parse(is);

               } catch (ParserConfigurationException e) {

                   Log.e(“Error: “, e.getMessage());

                   return null;

               } catch (SAXException e) {

                   Log.e(“Error: “, e.getMessage());

                   return null;

               } catch (IOException e) {

                   Log.e(“Error: “, e.getMessage());

                   return null;

               }

                   // return DOM

               return doc;

       }

    }

     

     

    Berikut tampilan source code SitesXmlPullParser.java

    package com.makemyandroidapp.example.stacksites;import java.io.BufferedReader;

    import java.io.FileInputStream;

    import java.io.InputStreamReader;

    import java.util.ArrayList;

    import java.util.List;

     

    import org.xmlpull.v1.XmlPullParser;

    import org.xmlpull.v1.XmlPullParserFactory;

     

    import android.content.Context;

     

    public class SitesXmlPullParser {

     

          static final String KEY_SITE = “site”;

          static final String KEY_NAME = “name”;

          static final String KEY_LINK = “link”;

          static final String KEY_ABOUT = “about”;

          static final String KEY_IMAGE_URL = “image”;

     

          public static List<StackSite> getStackSitesFromFile(Context ctx) {

     

                // List of StackSites that we will return

                List<StackSite> stackSites;

                stackSites = new ArrayList<StackSite>();

     

                // temp holder for current StackSite while parsing

                StackSite curStackSite = null;

                // temp holder for current text value while parsing

                String curText = “”;

     

                try {

                      // Get our factory and PullParser

                      XmlPullParserFactory factory = XmlPullParserFactory.newInstance();

                      XmlPullParser xpp = factory.newPullParser();

     

                      // Open up InputStream and Reader of our file.

                      FileInputStream fis = ctx.openFileInput(“StackSites.xml”);

                      BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

     

                      // point the parser to our file.

                      xpp.setInput(reader);

     

                      // get initial eventType

                      int eventType = xpp.getEventType();

     

                      // Loop through pull events until we reach END_DOCUMENT

                      while (eventType != XmlPullParser.END_DOCUMENT) {

                            // Get the current tag

                            String tagname = xpp.getName();

     

                            // React to different event types appropriately

                            switch (eventType) {

                            case XmlPullParser.START_TAG:

                                  if (tagname.equalsIgnoreCase(KEY_SITE)) {

                                        // If we are starting a new <site> block we need

                                        //a new StackSite object to represent it

                                        curStackSite = new StackSite();

                                  }

                                  break;

     

                            case XmlPullParser.TEXT:

                                  //grab the current text so we can use it in END_TAG event

                                  curText = xpp.getText();

                                  break;

     

                            case XmlPullParser.END_TAG:

                                  if (tagname.equalsIgnoreCase(KEY_SITE)) {

                                        // if </site> then we are done with current Site

                                        // add it to the list.

                                        stackSites.add(curStackSite);

                                  } else if (tagname.equalsIgnoreCase(KEY_NAME)) {

                                        // if </name> use setName() on curSite

                                        curStackSite.setName(curText);

                                  } else if (tagname.equalsIgnoreCase(KEY_LINK)) {

                                        // if </link> use setLink() on curSite

                                        curStackSite.setLink(curText);

                                  } else if (tagname.equalsIgnoreCase(KEY_ABOUT)) {

                                        // if </about> use setAbout() on curSite

                                        curStackSite.setAbout(curText);

                                  } else if (tagname.equalsIgnoreCase(KEY_IMAGE_URL)) {

                                        // if </image> use setImgUrl() on curSite

                                        curStackSite.setImgUrl(curText);

                                  }

                                  break;

     

                            default:

                                  break;

                            }

                            //move on to next iteration

                            eventType = xpp.next();

                      }

                } catch (Exception e) {

                      e.printStackTrace();

                }

     

                // return the populated list.

                return stackSites;

          }

    }

     

     

    Berikut tampilan source code StackSite.java

    package com.makemyandroidapp.example.stacksites; 

    /*

    * Data object that holds all of our information about a StackExchange Site.

    */

    public class StackSite {

     

          private String name;

          private String link;

          private String about;

          private String imgUrl;

     

          public String getName() {

                return name;

          }

          public void setName(String name) {

                this.name = name;

          }

          public String getLink() {

                return link;

          }

          public void setLink(String link) {

                this.link = link;

          }

          public String getAbout() {

                return about;

          }

          public void setAbout(String about) {

                this.about = about;

          }

          public String getImgUrl() {

                return imgUrl;

          }

          public void setImgUrl(String imgUrl) {

                this.imgUrl = imgUrl;

          }

          @Override

          public String toString() {

                return “StackSite [name=” + name + “, link=” + link + “, about=”

                            + about + “, imgUrl=” + imgUrl + “]”;

          }

    }

     

     

     

     

     

     

    Berikut tampilan menu aplikasi StackSites

    a

     

    Berikut tampilan utama aplikasi StackSites

     

    b

     

    Berikut tampilan Sistem Informasi Akademik Mahasiswa

     

    c

     

    Berikut tampilan website PTIIK

     

    d

     

    Berikut Tampilan website e-lerning Herman Class

    e

     

    Berikut tampilan website 9gag

     

    f

     

    Berikut tampilan website Dota2lounge

    g