Android

Android, open application on click of a URL.


Add following code in your AndroidManifest.xml tag.

    <intent-filter>
        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <data android:host="www.put-your-website.com" />
        <data android:scheme="https" />
        <data android:scheme="http" />
        <data android:pathPattern=".*" />
    </intent-filter>

Once the activity is launched, getIntent().getData() will give the URL for which your application was launched.

As per the above intent-filter. If the webpage contains

<a href="http://www.put-your-website.com/any/path/to/open">Launch Application</a>

Click on this anchor would ask you to open the url in either browser or your application. In case your application is not installed on device, this url will continue to load in browser.

Resizing webview to match the content size


There has been lots of discussion around methods of resizing the webview to fit the size of its content.

The actual issue can be seen when we are using webview inside a scrollview. In case we wish to show something on top of webview and allow the whole page to scroll, if web view content goes beyond screen size.

If at first we load huge data in webview, it expands itself to fit the whole content, but when we load a smaller data later, it still shows the same previous size, which is way more than size required to display smaller data. Side effect of this is that user can keep scrolling beyond the html content.

Following are few threads where this issue has been discussed.

http://stackoverflow.com/questions/3509158/scroll-view-doest-resize-when-the-content-of-child-view-changes

http://stackoverflow.com/questions/15546416/how-to-shrink-webview-size-dynamically-according-to-its-content

As you can see, most of the people suggest not to use webview inside scroll, and others suggest creation of new instances of webview every time we load a url into it. But both of these are not real solution to the problem.

Here is a small trick which worked for me.

private void setupWebView() {
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            webView.loadUrl("javascript:MyApp.resize(document.body.getBoundingClientRect().height)");
            super.onPageFinished(view, url);
        }
    });
    webView.addJavascriptInterface(this, "MyApp");
}

@JavascriptInterface
public void resize(final float height) {
    MyActivity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            webView.setLayoutParams(new LinearLayout.LayoutParams(getResources().getDisplayMetrics().widthPixels, (int) (height * getResources().getDisplayMetrics().density)));
        }
    });
}

Different screen orientation on different screen size.


There are many tutorials around on web which tells how to support different screen sizes in android. But there are many tiny little real problems which comes in every day life of android developer while supporting different screen size.

Well I understand we can create different layouts & values for different screen sizes which will ensure my screen is properly scaled and fits properly in different screen size. It also ensures the flexibility of amount of information being displayed on different screen size.

Now if we want the application to appear in portrait on small & normal screen sizes, but if the screen is large or xlarge we want the application to appear in landscape, then how do we go about it?

At first I thought that probably defining different screen orientation in different value folder will get this done. But unfortunately it does not work on all android devices.

So the only method left for us to achieve different screen orientation on different screen size is programmatic.

What we need to do is – at the time of activity creation, get the screen size and accordingly set the orientation.

                int layout = getResources().getConfiguration().screenLayout
				& Configuration.SCREENLAYOUT_SIZE_MASK;
		if (layout == Configuration.SCREENLAYOUT_SIZE_XLARGE
				|| layout == Configuration.SCREENLAYOUT_SIZE_LARGE) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		} else {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		}

Android 3.0 Honeycomb Drag and Drop tutorial


Since Android 3.0 Honeycomb we have drag and drop framework which allows us to move data from one view to another in current layout by simple graphical drag and drop gesture.

The Drag and Drop Framework has ClipData, DragEvent & DragShadowBuilder classes introduced along with couple of helper methods which allows to achieve drag and drop feature.

The drag & drop operation begins when user makes some kind of gesture on screen which indicates the start of drag. For example, user can perform long press on item before he starts dragging it. (Just like it happens on home screen)

When the drag event starts, systems call backs the application to get the representation of data being dragged.
Developer can create this representation be extending DragShadowBuilder class. Developer can also ignore the implementation of DragShadowBuilder and rely on system’s default representation of data (which will be the view itself).

While the view is getting dragged on screen, system generates DragEvents which can be intercepted by application by setting View.setOnDragListener().

OnDragListener interface has callback method public boolean onDrag(View view, DragEvent dragEvent)
which will get called whenever any view is dragged or dropped.

The DragEvent parameter provides getAction() which tells the application which type of action has occurred.

Following types of action can be identified.

