Wednesday 29 January 2014

Publishing ads in Android Applications using Google AdMob

step1:Add google play services library to the project.
         To know how to add library project visit this post :http://ramsandroid4all.blogspot.in/2013/03/google-maps-android-api-v2.html

step2:Register application in www.admob.com and get publisher ID

step3:Add following code in java class

MainActivity.java:
-------------------
package com.ram.displayallcontacts;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;

public class MainActivity extends Activity {
    /** The view to show the ad. */
    private AdView adView;

    /* Your ad unit id. Replace with your actual ad unit id. */
    private static final String AD_UNIT_ID = "a152ce2b1c542db";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ad);

        // Create an ad.
        adView = new AdView(this);
        adView.setAdSize(AdSize.BANNER);
        adView.setAdUnitId(AD_UNIT_ID);

        // Add the AdView to the view hierarchy. The view will have no size
        // until the ad is loaded.
        LinearLayout layout = (LinearLayout) findViewById(R.id.ll);
        layout.addView(adView);

       // Start loading the ad in the background.
        adView.loadAd(new AdRequest.Builder().build());

    }

    @Override
    public void onResume() {
        super.onResume();
        if (adView != null) {
            adView.resume();
        }
    }

    @Override
    public void onPause() {
        if (adView != null) {
            adView.pause();
        }
        super.onPause();
    }

    /** Called before the activity is destroyed. */
    @Override
    public void onDestroy() {
        // Destroy the AdView.
        if (adView != null) {
            adView.destroy();
        }
        super.onDestroy();
    }
}

step4:Add following tags under AndroidManifest.xml -->application tag and add internet permissions as follows
AndroiManifest.xml:
-------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ram.displayallcontacts"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ram.displayallcontacts.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>

</manifest>

Publishing Android Application in Google Play Store

Requirements from application side:
----------------------------------
1.Minimum 2 screenshots(Max 8) of Application(Using DDMS Tool and in that use Devices tool).
2.One High Resolution icon(Application logo) with size(512/512).
3.Application apk file(for ex:SampleApplication.apk).


-->Before generating .apk file remove log statements from application.

Generating .apk file from application for Google Play Store:
-----------------------------------------------------------
Open Application AndroidManifest.xml file and select Manifest
-->Use the Export Wizard-->Next-->Select Create new keystore-->select browse and show the location where keystore file is going to generate-->next give password(if you forgot password no forgot password option) and select Next -->In Key Creation window give information for Alias,Password(Same password that has given in previous window),Validity(maximum validity is 25years) and FirstandLastName(Remaining fields are optional) and select Next.-->In next window select browse and choose the location where you want to generate .apk file and hit finish.


-->Get Google Play Store Developer account from https://play.google.com/apps/publish (or search in google with "google play developer console" keyword)

-->We need to pay 25 dollars for google play store developer account from any debit or credit card
   and need to provide account information.

-->After getting developer account we can publish apps in google play store to publish Sign in     Google Play Developer website with google account(gmail account)

Upload application information in developer console:
----------------------------------------------------
-->Select Add new application.

-->Next give application title and Select Upload apk option.

-->Next Select Upload your first apk for production nex browse application .apk file

-->From left side navigation bar select Store Listing.

-->Next Provide Title, Description,Graphic assests,High-res icon,Application type,category,website,
   Email ,check Privacy Policy and finally select save Button in top the of the console.

-->From left side navigation bar select Pricing & Distribution.

-->Select paid or free and provide required information and select save Button in top the of the    console .

-->Next you we will see Ready to publish drop down box from top right corner of the console form    that select Publish this app.

Monday 20 January 2014

Display All Contacts from Contacts application in ListView



Above output checked in Real Device.

xml files under values folder:
strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Display All Contacts</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="btitle">Load Contacts</string>

</resources>

 

xml files under layout folder:
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/btitle"
        android:textSize="25sp" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:cacheColorHint="#ffccff"
        android:divider="#00ffff"
        android:dividerHeight="2sp" >
    </ListView>

</LinearLayout>


text.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textColor="#ff0000"
    android:textSize="25sp" >

</TextView>


Java Code:
MainActivity.java:
package com.ram.displayallcontacts;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;

public class MainActivity extends Activity {
    ListView list;
    LinearLayout ll;
    Button loadBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ll = (LinearLayout) findViewById(R.id.LinearLayout1);

        list = (ListView) findViewById(R.id.listView1);

