Thursday, 10 April 2014

how to Integrating AdMob in your Android App example


main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent" >
               
       <RelativeLayout
           android:id="@+id/add_mombe"
           android:layout_width="match_parent"
           android:layout_height="50dp"
           android:layout_alignParentBottom="true"
           android:background="#000000" >
       </RelativeLayout>
               
</RelativeLayout>

MainActivity.java

package com.example;

import android.app.Activity;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class MainActivity extends Activity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
     
        advertisement();
       
    public void advertisement() {

        RelativeLayout layout = (RelativeLayout) findViewById(R.id.add_mombe);
        AdView adView = new AdView(this, AdSize.BANNER, "your ID");
        layout.addView(adView);
        AdRequest request = new AdRequest();
        request.setTesting(true);
        adView.loadAd(request);
    }
}

AndroidManifest

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

<activity
            android:name="com.google.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation" >
        </activity>

how to create HorizontialListView in andoird


min.xml

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

<RelativeLayout
                    android:id="@+id/image_one"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/lin1"
                    android:layout_centerHorizontal="true">

                    <your package name.HorizontialListView
                        android:id="@+id/listview1"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content" >
                    </your package name.HorizontialListView>

                </RelativeLayout>
</RelativeLayout>

HorizontialListView.java

package com.example;

import java.util.LinkedList;
import java.util.Queue;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.Scroller;

public class HorizontialListView extends AdapterView<ListAdapter> {

    public boolean mAlwaysOverrideTouch = true;
    protected ListAdapter mAdapter;
    private int mLeftViewIndex = -1;
    private int mRightViewIndex = 0;
    protected int mCurrentX;
    protected int mNextX;
    private int mMaxX = Integer.MAX_VALUE;
    private int mDisplayOffset = 0;
    protected Scroller mScroller;
    private GestureDetector mGesture;
    private Queue<View> mRemovedViewQueue = new LinkedList<View>();
    private OnItemSelectedListener mOnItemSelected;
    private OnItemClickListener mOnItemClicked;
    private boolean mDataChanged = false;
   

