Sunday, 12 October 2014

How to parse Json file and display result in android?

Let's consider personality application where going to display actor's name, actor's description, actor's image etc.,

Let's take a json sample form this link..

https://dl.dropboxusercontent.com/s/jv2trufpmgr2gjz/actors.json?dl=0

Structure looks like this..

{
  "actors": [
    {
      "name": "Brad Pitt",
      "description": "William Bradley 'Brad' Pitt is an American actor and film producer. He has received a Golden Globe Award, a Screen Actors Guild Award, and three Academy Award nominations in acting categories",
      "dob": "December 18, 1963",
      "country": "United States",
      "height": "1.80 m",
      "spouse": "Jennifer Aniston",
      "children": "Shiloh Nouvel Jolie-Pitt, Maddox Chivan Jolie-Pitt",
      "image": "http://microblogging.wingnity.com/JSONParsingTutorial/brad.jpg"
    },
    
    {
      "name": "Will Smith",
      "description": "Willard Carroll 'Will' Smith, Jr. is an American actor, producer, and rapper. He has enjoyed success in television, film, and music.",
      "dob": "September 25, 1968",
      "country": "United States",
      "height": "1.88 m",
      "spouse": "Jada Pinkett Smith",
      "children": "Jaden Smith, Willow Smith, Trey Smith",
      "image": "http://microblogging.wingnity.com/JSONParsingTutorial/will.jpg"
    }
  ]
}

Persons.java:


public class Persons {
private String name;
private String description;
private String dob;

private String country;
private String height;
private String spouse;
private String children;
private String image;
    public Persons(){

}
public Persons(String name,String description,String dob,String country,String height,String spouse,String children, String image){
this.name=name;
this.description=description;
this.dob=dob;
this.country=country;
this.height=height;
this.spouse=spouse;
this.children=children;
this.spouse=spouse;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getSpouse() {
return spouse;
}
public void setSpouse(String spouse) {
this.spouse = spouse;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getChildren() {
return children;
}
public void setChildren(String children) {
this.children = children;
}

}



GridUI.java:

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.personality.caches.ImageLoader;


import android.app.Activity;
import android.app.ProgressDialog;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.Toast;


public class GridUI extends Activity {
ArrayList<Persons> personsList;
GridView gridView;
GridAdapter gridAdapter;
private static final String url="https://dl.dropboxusercontent.com/s/jv2trufpmgr2gjz/actors.json?dl=0";
private  ImageLoader loader;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gridview);
        personsList= new ArrayList<Persons>();
    new JSONAsyncTask().execute(url);
    gridView=(GridView)findViewById(R.id.gridview);
    loader=new ImageLoader(GridUI.this);
    gridAdapter = new GridAdapter(this, R.layout.gridview_row, personsList);
    gridView.setAdapter(gridAdapter);
   
    }
    class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
    ProgressDialog dialog;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=new ProgressDialog(GridUI.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);

}


@Override
protected Boolean doInBackground(String... urls) {
        try {

//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);

// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();

if(status==200){
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);

JSONObject jsono=new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);

Persons actor = new Persons();

actor.setName(object.getString("name"));
actor.setDescription(object.getString("description"));
actor.setDob(object.getString("dob"));
actor.setCountry(object.getString("country"));
actor.setHeight(object.getString("height"));
actor.setSpouse(object.getString("spouse"));
actor.setChildren(object.getString("children"));
actor.setImage(object.getString("image"));

personsList.add(actor);
}
return true;
}

//------------------>>

} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}



@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.cancel();
gridAdapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.splash, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