        loadBtn = (Button) findViewById(R.id.button1);
        loadBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                LoadContactsAyscn lca = new LoadContactsAyscn();
                lca.execute();
            }
        });

    }

    class LoadContactsAyscn extends AsyncTask<Void, Void, ArrayList<String>> {
        ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            pd = ProgressDialog.show(MainActivity.this, "Loading Contacts",
                    "Please Wait");
        }

        @Override
        protected ArrayList<String> doInBackground(Void... params) {
            // TODO Auto-generated method stub
            ArrayList<String> contacts = new ArrayList<String>();

            Cursor c = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    null, null, null);
            while (c.moveToNext()) {

                String contactName = c
                        .getString(c
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String phNumber = c
                        .getString(c
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                contacts.add(contactName + ":" + phNumber);

            }
            c.close();

            return contacts;
        }

        @Override
        protected void onPostExecute(ArrayList<String> contacts) {
            // TODO Auto-generated method stub
            super.onPostExecute(contacts);

            pd.cancel();

            ll.removeView(loadBtn);

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                    getApplicationContext(), R.layout.text, contacts);

            list.setAdapter(adapter);

        }

    }
}

 

AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ram.displayallcontacts"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.READ_CONTACTS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ram.displayallcontacts.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest> 

 


Sunday 19 January 2014

Custom Toast Example in Android



 Images used in this project :


strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">CustomToast Example</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="buttontitle">Display Toast</string>

</resources>


activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="18dp"
        android:text="@string/buttontitle" />

</RelativeLayout>


customtoast.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/images22"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:src="@drawable/hi" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="18dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#ff0000"
        android:textSize="25sp"
        android:textStyle="italic" />

</LinearLayout>


MainActivity.java:
package com.ram.customtoastexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button b = (Button) findViewById(R.id.button1);

        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Toast t = new Toast(getApplicationContext());

                View v = getLayoutInflater()
                        .inflate(R.layout.customtoast, null);

                TextView text = (TextView) v.findViewById(R.id.textView1);

                text.setText("Button is working");

                t.setView(v);

                t.show();
            }
        });
    }

}





Installing app on External storage

