Friday, 6 September 2013

Xml Parsing

MainActivity.java

package com.eds.demo;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

    /** Create Object For SiteList Class */
    SitesList sitesList = null;
    int i=0,j=1,k=2;
    ImageView im1,im2,im3;
     ProgressDialog progress;
     XMLReader xr;
    /** Called when the activity is first created. */ 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
         im1=(ImageView)findViewById(R.id.image1);
         im2=(ImageView)findViewById(R.id.image2);
         im3=(ImageView)findViewById(R.id.image3);
         try {
            
             /** Handling XML */
             SAXParserFactory spf = SAXParserFactory.newInstance();
             SAXParser sp = spf.newSAXParser();
               xr = sp.getXMLReader();
             MyXMLHandler myXMLHandler = new MyXMLHandler();
             xr.setContentHandler(myXMLHandler);
        
             new Myasynch().execute();
            
            
         } catch (Exception e) {
             System.out.println("XML Pasing Excpetion = " + e);
         }
       
      
    }
    public void click(View V)
    {  
        if(i==sitesList.getWebsite().size())
        {
            i=0;
        }
       
        try {
            ++i;
            if(i==sitesList.getWebsite().size())
            {
                i=0;
            }
            im1.setImageDrawable(Drawable.createFromStream((InputStream)new URL(sitesList.getWebsite().get(i)).getContent(), "src"));
            ++j;
            if(j==sitesList.getWebsite().size())
            {
                j=0;
            }
           
            im2.setImageDrawable(Drawable.createFromStream((InputStream)new URL(sitesList.getWebsite().get(j)).getContent(), "src"));
            ++k;
            if(k==sitesList.getWebsite().size())
            {
                k=0;
            }
            im3.setImageDrawable(Drawable.createFromStream((InputStream)new URL(sitesList.getWebsite().get(k)).getContent(), "src"));
           
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }

    class Myasynch extends AsyncTask<Void, Void, Void> {

        ProgressDialog progress;
        InputStream ins;
        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            progress.cancel();
          //  Toast.makeText(getApplicationContext(),imageName,10000).show();
            sitesList = MyXMLHandler.sitesList;
            try {
                im1.setImageDrawable(Drawable.createFromStream((InputStream)new URL(sitesList.getWebsite().get(0)).getContent(), "src"));
                im2.setImageDrawable(Drawable.createFromStream((InputStream)new URL(sitesList.getWebsite().get(1)).getContent(), "src"));
                im3.setImageDrawable(Drawable.createFromStream((InputStream)new URL(sitesList.getWebsite().get(2)).getContent(), "src"));
               
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
          
           Toast.makeText(getApplicationContext(), sitesList.getWebsite().get(1),20000).show();
                    super.onPostExecute(result);
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            progress = ProgressDialog.show(MainActivity.this,
                    "", "Searching....");
            progress.setCancelable(true);
            super.onPreExecute();
        }
        
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            HttpClient http_client = new DefaultHttpClient();

            HttpGet get = new HttpGet("http://clientextranet.in/android/android_test.php");

            try {
                HttpResponse response = http_client.execute(get);

                ins = response.getEntity().getContent();
               
                xr.parse(new InputSource(ins));

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

       

    }

}
MyXMLHandler.jav:-

package com.eds.demo;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class MyXMLHandler extends DefaultHandler {

    Boolean currentElement = false;
    String currentValue = null;
    public static SitesList sitesList = null;
    public static SitesList getSitesList()
    {
        return sitesList;
    }
   
    public static void setSitesList(SitesList sitesList)
    {
        MyXMLHandler.sitesList = sitesList;
    }
    /** Called when tag starts ( ex:- <name>AndroidPeople</name>
    * -- <name> )*/
    @Override
    public void startElement(String uri, String localName, String qName,
                             Attributes attributes) throws SAXException
    {
        currentElement = true;
        if (localName.equals("maintag"))
        {
            /** Start */
            sitesList = new SitesList();
        }
     
    }
    /** Called when tag closing ( ex:- <name>AndroidPeople</name>
    * -- </name> )*/
    @Override
    public void endElement(String uri, String localName, String qName)
    throws SAXException
    {
        currentElement = false;
        /** set value */
        if (localName.equalsIgnoreCase("name")){
            sitesList.setName(currentValue);
        Log.d("SAGAR", "NAME "+currentValue);}
        else if (localName.equalsIgnoreCase("url"))
        {
            sitesList.setWebsite(currentValue);
        Log.d("SAGAR", "url "+currentValue);}
    }
    /** Called to get tag characters ( ex:- <name>AndroidPeople</name>
    * -- to get AndroidPeople Character ) */
    @Override
    public void characters(char[] ch, int start, int length)
    throws SAXException
    {
        if (currentElement)
        {
            currentValue = new String(ch, start, length);
            currentElement = false;
        }
    }
}

SitesList.java:-

package com.eds.demo;

import java.util.ArrayList;

/** Contains getter and setter method for varialbles  */
public class SitesList {

      /** Variables */
    private ArrayList<String> name = new ArrayList<String>();
    private ArrayList<String> website = new ArrayList<String>();
  
    /** In Setter method default it will return arraylist
    * change that to add */
    public ArrayList<String> getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name.add(name);
    }
    public ArrayList<String> getWebsite()
    {
        return website;
    }
    public void setWebsite(String website)
    {
        this.website.add(website);
    }
  

}