GridAdapter.java:

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.personality.caches.ImageLoader;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class GridAdapter extends BaseAdapter {
public  ImageLoader loader;
private final ArrayList<Persons> itemLists;
public static final String NAME="name";
public static final String DOB="dob";
public static final String HEIGHT="height";
public static final String COUNTRY="country";
public static final String DESCRIPTION="description";
public static final String SPOUSE="spouse";
public static final String CHILDREN="children";
public static final String image="image";



  LayoutInflater layoutInflater;
  int Resource;
  ViewHolder viewHolder;
  Activity activity;


  public GridAdapter(Activity a, int resource, ArrayList<Persons> itemList) {
layoutInflater = (LayoutInflater) a
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
itemLists=itemList;
activity=a;
 loader=new ImageLoader(a.getApplicationContext());



}
  @Override
public int getCount() {
return itemLists.size();

}


  @Override
public Object getItem(int position) {
return itemLists.get(position);
}
@Override
public long getItemId(int position) {
return position;

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v= convertView;
try {
if(v==null){
viewHolder = new ViewHolder();
v = layoutInflater.inflate(Resource, null);
viewHolder.tvName=(TextView)v.findViewById(R.id.tvname);
viewHolder.imageview=(SquareImageView)v.findViewById(R.id.picture);
v.setTag(viewHolder);


}
else{
viewHolder = (ViewHolder) v.getTag();

}

final String actorImage=itemLists.get(position).getImage();
final String name=itemLists.get(position).getName();
final String dob=itemLists.get(position).getDob();
final String height=itemLists.get(position).getHeight();
final String country=itemLists.get(position).getCountry();
final String description=itemLists.get(position).getDescription();
final String spouse=itemLists.get(position).getSpouse();
final String children=itemLists.get(position).getChildren();
final String search = itemLists.get(position).getName().toString();

//  Ion.with(viewHolder.imageview).placeholder(R.drawable.ic_launcher).error(R.drawable.ic_launcher).load(actorImage);
viewHolder.tvName.setText(itemLists.get(position).getName());
loader.DisplayImage(actorImage,viewHolder.imageview);
itemLists.get(position).getImage();
viewHolder.imageview.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {

if(search.contains("Brad Pitt")){
Toast.makeText(activity, "Bradss", Toast.LENGTH_SHORT)
.show();}
else{
}
// TODO Auto-generated method stub
Intent intent=new Intent(activity,DetailsActivity.class);
intent.putExtra(NAME, name);
intent.putExtra(DOB, dob);
intent.putExtra(HEIGHT, height);
intent.putExtra(COUNTRY, country);
intent.putExtra(DESCRIPTION, description);
intent.putExtra(SPOUSE, spouse);
intent.putExtra(CHILDREN, children);
intent.putExtra(image, actorImage);
activity.startActivity(intent);



}
});
// TODO Auto-generated method stub
}
catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
static class ViewHolder {
public SquareImageView imageview;
public TextView tvName;


}

}
gridview.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="0dp"
        android:horizontalSpacing="0dp"
        android:stretchMode="columnWidth"
        android:numColumns="2" />
</FrameLayout>


gridviewrow.xml:

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent">
    <com.personality.SquareImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        />
    <TextView
        android:id="@+id/tvname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:layout_gravity="bottom"
        android:textColor="@android:color/white"
        android:background="#55000000"
        />
</FrameLayout>

DetailsActivity.java:

package com.personality;

import com.personality.caches.ImageLoader;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class DetailsActivity extends Activity {
ImageView imageView;
TextView name,dob,height,country,description,spouse,children;
private Bundle bundle;
public  ImageLoader loader;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.details);
   loader=new ImageLoader(DetailsActivity.this);

        name=(TextView)findViewById(R.id.tvName);
        dob=(TextView)findViewById(R.id.tvDateOfBirth);
        height=(TextView)findViewById(R.id.tvHeight);
        country=(TextView)findViewById(R.id.tvCountry);
        description=(TextView)findViewById(R.id.tvDescriptionn);
        spouse=(TextView)findViewById(R.id.tvSpouse);
        children=(TextView)findViewById(R.id.tvChildren);
        imageView=(ImageView)findViewById(R.id.ivImage);
        
bundle = this.getIntent().getExtras();
if(bundle != null && bundle.containsKey(GridAdapter.NAME) && bundle.containsKey(GridAdapter.CHILDREN) && bundle.containsKey(GridAdapter.COUNTRY) && bundle.containsKey(GridAdapter.DESCRIPTION) && bundle.containsKey(GridAdapter.DOB)&& bundle.containsKey(GridAdapter.HEIGHT) && bundle.containsKey(GridAdapter.image) && bundle.containsKey(GridAdapter.SPOUSE)){
String names=bundle.getString(GridAdapter.NAME);
String childrens=bundle.getString(GridAdapter.CHILDREN);
String dobs=bundle.getString(GridAdapter.DOB);
String heights=bundle.getString(GridAdapter.HEIGHT);
String countrys=bundle.getString(GridAdapter.COUNTRY);
String descriptions=bundle.getString(GridAdapter.DESCRIPTION);
String spouses=bundle.getString(GridAdapter.SPOUSE);
String images=bundle.getString(GridAdapter.image);
name.setText(names);
dob.setText(dobs);
children.setText(childrens);
height.setText(heights);
country.setText(countrys);
description.setText(descriptions);
spouse.setText(spouses);
loader.DisplayImage(images,imageView);

}

    }

}
details.xml:

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
   <LinearLayout
        android:id="@+id/LinearLayouts"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="4dp"
        android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
            
              <LinearLayout
            android:layout_width="300dp"
            android:layout_height="300dp"
             >
            

            <ImageView
                android:id="@+id/ivImage"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="10dp"
                android:layout_gravity="center"
                android:src="@drawable/ic_launcher" />
            </LinearLayout>

            <TextView
                android:id="@+id/tvName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:text="Tom Cruise"
                android:textColor="#166CED"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <TextView
                android:id="@+id/tvDateOfBirth"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#D64530"
                android:text="Date of Birth: July 3, 1962" />

            <TextView
                android:id="@+id/tvHeight"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Height: 1.80 m"
                android:textColor="#D64530"
                android:textAppearance="?android:attr/textAppearanceSmall" />

            <TextView
                android:id="@+id/tvCountry"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#D64530"
                android:text="United States" />

        </LinearLayout>

    </LinearLayout>

    <TextView
        android:id="@+id/tvDescriptionn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#009A57"
        android:text="Description" />

    <TextView
        android:id="@+id/tvSpouse"
        android:layout_width="wrap_content" android:textColor="#166CED"
        android:layout_height="wrap_content"
        android:text="Spouse: Katie Holmes" />

    <TextView
        android:id="@+id/tvChildren"
        android:layout_width="wrap_content" android:textColor="#166CED"
        android:layout_height="wrap_content"
        android:text="Children: Suri Cruise, Isabella Jane Cruise, Connor Cruise" />