    public HorizontialListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }   
    private synchronized void initView() {
        mLeftViewIndex = -1;
        mRightViewIndex = 0;
        mDisplayOffset = 0;
        mCurrentX = 0;
        mNextX = 0;
        mMaxX = Integer.MAX_VALUE;
        mScroller = new Scroller(getContext());
        mGesture = new GestureDetector(getContext(), mOnGesture);
    }   
    @Override
    public void setOnItemSelectedListener(AdapterView.OnItemSelectedListener listener) {
        mOnItemSelected = listener;
    }   
    @Override
    public void setOnItemClickListener(AdapterView.OnItemClickListener listener){
        mOnItemClicked = listener;
    }   
    private DataSetObserver mDataObserver = new DataSetObserver() {
        @Override
        public void onChanged() {
            synchronized(HorizontialListView.this){
                mDataChanged = true;
            }
            invalidate();
            requestLayout();
        }
        @Override
        public void onInvalidated() {
            reset();
            invalidate();
            requestLayout();
        }
       
    };
    @Override
    public ListAdapter getAdapter() {
        return mAdapter;
    }
    @Override
    public View getSelectedView() {
        //TODO: implement
        return null;
    }
    @Override
    public void setAdapter(ListAdapter adapter) {
        if(mAdapter != null) {
            mAdapter.unregisterDataSetObserver(mDataObserver);
        }
        mAdapter = adapter;
        mAdapter.registerDataSetObserver(mDataObserver);
        reset();
    }   
    private synchronized void reset(){
        initView();
        removeAllViewsInLayout();
        requestLayout();
    }
    @Override
    public void setSelection(int position) {
      
    }   
    private void addAndMeasureChild(final View child, int viewPos) {
        LayoutParams params = child.getLayoutParams();
        if(params == null) {
            //params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        }
        addViewInLayout(child, viewPos, params, true);
        child.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST),
                MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST));
    }
    @SuppressLint("DrawAllocation")
    @Override
    protected synchronized void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

        if(mAdapter == null){
            return;
        }       
        if(mDataChanged){
            int oldCurrentX = mCurrentX;
            initView();
            removeAllViewsInLayout();
            mNextX = oldCurrentX;
            mDataChanged = false;
        }
        if(mScroller.computeScrollOffset()){
            int scrollx = mScroller.getCurrX();
            mNextX = scrollx;
        }       
        if(mNextX < 0){
            mNextX = 0;
            mScroller.forceFinished(true);
        }
        if(mNextX > mMaxX) {
            mNextX = mMaxX;
            mScroller.forceFinished(true);
        }       
        int dx = mCurrentX - mNextX;
       
        removeNonVisibleItems(dx);
        fillList(dx);
        positionItems(dx);       
        mCurrentX = mNextX;

               if(!mScroller.isFinished()){
            post(new Runnable(){
                public void run() {
                    requestLayout();
                }
            });
           
        }
    }   
    private void fillList(final int dx) {
        int edge = 0;
        View child = getChildAt(getChildCount()-1);
        if(child != null) {
            edge = child.getRight();
        }
        fillListRight(edge, dx);       
        edge = 0;
        child = getChildAt(0);
        if(child != null) {
            edge = child.getLeft();
        }
        fillListLeft(edge, dx);               
    }   
    private void fillListRight(int rightEdge, final int dx) {
        while(rightEdge + dx < getWidth() && mRightViewIndex < mAdapter.getCount()) {
           
            View child = mAdapter.getView(mRightViewIndex, mRemovedViewQueue.poll(), this);
            addAndMeasureChild(child, -1);
            rightEdge += child.getMeasuredWidth();
           
            if(mRightViewIndex == mAdapter.getCount()-1){
                mMaxX = mCurrentX + rightEdge - getWidth();
            }
            mRightViewIndex++;
        }       
    }   
    private void fillListLeft(int leftEdge, final int dx) {
        while(leftEdge + dx > 0 && mLeftViewIndex >= 0) {
            View child = mAdapter.getView(mLeftViewIndex, mRemovedViewQueue.poll(), this);
            addAndMeasureChild(child, 0);
            leftEdge -= child.getMeasuredWidth();
            mLeftViewIndex--;
            mDisplayOffset -= child.getMeasuredWidth();
        }
    }   
    private void removeNonVisibleItems(final int dx) {
        View child = getChildAt(0);
        while(child != null && child.getRight() + dx <= 0) {
            mDisplayOffset += child.getMeasuredWidth();
            mRemovedViewQueue.offer(child);
            removeViewInLayout(child);
            mLeftViewIndex++;
            child = getChildAt(0);           
        }       
        child = getChildAt(getChildCount()-1);
        while(child != null && child.getLeft() + dx >= getWidth()) {
            mRemovedViewQueue.offer(child);
            removeViewInLayout(child);
            mRightViewIndex--;
            child = getChildAt(getChildCount()-1);
        }
    }   
    private void positionItems(final int dx) {
        if(getChildCount() > 0){
            mDisplayOffset += dx;
            int left = mDisplayOffset;
            for(int i=0;i<getChildCount();i++){
                View child = getChildAt(i);
                int childWidth = child.getMeasuredWidth();
                child.layout(left, 0, left + childWidth, child.getMeasuredHeight());
                left += childWidth;
            }
        }
    }   
    public synchronized void scrollTo(int x) {
        mScroller.startScroll(mNextX, 0, x - mNextX, 0);
        requestLayout();
    }
   
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        boolean handled = mGesture.onTouchEvent(ev);
        return handled;
    }   
    protected boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) {
        synchronized(HorizontialListView.this){
            mScroller.fling(mNextX, 0, (int)-velocityX, 0, 0, mMaxX, 0, 0);
        }
        requestLayout();
       
        return true;
    }   
    protected boolean onDown(MotionEvent e) {
        mScroller.forceFinished(true);
        return true;
    }
    private OnGestureListener mOnGesture = new GestureDetector.SimpleOnGestureListener() {

        @Override
        public boolean onDown(MotionEvent e) {
            return HorizontialListView.this.onDown(e);
        }
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) {
            return HorizontialListView.this.onFling(e1, e2, velocityX, velocityY);
        }
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                float distanceX, float distanceY) {
           
            synchronized(HorizontialListView.this){
                mNextX += (int)distanceX;
            }
            requestLayout();
           
            return true;
        }
        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            Rect viewRect = new Rect();
            for(int i=0;i<getChildCount();i++){
                View child = getChildAt(i);
                int left = child.getLeft();
                int right = child.getRight();
                int top = child.getTop();
                int bottom = child.getBottom();
                viewRect.set(left, top, right, bottom);
                if(viewRect.contains((int)e.getX(), (int)e.getY())){
                    if(mOnItemClicked != null){
                        mOnItemClicked.onItemClick(HorizontialListView.this, child, mLeftViewIndex + 1 + i, mAdapter.getItemId( mLeftViewIndex + 1 + i ));
                    }
                    if(mOnItemSelected != null){
                        mOnItemSelected.onItemSelected(HorizontialListView.this, child, mLeftViewIndex + 1 + i, mAdapter.getItemId( mLeftViewIndex + 1 + i ));
                    }
                    break;
                }               
            }
            return true;
        }                       
    };   
}