Installing app on External storage(for ex,the device's SD card):

Beginning with API Level 8, you can allow your application to be installed on the external storage (for example, the device's SD card). This is an optional feature you can declare for your application with the android:installLocation manifest attribute. If you do not declare this attribute, your application will be installed on the internal storage only and it cannot be moved to the external storage.

To allow the system to install your application on the external storage, modify your manifest file to include the android:installLocation attribute in the <manifest> element, with a value of either "preferExternal" or "auto".

For example:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    android:installLocation="preferExternal"
    ... >


If you declare "preferExternal", you request that your application be installed on the external storage, but the system does not guarantee that your application will be installed on the external storage. If the external storage is full, the system will install it on the internal storage. The user can also move your application between the two locations.

If you declare "auto", you indicate that your application may be installed on the external storage, but you don't have a preference of install location. The system will decide where to install your application based on several factors. The user can also move your application between the two locations.

Warning: When the user enables USB mass storage to share files with a computer or unmounts the SD card via the system settings, the external storage is unmounted from the device and all applications running on the external storage are immediately killed.

Applications That Should NOT Install on External Storage:

When the user enables USB mass storage to share files with their computer (or otherwise unmounts or removes the external storage), any application installed on the external storage and currently running is killed. The system effectively becomes unaware of the application until mass storage is disabled and the external storage is remounted on the device. Besides killing the application and making it unavailable to the user, this can break some types of applications in a more serious way. In order for your application to consistently behave as expected, you should not allow your application to be installed on the external storage if it uses any of the following features, due to the cited consequences when the external storage is unmounted:

Services
Your running Service will be killed and will not be restarted when external storage is remounted. You can, however, register for the ACTION_EXTERNAL_APPLICATIONS_AVAILABLE broadcast Intent, which will notify your application when applications installed on external storage have become available to the system again. At which time, you can restart your Service.

Alarm Services
Your alarms registered with AlarmManager will be cancelled. You must manually re-register any alarms when external storage is remounted.

Input Method Engines
Your IME will be replaced by the default IME. When external storage is remounted, the user can open system settings to enable your IME again.

Live Wallpapers
Your running Live Wallpaper will be replaced by the default Live Wallpaper. When external storage is remounted, the user can select your Live Wallpaper again.

App Widgets
Your App Widget will be removed from the home screen. When external storage is remounted, your App Widget will not be available for the user to select until the system resets the home application (usually not until a system reboot).

Account Managers
Your accounts created with AccountManager will disappear until external storage is remounted.

Sync Adapters
Your AbstractThreadedSyncAdapter and all its sync functionality will not work until external storage is remounted.

Device Administrators
Your DeviceAdminReceiver and all its admin capabilities will be disabled, which can have unforeseeable consequences for the device functionality, which may persist after external storage is remounted.

Broadcast Receivers listening for "boot completed"
The system delivers the ACTION_BOOT_COMPLETED broadcast before the external storage is mounted to the device. If your application is installed on the external storage, it can never receive this broadcast.

If your application uses any of the features listed above, you should not allow your application to install on external storage. By default, the system will not allow your application to install on the external storage, so you don't need to worry about your existing applications. However, if you're certain that your application should never be installed on the external storage, then you should make this clear by declaring android:installLocation with a value of "internalOnly". Though this does not change the default behavior, it explicitly states that your application should only be installed on the internal storage and serves as a reminder to you and other developers that this decision has been made.







Source :  http://developer.android.com/index.html


SAX Parser Example with Custom ListView







activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button_parse"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="parse" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#990066"
        android:dividerHeight="3dp" >
    </ListView>

</LinearLayout>

custom.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#ff0000" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#0000ff" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#0000ff" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#0000ff" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#0000ff" />

    <TextView
        android:id="@+id/textView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#0000ff" />

</LinearLayout>


MainActivity.java:
package com.ram.saxparserexample;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {
    URL url;
    ListView list;

    ArrayList<String> titles = new ArrayList<String>();
    ArrayList<String> artists = new ArrayList<String>();
    ArrayList<String> countries = new ArrayList<String>();
    ArrayList<String> companies = new ArrayList<String>();
    ArrayList<String> prices = new ArrayList<String>();
    ArrayList<String> years = new ArrayList<String>();

    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        list = (ListView) findViewById(R.id.listView1);

        Button parse = (Button) findViewById(R.id.button_parse);
        text = (TextView) findViewById(R.id.textView1);

        parse.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                MyAsync ma = new MyAsync();
                ma.execute();

            }
        });

    }

    class MyAsync extends AsyncTask<Void, Void, Void> {
        ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            pd = ProgressDialog.show(MainActivity.this, "", "loading");
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            try {
                url = new URL("http://www.xmlfiles.com/examples/cd_catalog.xml");

                // Create an instance for SAXParserFactory
                SAXParserFactory mySAXParserFactory = SAXParserFactory
                        .newInstance();

                // Create an instance for SAXParser
                SAXParser mySAXParser = mySAXParserFactory.newSAXParser();

                // Create an instance for XMLReader
                XMLReader myXMLReader = mySAXParser.getXMLReader();

                // Create an instance for customized handler class
                XMLHandler myXMLHandler = new XMLHandler();

                // apply handler to the XMLReader
                myXMLReader.setContentHandler(myXMLHandler);

                // open the connection
                InputSource is = new InputSource(url.openStream());

                is.setEncoding("ISO-8859-1");

                // parse the data
                myXMLReader.parse(is);

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);

            pd.cancel();
            CustomAdapter ca = new CustomAdapter();
            list.setAdapter(ca);
        }

    }

    class XMLHandler extends DefaultHandler {

        boolean TITLE = false;
        boolean ARTIST = false;
        boolean COUNTRY = false;
        boolean COMPANY = false;
        boolean PRICE = false;
        boolean YEAR = false;

        @Override
        public void startElement(String uri, String localName, String qName,
                Attributes attributes) throws SAXException {
            // TODO Auto-generated method stub
            super.startElement(uri, localName, qName, attributes);

            if (localName.equals("TITLE")) {
                this.TITLE = true;
            } else if (localName.equals("ARTIST")) {
                this.ARTIST = true;
            } else if (localName.equals("COUNTRY")) {
                this.COUNTRY = true;
            } else if (localName.equals("COMPANY")) {
                this.COMPANY = true;
            } else if (localName.equals("PRICE")) {
                this.PRICE = true;
            } else if (localName.equals("YEAR")) {
                this.YEAR = true;
            }
        }

        @Override
        public void characters(char[] ch, int start, int length)
                throws SAXException {
            // TODO Auto-generated method stub
            super.characters(ch, start, length);
            if (this.TITLE) {
                titles.add(new String(ch, start, length));
            } else if (this.ARTIST) {
                artists.add(new String(ch, start, length));

            } else if (this.COUNTRY) {
                countries.add(new String(ch, start, length));

            } else if (this.COMPANY) {
                companies.add(new String(ch, start, length));

            } else if (this.PRICE) {
                prices.add(new String(ch, start, length));

            } else if (this.YEAR) {
                years.add(new String(ch, start, length));

            }

        }

        @Override
        public void endElement(String uri, String localName, String qName)
                throws SAXException {
            // TODO Auto-generated method stub
            super.endElement(uri, localName, qName);
            if (localName.equals("TITLE")) {
                this.TITLE = false;
            } else if (localName.equals("ARTIST")) {
                this.ARTIST = false;
            } else if (localName.equals("COUNTRY")) {
                this.COUNTRY = false;
            } else if (localName.equals("COMPANY")) {
                this.COMPANY = false;
            } else if (localName.equals("PRICE")) {
                this.PRICE = false;
            } else if (localName.equals("YEAR")) {
                this.YEAR = false;
            }
        }
    }

    class CustomAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return titles.size();
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int index, View v, ViewGroup arg2) {
            // TODO Auto-generated method stub
            v = getLayoutInflater().inflate(R.layout.custom, null);

            TextView t1 = (TextView) v.findViewById(R.id.textView1);
            TextView t2 = (TextView) v.findViewById(R.id.textView2);
            TextView t3 = (TextView) v.findViewById(R.id.textView3);
            TextView t4 = (TextView) v.findViewById(R.id.textView4);
            TextView t5 = (TextView) v.findViewById(R.id.textView5);
            TextView t6 = (TextView) v.findViewById(R.id.textView6);

            t1.setText(titles.get(index).toString());
            t2.setText(artists.get(index).toString());
            t3.setText(countries.get(index).toString());
            t4.setText(companies.get(index).toString());
            t5.setText(prices.get(index).toString());
            t6.setText(years.get(index).toString());

            return v;
        }

    }
}


AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ram.saxparserexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ram.saxparserexample.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Monday 6 January 2014

SAXParser example in Android



activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button_parse"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="parse" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

MainActivity.java:
package com.ram.saxparserexample;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    URL url;
    ArrayList<String> list = new ArrayList<String>();
    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button parse = (Button) findViewById(R.id.button_parse);
        text = (TextView) findViewById(R.id.textView1);

        parse.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                MyAsync ma = new MyAsync();
                ma.execute();

            }
        });

    }

    class MyAsync extends AsyncTask<Void, Void, Void> {
        ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            pd = ProgressDialog.show(MainActivity.this, "", "loading");
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            try {
                url = new URL("http://www.w3schools.com/xml/note.xml");

                // Create an instance for SAXParserFactory
                SAXParserFactory mySAXParserFactory = SAXParserFactory
                        .newInstance();

                // Create an instance for SAXParser
                SAXParser mySAXParser = mySAXParserFactory.newSAXParser();

                // Create an instance for XMLReader
                XMLReader myXMLReader = mySAXParser.getXMLReader();

                // Create an instance for customized handler class
                XMLHandler myXMLHandler = new XMLHandler();

                // apply handler to the XMLReader
                myXMLReader.setContentHandler(myXMLHandler);

                // open the connection
                InputSource is = new InputSource(url.openStream());

                is.setEncoding("ISO-8859-1");

                // parse the data
                myXMLReader.parse(is);

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            pd.cancel();

            for (String s : list) {
                text.append(s + "\n");
            }
        }

    }

    class XMLHandler extends DefaultHandler {
        boolean to = false;
        boolean from = false;
        boolean heading = false;
        boolean body = false;

        @Override
        public void startElement(String uri, String localName, String qName,
                Attributes attributes) throws SAXException {
            // TODO Auto-generated method stub
            super.startElement(uri, localName, qName, attributes);

            if (localName.equals("to")) {
                this.to = true;
            } else if (localName.equals("from")) {
                this.from = true;
            } else if (localName.equals("heading")) {
                this.heading = true;
            } else if (localName.equals("body")) {
                this.body = true;
            }
        }

        @Override
        public void characters(char[] ch, int start, int length)
                throws SAXException {
            // TODO Auto-generated method stub
            super.characters(ch, start, length);
            if (this.to) {
                list.add(new String(ch, start, length));
            } else if (this.from) {
                list.add(new String(ch, start, length));

            } else if (this.heading) {
                list.add(new String(ch, start, length));

            } else if (this.body) {
                list.add(new String(ch, start, length));

            }

        }

        @Override
        public void endElement(String uri, String localName, String qName)
                throws SAXException {
            // TODO Auto-generated method stub
            super.endElement(uri, localName, qName);
            if (localName.equals("to")) {
                this.to = false;
            } else if (localName.equals("from")) {
                this.from = false;
            } else if (localName.equals("heading")) {
                this.heading = false;
            } else if (localName.equals("body")) {
                this.body = false;
            }
        }
    }
}

AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ram.saxparserexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ram.saxparserexample.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>