</LinearLayout>
    
</ScrollView>


Add imageLoader.jar files.

FileCache.java:

import java.io.File;
import android.content.Context;
public class FileCache {
     
    private File cacheDir;
     
    public FileCache(Context context){
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"TTImages_cache");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }
     
    public File getFile(String url){
        //I identify images by hashcode. Not a perfect solution, good for the demo.
        String filename=String.valueOf(url.hashCode());
        //Another possible solution (thanks to grantland)
        //String filename = URLEncoder.encode(url);
        File f = new File(cacheDir, filename);
        return f;
         
    }
     
    public void clear(){
        File[] files=cacheDir.listFiles();
        if(files==null)
            return;
        for(File f:files)
            f.delete();
    }
}


imageLoader.java:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.personality.R;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class ImageLoader {

   ImageLoader imageLoader;     
    MemoryCache memoryCache=new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService; 
     
    public ImageLoader(Context context){
        fileCache=new FileCache(context);
        executorService=Executors.newFixedThreadPool(5);
    }
     
    final int stub_id=R.drawable.ic_launcher;
    public void DisplayImage(String url, ImageView imageView)
    {
        imageViews.put(imageView, url);
        Bitmap bitmap=memoryCache.get(url);
        if(bitmap!=null)
            imageView.setImageBitmap(bitmap);
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }
    }
         
    private void queuePhoto(String url, ImageView imageView)
    {
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }
     
    private Bitmap getBitmap(String url) 
    {
        File f=fileCache.getFile(url);
         
        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;
         
        //from web
        try {
            Bitmap bitmap=null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex){
           ex.printStackTrace();
           if(ex instanceof OutOfMemoryError)
               memoryCache.clear();
           return null;
        }
    }
    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);
             
            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=200;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }
             
            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }
     
    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u; 
            imageView=i;
        }
    }
     
    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;
        PhotosLoader(PhotoToLoad photoToLoad){
            this.photoToLoad=photoToLoad;
        }
         
        @Override
        public void run() {
            if(imageViewReused(photoToLoad))
                return;
            Bitmap bmp=getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if(imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
            Activity a=(Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }
    }
     
    boolean imageViewReused(PhotoToLoad photoToLoad){
        String tag=imageViews.get(photoToLoad.imageView);
        if(tag==null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }
     
    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;
        public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
        public void run()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap!=null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }
    public void pause(){
imageLoader.pause();
}

public void resume(){
imageLoader.resume();
}


public void stop() {
imageLoader.stop();
}

}

MemoryCache.java:

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import android.graphics.Bitmap;
import android.util.Log;
public class MemoryCache {
    private static final String TAG = "MemoryCache";
    private Map<String, Bitmap> cache=Collections.synchronizedMap(
            new LinkedHashMap<String, Bitmap>(10,1.5f,true));//Last argument true for LRU ordering
    private long size=0;//current allocated size
    private long limit=1000000;//max memory in bytes
    public MemoryCache(){
        //use 25% of available heap size
        setLimit(Runtime.getRuntime().maxMemory()/4);
    }
     
    public void setLimit(long new_limit){
        limit=new_limit;
        Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB");
    }
    public Bitmap get(String id){
        try{
            if(!cache.containsKey(id))
                return null;
            //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78 
            return cache.get(id);
        }catch(NullPointerException ex){
            ex.printStackTrace();
            return null;
        }
    }
    public void put(String id, Bitmap bitmap){
        try{
            if(cache.containsKey(id))
                size-=getSizeInBytes(cache.get(id));
            cache.put(id, bitmap);
            size+=getSizeInBytes(bitmap);
            checkSize();
        }catch(Throwable th){
            th.printStackTrace();
        }
    }
     