How to GPS ON and OFF programatically in Android


toggle = (ToggleButton) findViewById(R.id.btn_gps_on_off);
        toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {

                if (isChecked) {
                   turnGPSOn();
                  
                } else {
                    turnGPSOff();
                 }
            }
        });

// turnGPSOn use this method 

public void turnGPSOn() {
        Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
        intent.putExtra("enabled", true);
        this.context.sendBroadcast(intent);

        String provider = Settings.Secure.getString(
                context.getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if (!provider.contains("gps")) { // if gps is disabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings",
                    "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3"));
            this.context.sendBroadcast(poke);

        }
    }

// turnGPSOff use this method

public void turnGPSOff() {
        Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
        intent.putExtra("disabled", false);
        this.context.sendBroadcast(intent);

        String provider = Settings.Secure.getString(
                context.getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if (!provider.contains("gps")) { // if gps is disabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings",
                    "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3"));
            this.context.sendBroadcast(poke);

        }
    }

Android XML Parsing Tutorial


 MainActivity.java

 package com.example.simplexmlparsing;

import android.content.Context;
import android.view.Menu;

public class MainActivity extends Activity {

    public static void responces(Context conn,ArrayList<Datalist> arr){                       
    }   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
               
       int no=1;
       WebAPIHelper webAPIHelper = new WebAPIHelper(no, con,"Please wait");
       webAPIHelper.execute("your xml url type");
    }
}

WebAPIHelper.java

package com.example.simplexmlparsing;

import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public class WebAPIHelper extends AsyncTask<String, Integer, Long> {
    private ProgressDialog progressDlg;

    private Document response;
    private int requestNumber;
    private String loadingMessage;
    Context con;
    private WebAPIRequest webAPIRequest = new WebAPIRequest();

    public WebAPIHelper() {

    }

    public WebAPIHelper(int requestNumber, Context context, String msg) {
        con = context;
        progressDlg = new ProgressDialog(con);
        this.requestNumber = requestNumber;
        loadingMessage = msg;
    }

    protected void onPreExecute() {
        // if(loadingMessage!="")
        // {
        progressDlg.setMessage(loadingMessage);
        progressDlg.show();
        // }
    }

    protected Long doInBackground(String... urls) {
        response = webAPIRequest.performGet(urls[0]);
        return null;
    }

    protected void onPostExecute(Long i) {

        if (requestNumber == 1) {
           
            ArrayList<Datalist> NOtification_List = null;
           
            if (response != null) {
               
                Element node = (Element) response.getElementsByTagName("root").item(0);
                NodeList nlist = node.getElementsByTagName("result");
               
                for (int j = 0; j < nlist.getLength(); j++) {
                   
                    if (NOtification_List == null) {
                       
                        NOtification_List = new ArrayList<Datalist>();
                    }
                   
                    Datalist datalist = new Datalist();
                    Element childNode = (Element) nlist.item(j);

                    datalist.name= getValueFromNode(childNode,"Element name");
                   
                    NOtification_List.add(datalist);

                }
            }    
        }       
        progressDlg.dismiss();
    }

    String getValueFromNode(Element childNode, String tagName) {
        String strValue = "";
        try {
            Element node = (Element) childNode.getElementsByTagName(tagName)
                    .item(0);
            for (int i = 0; i < node.getChildNodes().getLength(); i++) {
                strValue = strValue.concat(node.getChildNodes().item(i)
                        .getNodeValue());
            }
        } catch (Exception exp) {
        }
        return strValue;
    }

    int parseIntValue(String strValue) {
        int value = 0;
        if (strValue != null && strValue.length() > 0) {
            value = Integer.parseInt(strValue);
        }
        return value;
    }

    double parseDoubleValue(String strValue) {
        double value = 0.0;
        if (strValue != null && strValue.length() > 0) {
            // value = Float.parseFloat(strValue);
            value = Double.parseDouble(strValue);
        }
        return value;
    }
}