DragEvent.ACTION_DRAG_STARTED – Drag event has started
DragEvent.ACTION_DRAG_ENTERED – Drag has brought the drop shadow in view bounds.
DragEvent.ACTION_DRAG_EXITED – Drag has taken the drop shadow out of view bounds.
DragEvent.ACTION_DRAG_LOCATION – Drag is happening and drop shadow is inside view bounds.
DragEvent.ACTION_DROP – Drop has happened inside view bounds.
DragEvent.ACTION_DRAG_ENDED – Drop has happened outside view bounds.

Now lets have a look at a sample code and see how it looks.

To demonstrate the drag and drop, I am going to create a simple grid view and a trash can(Image view). User can drag an item from grid view to trash can to delete that item.

Lets have a look at layout file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/parent_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <GridView
        android:id="@+id/grid_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:horizontalSpacing="10dip"
        android:numColumns="4"
        android:verticalSpacing="10dip" />

    <ImageView
        android:id="@+id/trash_can"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:contentDescription="Delete"
        android:padding="40dip"
        android:src="@drawable/trash_can"
        android:visibility="gone" >
    </ImageView>

</RelativeLayout>

 
Lets fill the child views in grid.

ArrayList drawables;

private BaseAdapter adapter;
private int draggedIndex = -1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    drawables = new ArrayList();
    drawables.add(R.drawable.sample_0);
    drawables.add(R.drawable.sample_1);
    drawables.add(R.drawable.sample_2);
    drawables.add(R.drawable.sample_3);
    drawables.add(R.drawable.sample_4);
    drawables.add(R.drawable.sample_5); 
    drawables.add(R.drawable.sample_6);
    drawables.add(R.drawable.sample_7);
    GridView gridView = (GridView) findViewById(R.id.grid_view);
        gridView.setOnItemLongClickListener(MainActivity.this);
    gridView.setAdapter(adapter = new BaseAdapter() {

        @Override
        // Get a View that displays the data at the specified position in
        // the data set.
        public View getView(int position, View convertView,
                ViewGroup gridView) {
            // try to reuse the views.
            ImageView view = (ImageView) convertView;
            // if convert view is null then create a new instance else reuse
            // it
            if (view == null) {
                view = new ImageView(MainActivity.this);
            }
            view.setImageResource(drawables.get(position));
            view.setTag(String.valueOf(position));
            return view;
        }
    
        @Override
        // Get the row id associated with the specified position in the
        // list.
        public long getItemId(int position) {
            return position;
        }

        @Override
        // Get the data item associated with the specified position in the
        // data set.
        public Object getItem(int position) {
            return drawables.get(position);
        }

        @Override
        // How many items are in the data set represented by this Adapter.
        public int getCount() {
            return drawables.size();
        }
    });
}

 

You can see that I’ve set the activity as onItemLongCLickListener. Lets look at on onItemLongClick method

We want to start the drag operation when an item is long clicked, we also want to make the trash can visible.
To achieve this we will have to create ClipData.Item and then we will create ClipData object which be used to start drag.

Since we want both, dragged view and trash can to get the drag events, we will set drag listeners for both of them.

@Override
    public boolean onItemLongClick(AdapterView gridView, View view,
            int position, long row) {
        ClipData.Item item = new ClipData.Item((String) view.getTag());
        ClipData clipData = new ClipData((CharSequence) view.getTag(),
                new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN }, item);
        view.startDrag(clipData, new View.DragShadowBuilder(view), null, 0);
        View trashCan = findViewById(R.id.trash_can);
        trashCan.setVisibility(View.VISIBLE);
        trashCan.setOnDragListener(MainActivity.this);

        trashCan.setOnDragListener(MainActivity.this);
        draggedIndex = position;
        return true;
    }

 

Now looks like my activity is playing lot many roles. It is also a drag listener. Lets look at how my onDrag method looks like.