    private void checkSize() {
        Log.i(TAG, "cache size="+size+" length="+cache.size());
        if(size>limit){
            Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();//least recently accessed item will be the first one iterated  
            while(iter.hasNext()){
                Entry<String, Bitmap> entry=iter.next();
                size-=getSizeInBytes(entry.getValue());
                iter.remove();
                if(size<=limit)
                    break;
            }
            Log.i(TAG, "Clean cache. New size "+cache.size());
        }
    }
    public void clear() {
        try{
            //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78 
            cache.clear();
            size=0;
        }catch(NullPointerException ex){
            ex.printStackTrace();
        }
    }
    long getSizeInBytes(Bitmap bitmap) {
        if(bitmap==null)
            return 0;
        return bitmap.getRowBytes() * bitmap.getHeight();
    }
}

Utils.java:

import java.io.InputStream;
import java.io.OutputStream;
public class Utils {
    public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }
}

Tuesday, 30 September 2014

Displaying images form list of urls in android.

Now I am going to discuss about how to display images from list of url in android.

Let's follow some code standardization. Code Standardization is where no constants should be declared inside the class file. It should be moved by creating Constants.java. and for xml you can use strings.

Flow of the application is When you click from Listview, it displays images where I am using viewpager to swipe image from left to right and vice versa.

Getting a list of constants urls
Constants.java:

public final class Constants {
public static final String[] aakansha={
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-001.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-002.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-003.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-004.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-005.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-006.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-007.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-008.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-009.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-010.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-011.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-012.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-013.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-014.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-016.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-017.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-018.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-019.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-021.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-022.jpg",
           "http://androidexample.com/media/webservice/LazyListView_images/image9.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image10.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image0.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image1.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image2.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image3.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image4.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image5.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image6.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image7.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image8.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image9.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image10.png"
         
   };

public static final String[] mStrings1={
           "http://androidexample.com/media/webservice/LazyListView_images/image9.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image10.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image0.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image1.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image2.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image3.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image4.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image5.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image6.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image7.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image8.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image9.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image10.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image0.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image1.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image2.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image3.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image4.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image5.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image6.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image7.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image8.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image9.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image10.png"
         
   };
}

 Create ListActivity.java

import com.example.constants.Constants;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class ListActivity extends Activity {
private ListView list;
HelpAdapter adapter;
   private Static final String KEY="key";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String[] listItems = getResources().getStringArray(R.array.help_items);

   list = (ListView) findViewById(R.id.listview);
   adapter = new HelpAdapter(this,listItems);
   list.setAdapter(adapter);
   list.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
if(position==0){
Intent intent=new Intent(ListActivity.this,ViewPagerSwipe.class);
intent.putExtra(KEY, Constants.aakansha); //pass the key and value.
startActivity(intent);
}
if(position==1){
Intent intent=new Intent(ListActivity.this,ViewPagerSwipe.class);
intent.putExtra(KEY, Constants.mStrings1);
startActivity(intent);
}
}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list, menu);
return true;
}

}

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=".ListActivity" >

     <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/listview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginTop="6dp" >
        </ListView>
    </LinearLayout>

</RelativeLayout>


I created a custom Adapter as for further development, I may place image and text too..Now just a text been used in HelpAdapter

HelpAdapter.java:

import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class HelpAdapter extends BaseAdapter {
    // Declare Variables
    private Context context;
    private String[] rank;
    private LayoutInflater inflater;
    public HelpAdapter(Context context, String[] rank) {
        this.context = context;
        this.rank = rank;
    }
    @Override
    public int getCount() {
        return rank.length;
    }
    @Override
    public Object getItem(int position) {
        return null;
    }
    @Override
    public long getItemId(int position) {
        return 0;
    }
    public View getView(int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView helpText;
        ImageView imgflag;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemView = inflater.inflate(R.layout.activity_help_row, parent, false);
        // Locate the TextViews in activity_help_row.xml
        helpText = (TextView) itemView.findViewById(R.id.helptext);
        // Locate the ImageView in activity_help_row.xml
        // Capture position and set to the TextViews
        helpText.setText(rank[position]);
        // Capture position and set to the ImageView
        return itemView;
    }
}
activity_help_row.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" >

   <RelativeLayout
        android:id="@+id/helpTextLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="vertical"
        android:visibility="visible" >

        <TextView
            android:id="@+id/helptext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:textSize="18sp" />

    </RelativeLayout>

</LinearLayout>

