Monday, 12 May 2014

how to implement SharedPreferences in android example


//put SharedPreferences
SharedPreferences shared = getSharedPreferences("SharedPreferences Name",MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString("0","value");
editor.putString("1","value");
editor.putString("2","value");
editor.putString("3","value");
editor.commit();
//get SharedPreferences
 SharedPreferences shared = getApplicationContext().getSharedPreferences("SharedPreferences Name",MODE_PRIVATE);
String value= (shared.getString("0", ""));
String value= (shared.getString("1", ""));
String value= (shared.getString("3", ""));

how to create side menu in android example

main.xml

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

    <!-- Menu Panel -->

    <RelativeLayout
        android:id="@+id/menuPanel"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:background="#1e232a"
        android:orientation="vertical" >

        <RelativeLayout
            android:id="@+id/Nevigstion"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="#e84c3d" >
         </RelativeLayout>

    <!-- Sliding Panel -->

    <LinearLayout
        android:id="@+id/slidingPanel"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@android:color/white"
        android:clickable="false"
        android:gravity="left"
        android:longClickable="false"
        android:orientation="vertical" >

        <RelativeLayout
            android:id="@+id/header"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="#3598db"
            android:gravity="center_vertical" >
               <ImageButton
                android:id="@+id/menuView_Button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="10dp" />
        </RelativeLayout>

        <!-- Rel_mainroot -->

        <RelativeLayout
            android:id="@+id/Rel_mainroot"
            android:layout_width="match_parent"
            android:layout_height="fill_parent" >

            <!-- Home -->

            <RelativeLayout
                android:id="@+id/rel_home"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:background="#ededed" >
            </RelativeLayout>
        </RelativeLayout>
    </LinearLayout>
</FrameLayout>

CollapseAnimation.java

import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.FrameLayout.LayoutParams;

public class CollapseAnimation extends TranslateAnimation implements TranslateAnimation.AnimationListener{
  
    private LinearLayout slidingLayout;
    int panelWidth;

    public CollapseAnimation(LinearLayout layout, int width, int fromXType, float fromXValue, int toXType,
            float toXValue, int fromYType, float fromYValue, int toYType, float toYValue) {
      
        super(fromXType, fromXValue, toXType, toXValue, fromYType, fromYValue, toYType, toYValue);
      
        //Initialize
        slidingLayout = layout;
          panelWidth = width;
        setDuration(400);
        setFillAfter( false );
        setInterpolator(new AccelerateDecelerateInterpolator());
        setAnimationListener(this);
      
        //Clear left and right margins
        LayoutParams params = (LayoutParams) slidingLayout.getLayoutParams();
             params.rightMargin = 0;
             params.leftMargin = 0;
             slidingLayout.setLayoutParams(params);
             slidingLayout.requestLayout();     
             slidingLayout.startAnimation(this);
            
    }
    public void onAnimationEnd(Animation animation) {
  
    }

    public void onAnimationRepeat(Animation animation) {
      
    }

    public void onAnimationStart(Animation animation) {
      
    }
}

 ExpandAnimation.java
 
import android.view.Gravity;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.FrameLayout.LayoutParams;

public class ExpandAnimation extends TranslateAnimation implements Animation.AnimationListener{

    private LinearLayout slidingLayout;
    int panelWidth;
  
    public ExpandAnimation(LinearLayout layout, int width, int fromXType, float fromXValue, int toXType,
            float toXValue, int fromYType, float fromYValue, int toYType, float toYValue) {
      
        super(fromXType, fromXValue, toXType, toXValue, fromYType, fromYValue, toYType, toYValue);
      
        //Initialize
        slidingLayout = layout;
        panelWidth = width;
        setDuration(400);
          setFillAfter( false );
          setInterpolator(new AccelerateDecelerateInterpolator());
          setAnimationListener(this);
          slidingLayout.startAnimation(this);
    }

    public void onAnimationEnd(Animation arg0) {
      
        //Create margin and align left
        LayoutParams params = (LayoutParams) slidingLayout.getLayoutParams();
             params.leftMargin = panelWidth;
             params.gravity = Gravity.LEFT;     
             slidingLayout.clearAnimation();
             slidingLayout.setLayoutParams(params);
             slidingLayout.requestLayout();
                  
    }

    public void onAnimationRepeat(Animation arg0) {
      
    }

    public void onAnimationStart(Animation arg0) {
      
    }
}

MainActivity.java

 public class MainActivity extends Activity implements OnClickListener {

   private static LinearLayout slidingPanel;
    private static boolean isExpanded;
    private DisplayMetrics metrics;
    private RelativeLayout headerPanel;
    private RelativeLayout menuPanel;
    private static int panelWidth;  

   FrameLayout.LayoutParams menuPanelParameters;
    FrameLayout.LayoutParams slidingPanelParameters;
    LinearLayout.LayoutParams headerPanelParameters;
    LinearLayout.LayoutParams listViewParameters;

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

        metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        panelWidth = (int) ((metrics.widthPixels) * 0.75);

        headerPanel = (RelativeLayout) findViewById(R.id.header);
        headerPanelParameters = (LinearLayout.LayoutParams) headerPanel.getLayoutParams();
        headerPanelParameters.width = metrics.widthPixels;
        headerPanel.setLayoutParams(headerPanelParameters);

        menuPanel = (RelativeLayout) findViewById(R.id.menuPanel);
        menuPanelParameters = (FrameLayout.LayoutParams) menuPanel.getLayoutParams();
        menuPanelParameters.width = panelWidth;
        menuPanel.setLayoutParams(menuPanelParameters);

        slidingPanel = (LinearLayout) findViewById(R.id.slidingPanel);
        slidingPanelParameters = (FrameLayout.LayoutParams) slidingPanel.getLayoutParams();
        slidingPanelParameters.width = metrics.widthPixels;
        slidingPanel.setLayoutParams(slidingPanelParameters);


        menuView_Button.setOnClickListener(this);

          }

@Override
    public void onClick(View v) {

 if (v == menuView_Button) {

            if (!isExpanded) {
                isExpanded = true;

                // Expand            
                new ExpandAnimation(slidingPanel, panelWidth,
                        Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 0.75f, 0, 0.0f, 0, 0.0f);
            } else {
                isExpanded = false;

                // Collapse

                new CollapseAnimation(slidingPanel, panelWidth,
                        TranslateAnimation.RELATIVE_TO_SELF, 0.75f,
                        TranslateAnimation.RELATIVE_TO_SELF, 0.0f, 0, 0.0f, 0,
                        0.0f);
            }
        }
     }
}

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));
        }
}