@Override
    public boolean onDrag(View view, DragEvent dragEvent) {
        switch (dragEvent.getAction()) {
        case DragEvent.ACTION_DRAG_STARTED:
            // Drag has started
            // If called for trash resize the view and return true
            if (view.getId() == R.id.trash_can) {
                view.animate().scaleX(1.0f);
                view.animate().scaleY(1.0f);
                return true;
            } else // else check the mime type and set the view visibility
            if (dragEvent.getClipDescription().hasMimeType(
                    ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                view.setVisibility(View.GONE);
                return true;

            } else {
                return false;
            }
        case DragEvent.ACTION_DRAG_ENTERED:
            // Drag has entered view bounds
            // If called for trash can then scale it.
            if (view.getId() == R.id.trash_can) {
                view.animate().scaleX(1.5f);
                view.animate().scaleY(1.5f);
            }
            return true;
        case DragEvent.ACTION_DRAG_EXITED:
            // Drag exited view bounds
            // If called for trash can then reset it.
            if (view.getId() == R.id.trash_can) {
                view.animate().scaleX(1.0f);
                view.animate().scaleY(1.0f);
            }
            view.invalidate();
            return true;
        case DragEvent.ACTION_DRAG_LOCATION:
            // Ignore this event
            return true;
        case DragEvent.ACTION_DROP:
            // Dropped inside view bounds
            // If called for trash can then delete the item and reload the grid
            // view
            if (view.getId() == R.id.trash_can) {
                drawables.remove(draggedIndex);
                draggedIndex = -1;
            }
            adapter.notifyDataSetChanged();
        case DragEvent.ACTION_DRAG_ENDED:
            // Hide the trash can
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    findViewById(R.id.trash_can).setVisibility(View.GONE);
                }
            }, 1000l);
            if (view.getId() == R.id.trash_can) {
                view.animate().scaleX(1.0f);
                view.animate().scaleY(1.0f);
            } else {
                view.setVisibility(View.VISIBLE);
            }
            // remove drag listeners
            view.setOnDragListener(null);
            return true;

        }
        return false;
    }

 
I think code is self explanatory, this method is called twice for every event and code takes care of identifying for which view it is called for and takes the action accordingly.

The only thing to notice here is that if we return true for DragEvent.ACTION_DRAG_STARTED then only we will get further events of DragEvent.ACTION_DRAG_ENTERED & DragEvent.ACTION_DRAG_EXITED. Otherwise these events will be ignored by system.

Lets put all this together and see how it looks.

/**
 * @author Chitranshu Asthana
 */

package com.example.dragviewexample;

import java.util.ArrayList;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipDescription;
import android.os.Bundle;
import android.os.Handler;
import android.view.DragEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnDragListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class MainActivity extends Activity implements OnDragListener,
        OnItemLongClickListener {

    ArrayList drawables;

    private BaseAdapter adapter;
    private int draggedIndex = -1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        drawables = new ArrayList();
        drawables.add(R.drawable.sample_0);
        drawables.add(R.drawable.sample_1);
        drawables.add(R.drawable.sample_2);
        drawables.add(R.drawable.sample_3);
        drawables.add(R.drawable.sample_4);
        drawables.add(R.drawable.sample_5);
        drawables.add(R.drawable.sample_6);
        drawables.add(R.drawable.sample_7);
        GridView gridView = (GridView) findViewById(R.id.grid_view);
        gridView.setOnItemLongClickListener(MainActivity.this);
        gridView.setAdapter(adapter = new BaseAdapter() {

            @Override
            // Get a View that displays the data at the specified position in
            // the data set.
            public View getView(int position, View convertView,
                    ViewGroup gridView) {
                // try to reuse the views.
                ImageView view = (ImageView) convertView;
                // if convert view is null then create a new instance else reuse
                // it
                if (view == null) {
                    view = new ImageView(MainActivity.this);
                }
                view.setImageResource(drawables.get(position));
                view.setTag(String.valueOf(position));
                return view;
            }

            @Override
            // Get the row id associated with the specified position in the
            // list.
            public long getItemId(int position) {
                return position;
            }

            @Override
            // Get the data item associated with the specified position in the
            // data set.
            public Object getItem(int position) {
                return drawables.get(position);
            }

            @Override
            // How many items are in the data set represented by this Adapter.
            public int getCount() {
                return drawables.size();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public boolean onDrag(View view, DragEvent dragEvent) {
        switch (dragEvent.getAction()) {
        case DragEvent.ACTION_DRAG_STARTED:
            // Drag has started
            // If called for trash resize the view and return true
            if (view.getId() == R.id.trash_can) {
                view.animate().scaleX(1.0f);
                view.animate().scaleY(1.0f);
                return true;
            } else // else check the mime type and set the view visibility
            if (dragEvent.getClipDescription().hasMimeType(
                    ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                view.setVisibility(View.GONE);
                return true;

            } else {
                return false;
            }
        case DragEvent.ACTION_DRAG_ENTERED:
            // Drag has entered view bounds
            // If called for trash can then scale it.
            if (view.getId() == R.id.trash_can) {
                view.animate().scaleX(1.5f);
                view.animate().scaleY(1.5f);
            }
            return true;
        case DragEvent.ACTION_DRAG_EXITED:
            // Drag exited view bounds
            // If called for trash can then reset it.
            if (view.getId() == R.id.trash_can) {
                view.animate().scaleX(1.0f);
                view.animate().scaleY(1.0f);
            }
            view.invalidate();
            return true;
        case DragEvent.ACTION_DRAG_LOCATION:
            // Ignore this event
            return true;
        case DragEvent.ACTION_DROP:
            // Dropped inside view bounds
            // If called for trash can then delete the item and reload the grid
            // view
            if (view.getId() == R.id.trash_can) {
                drawables.remove(draggedIndex);
                draggedIndex = -1;
            }
            adapter.notifyDataSetChanged();
        case DragEvent.ACTION_DRAG_ENDED:
            // Hide the trash can
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    findViewById(R.id.trash_can).setVisibility(View.GONE);
                }
            }, 1000l);
            if (view.getId() == R.id.trash_can) {
                view.animate().scaleX(1.0f);
                view.animate().scaleY(1.0f);
            } else {
                view.setVisibility(View.VISIBLE);
            }
            // remove drag listeners
            view.setOnDragListener(null);
            return true;

        }
        return false;
    }

    @Override
    public boolean onItemLongClick(AdapterView gridView, View view,
            int position, long row) {
        ClipData.Item item = new ClipData.Item((String) view.getTag());
        ClipData clipData = new ClipData((CharSequence) view.getTag(),
                new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN }, item);
        view.startDrag(clipData, new View.DragShadowBuilder(view), null, 0);
        View trashCan = findViewById(R.id.trash_can);
        trashCan.setVisibility(View.VISIBLE);
        trashCan.setOnDragListener(MainActivity.this);

        trashCan.setOnDragListener(MainActivity.this);
        draggedIndex = position;
        return true;
    }
}

 
And this is how it looks.
 