and in strings.xml: for array items, declare it. as I used in ListActivity to get collection of items in array. Always don't declare any constants in java file.Best practice is use in strings.

  final String[] listItems = getResources().getStringArray(R.array.help_items);


<array name="help_items">
        
        <item>A</item>
        <item>B</item>
    </array>

ViewPagerSwipe.java :

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.widget.Toast;

public class ViewPagerSwipe extends Activity {
ViewPagerAdapter viewpageradapter;
ViewPager viewpager;
private int currentPage;
@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.viewpage);
 Bundle extras = getIntent().getExtras();
 if(extras !=null) {
   String[] value = extras.getStringArray(ListActivity.KEY); // since it has been declared public.
 ViewPager viewpager=(ViewPager)findViewById(R.id.myfivepanelpager);
 viewpageradapter=new ViewPagerAdapter(this,value);
 viewpager.setCurrentItem(0);
 viewpager.setAdapter(viewpageradapter);
 currentPage=viewpageradapter.getCount();
 viewpager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
}
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
 
}
}

}

viewpage.xml:

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

    <android.support.v4.view.ViewPager
        android:id="@+id/myfivepanelpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

ViewPagerAdapter.java:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import android.net.Uri;
import com.example.utils.ImageLoader;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.Toast;

public class ViewPagerAdapter extends PagerAdapter {
Activity activity;
String imgArray[];
public ImageLoader imageLoader; 

public ViewPagerAdapter(Activity act, String[] imgArra) {
imgArray=imgArra;
activity=act;
   imageLoader=new ImageLoader(activity.getApplicationContext());

// TODO Auto-generated constructor stub
}

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

@Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0 == ((View) arg1);
}
public Object instantiateItem(View collection, int position) {
View view=null;
LayoutInflater layoutinflater=(LayoutInflater)collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=layoutinflater.inflate(R.layout.adapter, null);
int count=getCount();
final ImageView image=(ImageView)view.findViewById(R.id.imageView1);
image.setScaleType(ScaleType.FIT_XY);
imageLoader.DisplayImage(imgArray[position], image);
// image.setBackgroundResource(imgArray[position]);
 ((ViewPager) collection).addView(view, 0);
return view;
 
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
 ((ViewPager) arg0).removeView((View) arg2);
}


@Override
public Parcelable saveState() {
 return null;
}

}

adapter.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" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

As I used image loader. Add the jar file of image loader or use the package

FileCache.java:

import java.io.File;
import android.content.Context;
public class FileCache {
     
    private File cacheDir;
     
    public FileCache(Context context){
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"TTImages_cache");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }
     
    public File getFile(String url){
        //I identify images by hashcode. Not a perfect solution, good for the demo.
        String filename=String.valueOf(url.hashCode());
        //Another possible solution (thanks to grantland)
        //String filename = URLEncoder.encode(url);
        File f = new File(cacheDir, filename);
        return f;
         
    }
     
    public void clear(){
        File[] files=cacheDir.listFiles();
        if(files==null)
            return;
        for(File f:files)
            f.delete();
    }
}

ImageLoader.java:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class ImageLoader {
     
    MemoryCache memoryCache=new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService; 
     
    public ImageLoader(Context context){
        fileCache=new FileCache(context);
        executorService=Executors.newFixedThreadPool(5);
    }
     
    final int stub_id=R.drawable.ic_launcher;
    public void DisplayImage(String url, ImageView imageView)
    {
        imageViews.put(imageView, url);
        Bitmap bitmap=memoryCache.get(url);
        if(bitmap!=null)
            imageView.setImageBitmap(bitmap);
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }
    }
         
    private void queuePhoto(String url, ImageView imageView)
    {
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }
     
    private Bitmap getBitmap(String url) 
    {
        File f=fileCache.getFile(url);
         
        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;
         
        //from web
        try {
            Bitmap bitmap=null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex){
           ex.printStackTrace();
           if(ex instanceof OutOfMemoryError)
               memoryCache.clear();
           return null;
        }
    }
    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);
             
            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=200;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }
             
            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }
     
    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u; 
            imageView=i;
        }
    }
     
    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;
        PhotosLoader(PhotoToLoad photoToLoad){
            this.photoToLoad=photoToLoad;
        }
         
        @Override
        public void run() {
            if(imageViewReused(photoToLoad))
                return;
            Bitmap bmp=getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if(imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
            Activity a=(Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }
    }
     
    boolean imageViewReused(PhotoToLoad photoToLoad){
        String tag=imageViews.get(photoToLoad.imageView);
        if(tag==null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }
     
    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;
        public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
        public void run()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap!=null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }
    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }
}