Datalist.java

package com.example.simplexmlparsing;
public class Datalist {
   
    public String  name;
  
}

WebAPIRequest.java


package com.example.simplexmlparsing;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class WebAPIRequest{
    public Document performGet(String url)
    {
        Document doc = null;
        try
        {
            DefaultHttpClient client = new DefaultHttpClient();
            //URI uri = new URI(url.replaceAll(' ', '%20'));

            URI uri = new URI(url);
           
            HttpGet method = new HttpGet(uri);
            HttpResponse res = client.execute(method);
            InputStream data = res.getEntity().getContent();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse(data);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (URISyntaxException e)
        {
            // TODO Auto-generated catch block
            //e.printStackTrace();
             }
             catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }               
        return doc;
    }
}

XMLParser.java

 package com.example.simplexmlparsing;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class XMLParser {

    // constructor
    public XMLParser() {

    }
    public String getXmlFromUrl(String url) {
        String xml = null;

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
        return xml;
    }
       public Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is);

            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }

            return doc;
    }
     public final String getElementValue( Node elem ) {
         Node child;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                     if( child.getNodeType() == Node.TEXT_NODE  ){
                         return child.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }
        public String getValue(Element item, String str) {      
            NodeList n = item.getElementsByTagName(str);      
            return this.getElementValue(n.item(0));
        }
}




Android JSON Parsing Tutorial


Datalist.java

package com.example.simplejsonparsing;

public class Datalist {   
    public String name;
}

JSONfunctions.java

package com.example.simplejsonparsing;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
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.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONfunctions
{
    public static JSONObject getJSONfromURL(String url)
    {
        InputStream is = null;
        String result = null ;
        JSONObject jArray = null;
        try
        {
                HttpClient httpclient = new DefaultHttpClient();
                HttpGet httpget= new HttpGet(url);
                HttpResponse response = httpclient.execute(httpget);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
        }
        catch(Exception e)
        {
                Log.e("log_tag", "Error in http connection "+e.toString());
        }
        try
        {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");     
                }
                is.close();
                result=sb.toString();
        }
        catch(Exception e)
        {
            Log.e("log_tag", "Error converting result "+e.toString());
        }
        try
        {          
             jArray = new JSONObject(result);                                                   
        }
        catch(JSONException e)
        {
                Log.e("jArray................", "Error parsing data "+e.toString());
        }
   
       return jArray;
    }
}

 MainActivity.java

 package com.example.simplejsonparsing;

import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;

public class MainActivity extends Activity {

    public static void responces(Context conn,ArrayList<Datalist> arr){                       
    }   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
               
        int no=1;
        String url="your json url type;
        new search(MainActivity.this,url,no).execute();
    }
}

 search.java

 package com.example.simplejsonparsing;

