Friday, 25 March 2016

XML - Parsing (DOM, SAX, XMLPullParser)

XML stands for Extensible Mark-up Language.XML is a very popular format and commonly used for sharing data on the internet.
Android provides three types of XML parsers
1)DOM.
2)SAX.
3)XMLPullParser.

XMLPullParser.

 XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser  parser = factory.newPullParser();

            parser.setInput(is, null);

            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tagname = parser.getName();
                switch (eventType) {
                    case XmlPullParser.START_TAG:
                        if (tagname.equalsIgnoreCase("item")) {
                            // create a new instance of employee
                            _xmlmodel = new XmlModel();
                        }
                        break;

                    case XmlPullParser.TEXT:
                        text = parser.getText();
                        break;

                    case XmlPullParser.END_TAG:
                        if (tagname.equalsIgnoreCase("item")) {
                            // add employee object to list
                            _xmlmodel_response.add(_xmlmodel);
                        }else if (tagname.equalsIgnoreCase("id")) {
                            _xmlmodel.setId(text);
                        }  else if (tagname.equalsIgnoreCase("name")) {
                            _xmlmodel.setName(text);
                        } else if (tagname.equalsIgnoreCase("cost")) {
                            _xmlmodel.setCost(text);
                        }else if (tagname.equalsIgnoreCase("description")) {
                            _xmlmodel.setDescription(text);
                        }
                        break;

                    default:
                        break;
                }
                eventType = parser.next();
            }


SAX.
 XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser()
                    .getXMLReader();
            // create a SAXXMLHandler
            SAXXMLHandler saxHandler = new SAXXMLHandler();
            // store handler in XMLReader
            xmlReader.setContentHandler(saxHandler);
            // the process starts
            xmlReader.parse(new InputSource(is));
            // get the `Employee list`
            employees = saxHandler.getEmployees();

DOM Handler
  public Document getDocument(InputStream inputStream) {
        Document document = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = factory.newDocumentBuilder();
            InputSource inputSource = new InputSource(inputStream);
            document = db.parse(inputSource);
        } 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 document;
    }

 
    public String getValue(Element item, String name) {
        NodeList nodes = item.getElementsByTagName(name);
        return this.getTextNodeValue(nodes.item(0));
    }

    private final String getTextNodeValue(Node node) {
        Node child;
        if (node != null) {
            if (node.hasChildNodes()) {
                child = node.getFirstChild();
                while(child != null) {
                    if (child.getNodeType() == Node.TEXT_NODE) {
                        return child.getNodeValue();
                    }
                    child = child.getNextSibling();
                }
            }
        }
        return "";
    }

Click Here to get full code

output:


Tuesday, 22 March 2016

ANDROID N FEATURES

Multi-Window Support: The joy of multitasking can be experienced with this feature. Users can now sift around multiple windows on their device. It means they can work on more than one app at once, on multiple windows. They can even resize their app screen in multiple windows. For this, developers can set a minimum size to their apps.

New Settings menu: Android N now gives a revamped settings menu. A new Suggestions drop-down section appears at the top. Basic details of each menu is displayed in the main Settings menu itself. So, if you want to see if your device is connected to Bluetooth, you can see it on the main Settings menu itself. This is definitely a time saver setting.

Notifications Redesigned: Notifications have finally got a fresh change. It is similar to that of Marshmallow except for a few minor changes. Notifications are now bundled together and occupy the whole screen unlike Marshmallow where only a portion was occupied. Also, you can reply to messages from the notifications itself. You don’t need to launch the app for replying.

Mobile Data Saving: Thankfully, without installing any third party apps, users can now save the usage of their internet using this inbuilt feature. You simply have to turn it on to begin data saving. It blocks background data usage.

Night Mode: Users will love this one. Though it has been launched late but it’s better late than never. IOS has already launched it recently. With Night Mode turned on, you can easily use your device at night without having to cause strain to your eyes.

Improved Dozing: This feature hibernates all inactive apps on your device that were idle for a longer time. It works when you put your phone in your pocket or simply lock it.

Screen Zooming: Another inspiration from iOS, this feature now lets users with low vision to zoom into elements on their screens for clear visibility.

Android has surely come a long way in improving user experience with feasibility of Android developers. This time it has made sure to save users more time. Let’s see how it’s final release will be like.





Thursday, 10 March 2016

Android Geofencing with Google Maps

 Geo-fencing is a feature in Google Play Services that allows for checking when a user has entered or left a circular area. This feature is implemented using Google's Location Services, so it relies on location data from cellular towers, wireless networks and GPS. While this can be a powerful tool, it should be used conservatively as continuously polling for a users location can be taxing on the device battery. It should also be noted that Geo-fencing can take some time to register if the area has been entered or left, so you should plan accordingly when designing any apps that use this feature. For this post I have decided to put together an app that creates a Geo-fence around the users starting location and post a notification when the user enters or leaves the fence.