MemoryCache.java:

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import android.graphics.Bitmap;
import android.util.Log;
public class MemoryCache {
    private static final String TAG = "MemoryCache";
    private Map<String, Bitmap> cache=Collections.synchronizedMap(
            new LinkedHashMap<String, Bitmap>(10,1.5f,true));//Last argument true for LRU ordering
    private long size=0;//current allocated size
    private long limit=1000000;//max memory in bytes
    public MemoryCache(){
        //use 25% of available heap size
        setLimit(Runtime.getRuntime().maxMemory()/4);
    }
     
    public void setLimit(long new_limit){
        limit=new_limit;
        Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB");
    }
    public Bitmap get(String id){
        try{
            if(!cache.containsKey(id))
                return null;
            //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78 
            return cache.get(id);
        }catch(NullPointerException ex){
            ex.printStackTrace();
            return null;
        }
    }
    public void put(String id, Bitmap bitmap){
        try{
            if(cache.containsKey(id))
                size-=getSizeInBytes(cache.get(id));
            cache.put(id, bitmap);
            size+=getSizeInBytes(bitmap);
            checkSize();
        }catch(Throwable th){
            th.printStackTrace();
        }
    }
     
    private void checkSize() {
        Log.i(TAG, "cache size="+size+" length="+cache.size());
        if(size>limit){
            Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();//least recently accessed item will be the first one iterated  
            while(iter.hasNext()){
                Entry<String, Bitmap> entry=iter.next();
                size-=getSizeInBytes(entry.getValue());
                iter.remove();
                if(size<=limit)
                    break;
            }
            Log.i(TAG, "Clean cache. New size "+cache.size());
        }
    }
    public void clear() {
        try{
            //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78 
            cache.clear();
            size=0;
        }catch(NullPointerException ex){
            ex.printStackTrace();
        }
    }
    long getSizeInBytes(Bitmap bitmap) {
        if(bitmap==null)
            return 0;
        return bitmap.getRowBytes() * bitmap.getHeight();
    }
}

Utils.java:

import java.io.InputStream;
import java.io.OutputStream;
public class Utils {
    public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }
}

If you want to save or share an image.Create a button in adapter.xml or you can also use it in menu based on your requiremnt. I just show it in ViewPagerAdapter.

 public Object instantiateItem(View collection, int position) {
    LayoutInflater layoutinflater=(LayoutInflater)collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=layoutinflater.inflate(R.layout.adapter, null);
Button save=(Button)view.findViewById(R.id.savebutton);
Button share=(Button)view.findViewById(R.id.sharebutton);
save.setText("Save"+count);
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
 BitmapDrawable bitmapDrawable = (BitmapDrawable)image.getDrawable();
       Bitmap bitmap = bitmapDrawable.getBitmap();
 
       // Save this bitmap to a file.
       File cache = activity.getExternalCacheDir();
       File sharefile = new File(cache, "save.png"); //give your name and save it.
       try {
           FileOutputStream out = new FileOutputStream(sharefile);
           bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
           out.flush();
           out.close();
       } catch (IOException e) {
         
       }
 
       // Now send it out to share
       Intent share = new Intent(android.content.Intent.ACTION_SEND);
       share.setType("image/*");
       share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile));
       try {
           activity.startActivity(Intent.createChooser(share, "Share photo"));
       } catch (Exception e) {
           
       }
}
});
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
image.setDrawingCacheEnabled(true);
               Bitmap bitmap = image.getDrawingCache();
               
               String root = Environment.getExternalStorageDirectory().toString();
               File newDir = new File(root + "/Nokia");    
               newDir.mkdirs();
               Random gen = new Random();
               int n = 10000;
               n = gen.nextInt(n);
               String fotoname = "Photo-"+ n +".jpg";
               File file = new File (newDir, fotoname);
               if (file.exists ()) file.delete (); 
                try {
                      FileOutputStream out = new FileOutputStream(file);
                      bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                      out.flush();
                      out.close();
                      Toast.makeText(activity, "Saved to your folder"+fotoname, Toast.LENGTH_SHORT ).show();

               } catch (Exception e) {
                
               }
                       
            }
}) ;
             //others all are same.
image.setScaleType(ScaleType.FIT_XY);
imageLoader.DisplayImage(imgArray[position], image);
// image.setBackgroundResource(imgArray[position]);
 ((ViewPager) collection).addView(view, 0);
return view;
 
}

Happy Coding.. :)





Monday, 29 September 2014

How to add Ads in android.

 There are so many ads for mobile application especially in android. Some of them are

1. Admob
2. Airpush
3.Startapp
4.LeadBolt
5. Mopub and so on.

I used all.The best one is top 3 ad networks. Previously Admob provided SDK but now it has been integrated with Google play services so that you don't need to use separate sdk for Admob.

How to use Admob?

Go to apps.admob.com. Create an account and give your app name and it provides you an ad unit.