Android JDBC driver for Microsoft SQL Server and Sybase


Recently i shared a post about Configuring and accessing MySQL jdbc driver on android application.

Good thing about MySQL is that it is open source and hence the driver is open source too. Even if we couldn’t find any android compatible driver, it wouldn’t be too difficult to get the source code and port it for android.

But when it comes to MSSQL and Sybase, its a different story. After successfully configuring Mysql JDBC driver I was looking for compatible drivers for MSSQL and unfortunately none of the versions available were compatible.

It was disappointing in start but then I started looking for some hacks around and came across a really wonderful library – jTDS JDBC Driver.

Now good things about this driver is that it is free software available under terms of GNU Lesser General Public License. Which means it is allowed to be used in open source as well as comercial projects.

Another good thing about this JDBC driver is that it supports both MSSQL and Sybase and it is compatible with Android.

jTDS is an open source 100% pure Java (type 4) JDBC 3.0 driver for Microsoft SQL Server (6.5, 7, 2000, 2005 and 2008) and Sybase (10, 11, 12, 15). jTDS is based on FreeTDS and is currently the fastest production-ready JDBC driver for SQL Server and Sybase. jTDS is 100% JDBC 3.0 compatible, supporting forward-only and scrollable/updateable ResultSets, concurrent (completely independent) Statements and implementing all the DatabaseMetaData and ResultSetMetaData methods. Check out the feature matrix for more details.

Quite a few of the commercial JDBC drivers out there are based on jTDS (or FreeTDS), even if they no longer acknowledge this. jTDS has been tested with virtually all JDBC-based database management tools and is the driver of choice for most of these (recommended for DbVisualizer and SQuirreL SQL, distributed with Aqua Data Studio and DataDino). jTDS is also becoming a common choice for enterprise-level applications: it passes both the J2EE 1.3 certification and Hibernate test suites, and is recommended for JBoss, Hibernate, Atlassian JIRA and Confluence and Compiere.

So go ahead and give it a shot.. It worked for me, I am sure you will enjoy working with it too..

PS: Have a look at FAQs before jumping into writing code.