Wednesday, 4 September 2013

Base Activity Class Example

It’s always been a good idea to make a baseActivity in android project.

Usually one screen is represented by an activity. Suppose, you have 3 custom activity classes (i.e, you writes them) in your android project. And you extended these 3 custom activity from android.app.Activity class.

What I am suggesting is to create an activity from android.app.Activity called baseActivity and make the 3 custom activity to extend from baseActivity.

1. You can avoid code duplication of you application wise common ui tasks. Suppose you want to show progressDialog in different activities. Just write code to show a progressDialog in your baseActivity and call that method from other activity.

2. Your application menu should be consistent across different application. For example, you have a settings screen. Option menu is containing the navigation to settings screen. You should display the settings throughout the application, means regardless of activity. User want to access the settings screen from anywhere in application. This feature can be easily achieved, but you have to override onCreateOptionsMenu in each of your activity or, you can override it once in your baseActivity.

res--->menu--> menu_common.xml

menu_common.xml:- 

           
 <menu xmlns:android="http://schemas.android.com/apk/res/android" >
     <item
     android:id="@+id/menu_settings"
     android:title="setting"
     android:showAsAction="always"
     />
   <item
     android:id="@+id/menu_gallery"
     android:title="gallery"
     android:showAsAction="always"
     />

</menu>


BaseClass.java :- 


 package com.shekhar.baseclassexample;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SearchView;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class BaseClass extends Activity{
                  @Override
                protected void onCreate(Bundle savedInstanceState) {
                    // TODO Auto-generated method stub
                    super.onCreate(savedInstanceState);
                }
                  public boolean onCreateOptionsMenu(Menu menu) {
                      getMenuInflater().inflate(R.menu.menu_common, menu);
              
                      // Get the SearchView and set the searchable configuration
                      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                          SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
                          SearchView searchView = (SearchView) menu.findItem(R.id.menu_gallery).getActionView();
                          searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
                          searchView.setIconifiedByDefault(true);
                      }
              
                      return super.onCreateOptionsMenu(menu);
                  }
              
                  @Override
                  public boolean onOptionsItemSelected(MenuItem item) {
                      int itemId = item.getItemId();
              
                      if (itemId == android.R.id.home) {
                          finish();
              
                      } else if (itemId == R.id.menu_settings) {
                          startActivity(new Intent(this, Setting.class));
              
                      } else if (itemId == R.id.menu_gallery) {
                          startActivity(new Intent(this,Gallery.class));
              
                      }
              
                      return super.onOptionsItemSelected(item);
                  }
              
               
                 
}





Home.java 

package com.shekhar.baseclassexample;

import android.os.Bundle;

public class Home extends BaseClass{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
    }

}

Setting.java:- 

package com.shekhar.baseclassexample;

import android.os.Bundle;

public class Setting extends BaseClass {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.setting);
        }
}

Out-Put:- 



 

 
 

Friday, 18 January 2013

ToggleButton

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:background="#FF4000"
   
     >

    <ToggleButton
             android:id="@+id/togbtngame"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"            
              android:layout_centerVertical="true"
              android:layout_centerHorizontal="true"
             android:textOn=""
             android:textOff=""                                     
             android:background="@drawable/selector" />
            
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:id="@+id/text"
        android:layout_below="@id/togbtngame"
        android:layout_centerHorizontal="true"
        android:textSize="25dp"
        android:layout_marginTop="20dp"
        android:textColor="#000000"
        />

</RelativeLayout>
Selector.xml(InDrawable)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/on" android:state_checked="true" android:state_pressed="true"/>
    <item android:drawable="@drawable/on" android:state_checked="true" android:state_focused="false"/>
    <item android:drawable="@drawable/off" android:state_checked="false" android:state_pressed="true"/>
    <item android:drawable="@drawable/off" android:state_checked="false" android:state_focused="false"/>

</selector>
MainActivity.java
package com.shekhar;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MainActivity extends Activity {
   ToggleButton tb;
   TextView tx;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      tb=(ToggleButton)findViewById(R.id.togbtngame);
      tx=(TextView)findViewById(R.id.text);
      tb.setOnClickListener(new OnClickListener() {
       
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(tb.isChecked()){
                tx.setText("ON");
            }
            else{
                tx.setText("OFF");
            }
        }
    });
    }

   
}
OutPut...