Use which ad type you are going to display.  Since other networks are providing a clean documentation when you logged in. But Admob you need to surf and for new update, you can't find a clear updates and user miss some important keys in admob which I noticed. Here I am discussing about this.

Admob provides two types.

1. Banner adview

2. Interestitial ads.

If you choose interestitial ads, you can use like this.

import com.google.android.gms.ads.InterstitialAd;

public class MainActivity extends Activity {
private InterstitialAd interstitial; // Declare interstitial ads here.


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
           interstitial = new InterstitialAd(MainActivity.this);
        // Insert the Ad Unit ID
        interstitial.setAdUnitId("<Ad unit id>");

          AdRequest adRequests = new AdRequest.Builder().build();
   interstitial.loadAd(adRequests);
   interstitial.setAdListener(new AdListener() {
       @Override
       public void onAdLoaded() {
           super.onAdLoaded();
           interstitial.show();

       }

       @Override
       public void onAdFailedToLoad(int errorCode) {
           super.onAdFailedToLoad(errorCode);

       }

   });
 
       }
     

  For Banner ads:

       AdView adView = (AdView) this.findViewById(R.id.adView);
    
        AdRequest adRequest = new AdRequest.Builder()

        // Add a test device to show Test Ads..comment for real app when launching
        // .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
         //.addTestDevice("CC5F2C72DF2B356BBF0DA198")
                .build();

        // Load ads into Banner Ads
        adView.loadAd(adRequest);

    in xml:

       <com.google.android.gms.ads.AdView
         android:id="@+id/adView"
                         android:layout_width="wrap_content"
                         android:layout_height="wrap_content"
                         ads:adUnitId="<ads id>"
                         ads:adSize="BANNER"/>

 important to note that, you need to declare for xml as:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto" // these line is most needed in top of the xml when you are using adview inside layout.
................
<Adview> here
>
</LinearLayout>

 and in manifest file, these lines are to be added

 <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
 
        <activity
            android:name="com.google.android.gms.ads.AdActivity"        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
 

You can run and test it and it works.



Monday, 23 June 2014

My first experience with seminar in Android as Chief Guest -October 2012

Had  conducted two days of  workshop about Android. Though many workshop conducted, but the first workshop about Android was at Mahendra Engineering college on October  5th and 6th.
It was nice as principal, HOD were very interacted and taken care and arrangements were made to us as Chief Guest to the college were perfect. 

Me and my colleague Sivaputra invited as Chief Guest to the college. It's a great honour and immense pleasure for us. The first session handled by him the whole day where I taken care of handling next day.Nearly 200 students participated in the workshop.  Handling nearly 200 students by two of them was a challenging one where students should not get bored. Already well prepared by both to have some fun in between also to interact with students to their place. Representative  also taken care of us by arranging necessary which needed. College taken care the whole two days for accommodation and everything.  We given our best by providing students a valuable and sharing knowledge to them.  







Sunday, 22 December 2013

Increase Whatsapp trail period

Now whatsapp is increasing by more users since it has more advantage like an instant messenger which deliver your message immediately you send it and receive message immediately you sent message.It also allow you to send multimedia message such as voice record,video,video record,audio,image etc., but we all know every whatsapp users are entitled to 1 year free trial period before the person will be subsequently paying after trail ends.

I strongly recommend doing this when your whatsapp is a day to expire but you can still use it now. Faster enough the better it is.

Below will explain how to extend whatsapp usage.

Its available for the following devices.

 — S40 Java C3-00 / C3-01 / X2-00 / X2-01 / X3-02 / 201 / 300 / 302 / 303 / 306 / 311
— Symbian: X7 · E6 · N8 · C6 · C7 · E7 · 500 · 600 · 603 · 700 · 701 · 808
— S60 5th edition: Nokia 5800 · Nokia 5530 · Nokia 5230 · Nokia 5233 · Nokia 5235 · Nokia N97 · Nokia N97 mini · Nokia X6 · Nokia X5-01 · Nokia C6 · Nokia C5-03 · Samsung i8910 Omnia HD · Sony Ericsson Satio · Sony Ericsson Vivaz · Sony Ericsson Vivaz Pro
— S60 3rd edition: Nokia 5700 · Nokia 6110 · Nokia 6120 · Nokia 6121 · Nokia 6124 · Nokia 6700 · Nokia 6290 · Nokia E51 · Nokia E63 · Nokia E66 · Nokia E71 · Nokia E90 Communicator · Nokia N76 · Nokia N81 · Nokia N81 8GB · Nokia N82 · Nokia N95 · Nokia N95 8GB · Nokia 5320 · Nokia 5630 · Nokia 5730 · Nokia 6210 · Nokia 6220 · Nokia 6650 fold · Nokia 6710 Navigator · Nokia 6720 · Nokia 6730 · Nokia 6760 Slide · Nokia 6790 Surge · Nokia C5 · Nokia E52 · Nokia E55 · Nokia E72 · Nokia E73 · Nokia E75 · Nokia E5 · Nokia N78 · Nokia N79 · Nokia N85 · Nokia N86 8MP · Nokia N96 · Samsung GT-i8510 · Samsung GT-I7110 · Samsung SGH-L870 · Samsung SGH-G810 · Samsung SGH-iNNN