The first thing that should be done is to update the gradle.build file to include Google Play Services.

compile 'com.google.android.gms:play-services:6.5.87'

Next the manifest should be edited to allow the  permission in order to use the device's GPS functionality. Meta-data for the Google Play Services version should be included as a tag, and the service that will be used for handling what action to take on a Geo-fence event should be declared.

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

<meta-data
            android:name="com.google.android.gms.version"

            android:value="@integer/google_play_services_version" />

 Once the manifest file is set, then the main activity for the application should be set to implement GooglePlayServices connection callbacks and LocationClient Geofencing result and removal listeners. These are generally used for doing specific actions when PlayServices has connected or disconnected, as well as handling geofencing events.

public class MainActivity extends ActionBarActivity implements
        ConnectionCallbacks, OnConnectionFailedListener, ResultCallback<Status> {

    protected static final String TAG = "creating-and-monitoring-geofences";

    /**
     * Provides the entry point to Google Play services.
     */
    protected GoogleApiClient mGoogleApiClient;

    /**
     * The list of geofences used in this sample.
     */
    protected ArrayList<Geofence> mGeofenceList;

    /**
     * Used to keep track of whether geofences were added.
     */
    private boolean mGeofencesAdded;

    /**
     * Used when requesting to add or remove geofences.
     */
    private PendingIntent mGeofencePendingIntent;
   {


Verify that the device has Google Play Services available. If not, we can take action to alert the user to download it from the play store, or in this case simply end the activity.

private void verifyPlayServices() {
    switch ( GooglePlayServicesUtil.isGooglePlayServicesAvailable( this ) ) {
        case ConnectionResult.SUCCESS: {
            break;
        }
        case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED: {
            finish();
        }
        default: {
            finish();
        }
    }
}


Once Play Services have been confirmed, we can create a reference to the device LocationClient, and create a PendingIntent to start our service (GeofencingService.class) that handles performing an action when the user interacts with a geofence.

private PendingIntent getGeofencePendingIntent() {
        // Reuse the PendingIntent if we already have it.
        if (mGeofencePendingIntent != null) {
            return mGeofencePendingIntent;
        }
        Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
        // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
        // addGeofences() and removeGeofences().
        return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

Next ,Start the Geo Fence request.

private GeofencingRequest getGeofencingRequest() {
        GeofencingRequest.Builder builder = new GeofencingRequest.Builder();

        // The INITIAL_TRIGGER_ENTER flag indicates that geofencing service should trigger a
        // GEOFENCE_TRANSITION_ENTER notification when the geofence is added and if the device
        // is already inside that geofence.
        builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);

        // Add the geofences to be monitored by geofencing service.
        builder.addGeofences(mGeofenceList);

        // Return a GeofencingRequest.
        return builder.build();
    }


To get full code Click Here


Monday, 7 March 2016

Display list of WiFi networks in Android

Android provides the WiFiManager class for managing all aspects of WiFi connectivity. It is used to to define the names of various Intent actions that are broadcast upon any sort of change in WiFi state.

Through this post, we will learn how to display a list of available WiFi networks to which an Android device can be connected. The list can be viewed and updated, and attributes of individual entries can be modified.

WifiManager mainWifiObj;
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE); 

Methods defined in WifiManager class:


1)addNetwork(WifiConfiguration config)
This method add a new network description to the set of configured networks.

2)createWifiLock(String tag)
This method creates a new WifiLock.

3)disconnect()
This method disassociate from the currently active access point.

4)enableNetwork(int netId, boolean disableOthers)
This method allow a previously configured network to be associated with.

5)getWifiState()
This method gets the Wi-Fi enabled state

6)isWifiEnabled()
This method return whether Wi-Fi is enabled or disabled.

7)setWifiEnabled(boolean enabled)
This method enable or disable Wi-Fi.

8)updateNetwork(WifiConfiguration config)

This method update the network description of an existing configured network.

Sample Code:
  private void getWifiNetworksList(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        final WifiManager wifiManager =
                (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);;
        registerReceiver(new BroadcastReceiver(){

            @SuppressLint("UseValueOf") @Override
            public void onReceive(Context context, Intent intent) {
                sb = new StringBuilder();
                scanList = wifiManager.getScanResults();
                sb.append("\n  Number Of Wifi connections :" + " " +scanList.size()+"\n\n");
                for(int i = 0; i < scanList.size(); i++){
                    sb.append(new Integer(i+1).toString() + ". ");
                    sb.append((scanList.get(i)).toString());
                    sb.append("\n\n");
                }

                wifi_Address.setText(sb);
            }

        },filter);
        wifiManager.startScan();
    }


To Get Full Code Click Here