HTML – Download image through AJAX and display it


AJAX was initially designed to be used with text data (JSON/HTML/XML) and that is why this requirement of downloading images using AJAX were never fulfilled.

But with HTML5, XHR2 has been introduced which allows us to get ArrayBuffer in ajax response and this is something which can be used to download image.

There are two approaches that could be taken.

  1. Download the image, create a blob object and use it as src in img.
  2. Download the image, and create data url and use it as src in img.


  
  
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState==4 && xhr.status==200) {
        var blob = new Blob([xhr.response], {
            type: xhr.getResponseHeader("Content-Type")
        });
        var imgUrl = window.URL.createObjectURL(blob);
        document.getElementById("img").src = imgUrl;
      }
    }
  xhr.responseType = "arraybuffer";
  xhr.open("GET","Hacker.jpg",true);
  xhr.send();
  




  
  
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState==4 && xhr.status==200) {
        document.getElementById("img").src = "data:"+xhr.getResponseHeader("Content-Type")+";base64," + btoa(String.fromCharCode.apply(null, new Uint8Array(xhr.response)));
      }
    }
  xhr.responseType = "arraybuffer";
  xhr.open("GET","Hacker.jpg",true);
  xhr.send();
  


Know more about XHR2 look at http://www.html5rocks.com/en/tutorials/file/xhr2/

HTML, jQUERY find actual size of image in img tag


Basically using DOM functions, if we try and get the size of <img />, we always get the dimensions of DOM element, not the actual image.

To be able to get actual size of image, we will have to reload it in a new <img /> without any size restriction. If we do that, this new <img /> will take dimensions of actual image, and using simple DOM methods we can get the actual size of image.

Sample HTML

<img src="http://doc.jsfiddle.net/_downloads/jsfiddle-desktop-1440x900-a.png" width="480" height="300">

JS trick

function getImageSize(url, callback){
    $('<img />').attr('src', url).load(function(){
        callback(this.width, this.height);
    });
}
getImageSize($("img").attr('src'), function(width, height){
        console.log(width, height);
});

Try this on JSFIDDLE.

HTML5 Update

HTML5 has introduced a much easier way of doing the same thing. If your browser supports HTML5, ignore the previous method and use this one.

$("img")[0].naturalWidth
$("img")[0].naturalHeight

JavaScript faster for loops


Assuming you want to traverse through an array using for-loop

var array = [...........]

Slow Way

array.forEach(function(x){
    // TODO: Do Something
});

Fast Way

for(var i = 0; i < array.length; i++){
    // TODO: Do Something
}

Faster Way

for(var i = 0, len = array.length; i < len; i++){
    // TODO: Do Something
}

Reference: https://blogs.oracle.com/greimer/entry/best_way_to_code_a

Get Apache & PHP working on Mac OS X 10.10 Yosemite


Three saviour commands

Start Apache
sudo apachectl start

Stop Apache
sudo apachectl stop

Restart Apache
sudo apachectl restart

Enable PHP
Open terminal and edit /etc/apache2/httpd.conf

sudo vi /etc/apache2/httpd.conf

Go to line # LoadModule php5_module libexec/apache2/libphp5.so and remove # and save the file and restart the server.

Document Root
Document Root is the folder where PHP files are shared and executed. By default in Yosemite Document Root is set to /Library/WebServer/Documents.

To change it to your custom location edit the /etc/apache2/httpd.conf again and make following lines

  • change DocumentRoot "/Library/WebServer/Documents" to DocumentRoot "/your/path/to/shared/folder"
  • change <Directory "/Library/WebServer/Documents"> to <Directory "/your/path/to/shared/folder">

save the file and restart the server.

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.