Note: Since there are so many devices,some device may also support which is not in this list.Just try it.

Step 1:
Open your whatsapp and press Option > About > Account Info > Option > Delete Account

Step 2:
A page will be displayed telling you to enter your mobile number and telling you what will happen. 
 Delete All Your Whatsapp Service Payment Information

Step 3:
Then press continue after you enter your phone number and follow the next steps to complete deletion.

Step 4:
Now trial is gone but you are no more on whatsapp. Read on.
Open whatsapp back and register as normal as you do before by entering and confirming your phone number.

Step 5:
After successful registration, you get one more year free. Check the status again as explained above in the first place.

Step 6:
Finished.. all you need to do to get rid of the trial.





Tuesday, 17 December 2013

Game physics with Liquid Fun in android

Liquid Fun

LiquidFun is a 2D rigid body simulation library for games. Programmers can use it in their games to make objects move in realistic ways and make the game world more interactive

Physics Engine:

A system for generating procedural animations deals with physical process especially collisions. Doesn't
include rendering code.

Supporting Platforms :

Android

OSX

Windows

Particle Characteristics:

Color

Size

Position

Velocity

Strength

Creating a particle:


   b2ParticleDef pd;
   pd.flags = b2_elasticParticle;
   pd.color.Set(0, 0, 255, 255);
   pd.position.Set(i, 0);
   int tempIndex = m_world->CreateParticle(pd);


Particle Groups:

Create and destroy many particles at once.
Add Properties as Rotational angle,velocity, strength

Creating Particle Groups:

Create a shape
Create particular group definition object
Create the group

A sample code to demonstrate about creating and destroying particle:

Group creation code:

   b2ParticleGroupDef pd;
   b2PolygonShape shape;
   shape.SetAsBox(10, 5);
   pd.shape = 
   pd.flags = b2_elasticParticle;
   pd.angle = -0.5f;
   pd.angularVelocity = 2.0f;
   for (int32 i = 0; i < 5; i++)
   {
      pd.position.Set(10 + 20 * i, 40);
      pd.color.Set(i * 255 / 5, 255 - i * 255 / 5, 128, 255);
      world->CreateParticleGroup(pd);
      m_world->CreateParticleGroup(pd);
   }

Particle destroy:

   b2ParticleGroup* group = m_world->GetParticleGroupList();
   while (group)
   {
      b2ParticleGroup* nextGroup = group->GetNext(); // access this before we destroy the group
      m_world->DestroyParticleGroup(group);
      group = nextGroup;
   }

Source: 








Wednesday, 4 December 2013

Android Kitkat 4.4 features

Android kitkat 4.4 released on October 31st with special features.

1. Low memory support even in 512 Ram. This includes new Api ActivityManager.isLowRamDevice() which let's your app's behaviour to match target device's memory.

2. NFC through Host Card Emulation: Android 4.4 introduces Host card Emulation where it's based on Smart card that uses contactless protocol for transmission.

3.Sms ProviderThe new APIs use  new SMS_Deliver intent to allow app developers to route messages through the user’s default messaging app, making the cross-app experience seamless.

4.New Sensor Modes and Connectivity Hardware Sensor Batching is a new optimization that dramatically reduce power consumption during ongoing sensor activities.

5. Improved Security: Allows Antivirus Scanner api,control over individual app permissions.  KitKat also improves upon the cryptographic algorithms by adding support for two additional algorithms.

6.Chromium WebviewAndroid 4.4 includes a completely new implementation of WebView that's based on Chromium.Chromium WebView provides broad support for HTML5, CSS3, and JavaScript. It supports most of the HTML5 features available in Chrome for Android 30. It also brings an updated version of the JavaScript Engine (V8) that delivers dramatically improved JavaScript performance.

7.Screen Recording Android 4.4 adds support for screen recording and provides a screen recording utility that lets you start and stop recording on a device that's connected to your Android SDK environment over USB. It's a great new way to create walkthroughs and tutorials for your app, testing materials, marketing videos etc.,If your app plays video or other protected content that you don’t want to be captured by the screen recorder, you can useSurfaceView.setSecure() to mark the content as secure.