import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public class search extends AsyncTask < String , Integer , Long > {

     private ProgressDialog      progressDialog;
        private Context             targetCtx ;
        public JSONObject json;
     
         Context conn;
        
         ArrayList<Datalist> arry_networkdata=null;
               
         String url_data;
         int no,status;

         public search ( Context context,String data,int no) {
                this.targetCtx = context ;
                conn=context;               
                url_data=data;
                this.no=no;              
                progressDialog = new ProgressDialog ( targetCtx ) ;
                progressDialog.setCancelable ( false ) ;
                progressDialog.setMessage ( "Please wait..." ) ;
                progressDialog.setIndeterminate ( true ) ;                      
         }        
         public search ( Context context,String data,int no,int status) {
                this.targetCtx = context ;
                conn=context;               
                url_data=data;
                this.no=no;
                this.status=status;
                progressDialog = new ProgressDialog ( targetCtx ) ;
                progressDialog.setCancelable ( false ) ;
                progressDialog.setMessage ( "Please wait..." ) ;
                progressDialog.setIndeterminate ( true ) ;                      
         }        
         @Override
            protected void onPreExecute ( ) {
                         
                progressDialog.show () ;              
            }
            @Override
            protected Long doInBackground (String ... params) {
             
                 json=JSONfunctions.getJSONfromURL(url_data);
                 return null ;
            }
            @SuppressWarnings("static-access")
            @ Override
            protected void onPostExecute ( Long result ) {
              
                if(no==1){
try {
                           JSONObject tempp=json.getJSONObject("responseData");
                           JSONArray event_json=tempp.getJSONArray("results");
                          
                           for(int i=0;i<event_json.length();i++)
                            {    
                            
                            if(arry_networkdata == null)
                         {
                                arry_networkdata = new ArrayList<Datalist>();
                         }
                            Datalist con=new Datalist();
               
                 JSONObject temp= event_json.getJSONObject(i);
                
                 con.name=temp.getString("name");

                 arry_networkdata.add(con);
                                
                                     }
                                                      
                   MainActivity.responces(conn, arry_networkdata);
                                                                  
                    } catch (JSONException e) {
                                           
                        e.printStackTrace();
                    }
                    }               
                progressDialog.dismiss ( ) ;
            } 
}

Wednesday, 9 April 2014

how to download pdf and read in android


MainActivity

package com.example;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView tv_loading;
    String dest_file_path = "test.pdf";
    int downloadedSize = 0, totalsize;
    String download_file_url = "your url";
    float per = 0;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv_loading = new TextView(this);
        setContentView(tv_loading);
        tv_loading.setGravity(Gravity.CENTER);
        tv_loading.setTypeface(null, Typeface.BOLD);
        downloadAndOpenPDF();
    }
    void downloadAndOpenPDF() {
        new Thread(new Runnable() {
            public void run() {
                Uri path = Uri.fromFile(downloadFile(download_file_url));
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(path, "application/pdf");
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    finish();
                } catch (ActivityNotFoundException e) {
                    tv_loading
                            .setError("PDF Reader application is not installed in your device");
                }
            }
        }).start();  
    }
    File downloadFile(String dwnload_file_path) {
        File file = null;
        try {

            URL url = new URL(dwnload_file_path);
            HttpURLConnection urlConnection = (HttpURLConnection) url                  .openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            urlConnection.connect();
           
            File SDCardRoot = Environment.getExternalStorageDirectory();         
            file = new File(SDCardRoot, dest_file_path);
            FileOutputStream fileOutput = new FileOutputStream(file);    
            InputStream inputStream = urlConnection.getInputStream();
            totalsize = urlConnection.getContentLength();
            setText("Starting PDF download...");
            byte[] buffer = new byte[1024 * 1024];
            int bufferLength = 0;
            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutput.write(buffer, 0, bufferLength);
                downloadedSize += bufferLength;
                per = ((float) downloadedSize / totalsize) * 100;
                setText("Total PDF File size  : "
                        + (totalsize / 1024)
                        + " KB\n\nDownloading PDF " + (int) per
                        + "% complete");
            }        
            fileOutput.close();
            setText("Complete. Open PDF Application installed in the device.");
        } catch (final MalformedURLException e) {
            setTextError("Some error occured. Press back",Color.RED);
        } catch (final IOException e) {
            setTextError("Some error occured. Press back and try again.",
                    Color.RED);
        } catch (final Exception e) {
            setTextError("Failed to download image. Please internet connection.",Color.RED);
        }
        return file;
    }
    void setTextError(final String message, final int color) {
        runOnUiThread(new Runnable() {
            public void run() {
                tv_loading.setTextColor(color);
                tv_loading.setText(message);
            }
        });
    }
    void setText(final String txt) {
        runOnUiThread(new Runnable() {
            public void run() {
                tv_loading.setText(txt);
            }
        });
    }
}